Fixed jwt handling

This commit is contained in:
Sven Heidemann 2023-03-20 16:30:07 +01:00
parent ba1f4ee955
commit fdc9a118c8
6 changed files with 126 additions and 134 deletions

View File

@ -1,18 +1,19 @@
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LangChangeEvent, TranslateService } from '@ngx-translate/core';
import { MenuItem, PrimeNGConfig } from 'primeng/api';
import { catchError } from 'rxjs/operators';
import { AuthService } from 'src/app/services/auth/auth.service';
import { SettingsService } from 'src/app/services/settings/settings.service';
import { SpinnerService } from 'src/app/services/spinner/spinner.service';
import { ThemeService } from 'src/app/services/theme/theme.service';
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { LangChangeEvent, TranslateService } from "@ngx-translate/core";
import { MenuItem, PrimeNGConfig } from "primeng/api";
import { catchError } from "rxjs/operators";
import { AuthService } from "src/app/services/auth/auth.service";
import { SettingsService } from "src/app/services/settings/settings.service";
import { SpinnerService } from "src/app/services/spinner/spinner.service";
import { ThemeService } from "src/app/services/theme/theme.service";
import { throwError } from "rxjs";
import { SidebarService } from "../../services/sidebar/sidebar.service";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.scss"]
})
export class HeaderComponent implements OnInit {
langList: MenuItem[] = [];
@ -26,8 +27,10 @@ export class HeaderComponent implements OnInit {
private spinnerService: SpinnerService,
private settings: SettingsService,
private translateService: TranslateService,
private config: PrimeNGConfig
) { }
private config: PrimeNGConfig,
private sidebarService: SidebarService,
) {
}
ngOnInit(): void {
this.initMenuLists();
@ -38,9 +41,12 @@ export class HeaderComponent implements OnInit {
}
initUserMenuList(): void {
if (!this.authService.isLoggedIn$.value) {
return;
}
this.spinnerService.showSpinner();
const mail = this.authService.getEMailFromDecodedToken(this.authService.getDecodedToken());
this.authService.getUserByEMail(mail ?? '')
this.authService.getUserByEMail(mail ?? "")
.pipe(catchError(error => {
this.spinnerService.hideSpinner();
this.authService.logout();
@ -48,7 +54,7 @@ export class HeaderComponent implements OnInit {
}))
.subscribe(user => {
this.spinnerService.hideSpinner();
this.sidebarService.setMenu(true);
this.userMenuList = [
{
@ -59,22 +65,22 @@ export class HeaderComponent implements OnInit {
separator: true
},
{
label: this.translateService.instant('header.change_password'), command: () => {
label: this.translateService.instant("header.change_password"), command: () => {
this.changePassword();
},
icon: 'pi pi-key'
icon: "pi pi-key"
},
{
label: this.translateService.instant('header.settings'), command: () => {
label: this.translateService.instant("header.settings"), command: () => {
this.userSettings();
},
icon: 'pi pi-cog'
icon: "pi pi-cog"
},
{
label: this.translateService.instant('header.logout'), command: () => {
label: this.translateService.instant("header.logout"), command: () => {
this.logout();
},
icon: 'pi pi-sign-out'
icon: "pi pi-sign-out"
}
];
});
@ -83,17 +89,17 @@ export class HeaderComponent implements OnInit {
initMenuLists(): void {
this.langList = [
{
label: 'English', command: () => {
this.translate('en');
this.setLang('en');
},
label: "English", command: () => {
this.translate("en");
this.setLang("en");
}
},
{
label: 'Deutsch', command: () => {
this.translate('de');
this.setLang('de');
},
},
label: "Deutsch", command: () => {
this.translate("de");
this.setLang("de");
}
}
];
this.initUserMenuList();
@ -117,11 +123,11 @@ export class HeaderComponent implements OnInit {
}
changePassword(): void {
this.router.navigate(['/change-password']);
this.router.navigate(["/change-password"]);
}
userSettings(): void {
this.router.navigate(['/user-settings']);
this.router.navigate(["/user-settings"]);
}
logout(): void {
@ -130,7 +136,7 @@ export class HeaderComponent implements OnInit {
translate(lang: string) {
this.translateService.use(lang);
this.translateService.get('primeng').subscribe(res => this.config.setTranslation(res));
this.translateService.get("primeng").subscribe(res => this.config.setTranslation(res));
}
loadLang(): void {
@ -138,28 +144,26 @@ export class HeaderComponent implements OnInit {
const mail = this.authService.getEMailFromDecodedToken(token);
if (!mail) {
this.translate('en');
this.translate("en");
return;
}
let lang = localStorage.getItem(`${mail}_lang`);
if (!lang) {
lang = 'en';
lang = "en";
this.setLang(lang);
}
this.translate(lang);
}
setLang(lang: string): void {
this.authService.isUserLoggedInAsync().then(result => {
if (!result) {
return;
}
if (!this.authService.isLoggedIn$.value) {
return;
}
const token = this.authService.getDecodedToken();
const mail = this.authService.getEMailFromDecodedToken(token);
localStorage.setItem(`${mail}_lang`, lang);
});
const token = this.authService.getDecodedToken();
const mail = this.authService.getEMailFromDecodedToken(token);
localStorage.setItem(`${mail}_lang`, lang);
}
}

View File

@ -1,18 +1,18 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { catchError } from 'rxjs/operators';
import { ResetPasswordDTO } from 'src/app/models/auth/reset-password.dto';
import { AuthService } from 'src/app/services/auth/auth.service';
import { SpinnerService } from 'src/app/services/spinner/spinner.service';
import { ToastService } from 'src/app/services/toast/toast.service';
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { TranslateService } from "@ngx-translate/core";
import { catchError } from "rxjs/operators";
import { ResetPasswordDTO } from "src/app/models/auth/reset-password.dto";
import { AuthService } from "src/app/services/auth/auth.service";
import { SpinnerService } from "src/app/services/spinner/spinner.service";
import { ToastService } from "src/app/services/toast/toast.service";
import { throwError } from "rxjs";
@Component({
selector: 'app-forget-password',
templateUrl: './forget-password.component.html',
styleUrls: ['./forget-password.component.scss']
selector: "app-forget-password",
templateUrl: "./forget-password.component.html",
styleUrls: ["./forget-password.component.scss"]
})
export class ForgetPasswordComponent implements OnInit {
@ -35,19 +35,18 @@ export class ForgetPasswordComponent implements OnInit {
private route: ActivatedRoute,
private toastService: ToastService,
private translate: TranslateService
) { }
) {
}
ngOnInit(): void {
this.spinnerService.showSpinner();
this.authService.isUserLoggedInAsync().then(result => {
if (result) {
this.router.navigate(['/dashboard']);
}
if (!this.authService.isLoggedIn$.value) {
this.router.navigate(["/dashboard"]);
}
this.initForms();
this.checkResetPasswordId();
this.spinnerService.hideSpinner();
});
this.initForms();
this.checkResetPasswordId();
this.spinnerService.hideSpinner();
}
initForms(): void {
@ -62,11 +61,11 @@ export class ForgetPasswordComponent implements OnInit {
}
login(): void {
this.router.navigate(['/auth/login']);
this.router.navigate(["/auth/login"]);
}
register(): void {
this.router.navigate(['/auth/register']);
this.router.navigate(["/auth/register"]);
}
forgotPassword(): void {
@ -82,35 +81,37 @@ export class ForgetPasswordComponent implements OnInit {
this.spinnerService.hideSpinner();
return throwError(() => error);
})).subscribe(res => {
this.spinnerService.hideSpinner();
this.ready = true;
setTimeout(() => { this.router.navigate(['/dashboard']); }, 5000);
});
this.spinnerService.hideSpinner();
this.ready = true;
setTimeout(() => {
this.router.navigate(["/dashboard"]);
}, 5000);
});
}
checkResetPasswordId(): void {
const id = this.route.snapshot.params['id'];
const id = this.route.snapshot.params["id"];
if (id) {
this.resetPasswordId = id;
this.spinnerService.showSpinner();
this.authService.getEMailFromforgotPasswordId(id)
.pipe(catchError(error => {
this.spinnerService.hideSpinner();
this.router.navigate(['/auth/forgot-password']);
return throwError(() => error);
this.router.navigate(["/auth/forgot-password"]);
return throwError(() => error);
})).subscribe(email => {
this.spinnerService.hideSpinner();
if (email) {
this.emailForm.value.email = email;
} else {
this.router.navigate(['/auth/forgot-password']);
}
});
this.spinnerService.hideSpinner();
if (email) {
this.emailForm.value.email = email;
} else {
this.router.navigate(["/auth/forgot-password"]);
}
});
}
}
resetPassword(): void {
const id = this.route.snapshot.params['id'];
const id = this.route.snapshot.params["id"];
if (this.emailForm.value.password !== this.emailForm.value.passwordRepeat) {
this.repeatErrors.password = true;
return;
@ -124,14 +125,14 @@ export class ForgetPasswordComponent implements OnInit {
this.authService.resetPassword(resetPasswordDTO)
.pipe(catchError(error => {
this.router.navigate(['/auth/login']);
this.router.navigate(["/auth/login"]);
this.spinnerService.hideSpinner();
return throwError(() => error);
}))
.subscribe(resp => {
this.spinnerService.hideSpinner();
this.toastService.success(this.translate.instant('auth.forgot_password.message.reset_password'), this.translate.instant('auth.forgot_password.message.reset_password_d'));
this.router.navigate(['/auth/login']);
this.toastService.success(this.translate.instant("auth.forgot_password.message.reset_password"), this.translate.instant("auth.forgot_password.message.reset_password_d"));
this.router.navigate(["/auth/login"]);
});
}
}

View File

@ -48,16 +48,14 @@ export class LoginComponent implements OnInit {
ngOnInit(): void {
this.initLoginForm();
this.spinnerService.showSpinner();
this.authService.isUserLoggedInAsync().then(result => {
if (result) {
this.router.navigate(["/dashboard"]);
return;
}
if (this.authService.isLoggedIn$.value) {
this.router.navigate(["/dashboard"]);
return;
}
this.checkDiscordLogin();
this.resetStateFlags();
this.spinnerService.hideSpinner();
});
this.checkDiscordLogin();
this.resetStateFlags();
this.spinnerService.hideSpinner();
}
checkDiscordLogin() {

View File

@ -49,12 +49,10 @@ export class RegistrationComponent implements OnInit, OnDestroy {
private settings: SettingsService
) {
this.spinnerService.showSpinner();
this.authService.isUserLoggedInAsync().then(res => {
if (res) {
this.router.navigate(["/dashboard"]);
}
this.spinnerService.hideSpinner();
});
if (!this.authService.isLoggedIn$.value) {
this.router.navigate(["/dashboard"]);
}
this.spinnerService.hideSpinner();
}
ngOnInit(): void {

View File

@ -2,7 +2,7 @@ import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { JwtHelperService } from "@auth0/angular-jwt";
import { firstValueFrom, Observable, Subject, Subscription, throwError } from "rxjs";
import { BehaviorSubject, firstValueFrom, Observable, Subject, Subscription, throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import { AdminUpdateUserDTO } from "src/app/models/auth/admin-update-user.dto";
import { AuthRoles } from "src/app/models/auth/auth-roles.enum";
@ -23,8 +23,7 @@ import { OAuthDTO } from "../../models/auth/oauth.dto";
})
export class AuthService {
private isLoggedIn!: boolean;
isLoggedIn$ = new Subject<boolean>();
isLoggedIn$ = new BehaviorSubject<boolean>(false);
constructor(
private appsettings: SettingsService,
@ -33,9 +32,6 @@ export class AuthService {
private jwtHelper: JwtHelperService,
private spinnerService: SpinnerService
) {
this.isLoggedIn$.subscribe(value => {
this.isLoggedIn = value;
});
}
/* data requests */
@ -212,7 +208,7 @@ export class AuthService {
getDecodedToken(token: TokenDTO | undefined = undefined): { [key: string]: any } | null {
if (token) {
return this.jwtHelper.decodeToken(token.token);
return this.jwtHelper.decodeToken(token.token);
}
return this.jwtHelper.decodeToken(this.getToken().token);
@ -262,6 +258,7 @@ export class AuthService {
async isUserLoggedInAsync(): Promise<boolean> {
const token = this.getToken();
console.log(1, token);
if (!token || !token.refreshToken) {
this.isLoggedIn$.next(false);
@ -279,16 +276,12 @@ export class AuthService {
return false;
}
if (this.isLoggedIn) {
this.spinnerService.showSpinner();
const resfreshedToken = await firstValueFrom(await this.refresh(token));
this.spinnerService.hideSpinner();
if (resfreshedToken) {
this.saveToken(resfreshedToken);
return true;
}
this.spinnerService.showSpinner();
const resfreshedToken = await firstValueFrom(await this.refresh(token));
this.spinnerService.hideSpinner();
if (resfreshedToken) {
this.saveToken(resfreshedToken);
return true;
}
return false;

View File

@ -4,18 +4,18 @@ import { Themes } from "src/app/models/view/themes.enum";
import { AuthService } from "../auth/auth.service";
@Injectable({
providedIn: 'root'
providedIn: "root"
})
export class ThemeService {
themeName: string = Themes.Default;
sidebarWidth = '150px';
sidebarWidth = "150px";
isSidebarOpen = false;
themeName$ = new BehaviorSubject<string>(Themes.Default);
isSidebarOpen$ = new BehaviorSubject<boolean>(true);
sidebarWidth$ = new BehaviorSubject<string>('175px');
sidebarWidth$ = new BehaviorSubject<string>("175px");
constructor(
private authService: AuthService
@ -25,7 +25,7 @@ export class ThemeService {
});
this.isSidebarOpen$.subscribe(isSidebarOpen => {
this.isSidebarOpen = isSidebarOpen;
this.sidebarWidth$.next(isSidebarOpen ? '175px' : '75px');
this.sidebarWidth$.next(isSidebarOpen ? "175px" : "75px");
});
this.sidebarWidth$.subscribe(sidebarWidth => {
this.sidebarWidth = sidebarWidth;
@ -63,20 +63,18 @@ export class ThemeService {
return;
}
this.authService.isUserLoggedInAsync().then(result => {
if (!result) {
localStorage.setItem(`default_themeName`, Themes.Default);
this.themeName$.next(Themes.Default);
}
if (!this.authService.isLoggedIn$.value) {
localStorage.setItem(`default_themeName`, Themes.Default);
this.themeName$.next(Themes.Default);
}
const token = this.authService.getDecodedToken();
const mail = this.authService.getEMailFromDecodedToken(token);
if (mail) {
localStorage.setItem(`${mail}_themeName`, name);
}
localStorage.setItem(`default_themeName`, name);
this.themeName$.next(name);
});
const token = this.authService.getDecodedToken();
const mail = this.authService.getEMailFromDecodedToken(token);
if (mail) {
localStorage.setItem(`${mail}_themeName`, name);
}
localStorage.setItem(`default_themeName`, name);
this.themeName$.next(name);
}
loadMenu() {