From 1297f85124a914cccfbfa1bd3c99db3a2a373adf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 3 Jul 2026 16:56:17 +0200 Subject: [PATCH] feat(auth): started auth restructure --- webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/auth.service.ts | 10 +- webapp/src/app/api/model/models.ts | 1 + webapp/src/app/api/model/otkResponse.ts | 22 + webapp/src/app/app.routes.ts | 10 + .../app/modules/account/account.component.ts | 25 +- .../modules/accounts/accounts.component.html | 189 +++----- .../modules/accounts/accounts.component.scss | 5 + .../modules/accounts/accounts.component.ts | 122 ++++- .../modules/app-login/app-login.component.ts | 137 +++--- .../app-register/app-register.component.ts | 36 +- .../app/resolvers/accounts-page.resolver.ts | 19 + webapp/src/app/shared/guards/admin.guard.ts | 51 +- .../app/shared/guards/super-admin.guard.ts | 49 +- webapp/src/app/shared/guards/user.guard.ts | 37 +- .../authentication.interceptor.ts | 125 +++-- .../app/shared/services/credential.service.ts | 447 ++++++++---------- .../ui/app-layout/app-layout.component.html | 4 +- .../ui/app-layout/app-layout.component.ts | 27 +- .../ui/app-menu/app-menu.component.html | 14 +- .../shared/ui/app-menu/app-menu.component.ts | 12 +- 21 files changed, 664 insertions(+), 679 deletions(-) create mode 100644 webapp/src/app/api/model/otkResponse.ts create mode 100644 webapp/src/app/resolvers/accounts-page.resolver.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index f9eb4ffa..bc570cfd 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -139,6 +139,7 @@ model/newsArticleDetail.ts model/newsPage.ts model/openAccess.ts model/organizationPage.ts +model/otkResponse.ts model/patentEntry.ts model/patentsByAuthorResponse.ts model/personBio.ts diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 6beb60cc..ef111294 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -41,6 +41,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco // @ts-ignore import { LoginResponse } from '../model/loginResponse'; // @ts-ignore +import { OtkResponse } from '../model/otkResponse'; +// @ts-ignore import { UpdateAccountRequest } from '../model/updateAccountRequest'; // @ts-ignore @@ -738,9 +740,9 @@ export class AuthService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (bodyRequestOtk === null || bodyRequestOtk === undefined) { throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.'); @@ -782,7 +784,7 @@ export class AuthService extends BaseService { let localVarPath = `/api/auth/v2/request-otk`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: bodyRequestOtk, diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 6876bbeb..6d485f3d 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -115,6 +115,7 @@ export * from './newsArticleDetail'; export * from './newsPage'; export * from './openAccess'; export * from './organizationPage'; +export * from './otkResponse'; export * from './patentEntry'; export * from './patentsByAuthorResponse'; export * from './personBio'; diff --git a/webapp/src/app/api/model/otkResponse.ts b/webapp/src/app/api/model/otkResponse.ts new file mode 100644 index 00000000..7d956289 --- /dev/null +++ b/webapp/src/app/api/model/otkResponse.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface OtkResponse { + /** + * The status of the one-time code (OTC) request. + */ + status: string; + /** + * The unique identifier of the account for which the OTC was requested. + */ + account_id: string; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index efc1388d..c515ba70 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -21,6 +21,7 @@ import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu- import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'; import { publicationResolver } from './resolvers/publication-resolver'; import { accountResolver } from './resolvers/account.resolver'; +import { accountsPageResolver } from './resolvers/accounts-page.resolver'; export const routes: Routes = [ { @@ -107,6 +108,15 @@ export const routes: Routes = [ import('./modules/accounts/accounts.component').then( (mod) => mod.AccountsComponent, ), + resolve: { + accountPage: accountsPageResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = ['page', 'size', 'search', 'organization_id']; + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, }, { path: 'organizations', diff --git a/webapp/src/app/modules/account/account.component.ts b/webapp/src/app/modules/account/account.component.ts index 8b3eec70..647e5a99 100644 --- a/webapp/src/app/modules/account/account.component.ts +++ b/webapp/src/app/modules/account/account.component.ts @@ -145,18 +145,19 @@ export class AccountComponent { if (!oldPassword || !newPassword) { return; } - this._credentialService - .changePassword(oldPassword, newPassword) - .subscribe({ - error: (error) => { - console.error('Error changing password:', error); - this._snackBar.open( - 'Das alte Passwort ist nicht korrekt. Bitte versuchen Sie es erneut.', - 'OK', - { duration: 7000 }, - ); - }, - }); + try { + await this._credentialService.changePassword( + oldPassword, + newPassword, + ); + } catch (error) { + console.error('Error changing password:', error); + this._snackBar.open( + 'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.', + 'OK', + { duration: 7000 }, + ); + } }, }, }, diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 6a5fdb83..f8b2263f 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -14,133 +14,64 @@ -
- - Name oder E-Mail - - - - @if (credentialService.isEffectiveSuperAdmin()) { - - Organisation - - Alle Organisationen - @for (organization of organizations; track organization.id) { - - {{ organization.name }} - - } - - - } - -
- - -
-
- -
-
- {{ total }} Accounts - @if (isLoading) { - Wird geladen... - } -
- -
- - - - - - - - - - - - - @for (account of accounts; track account.id) { - - - - - - - - - } @empty { - - - - } - -
NameE-MailOrganisationRolleStatusAktionen
- - {{ account.email }}{{ account.organization_name }} - {{ account.role | role }} - - - {{ account.deleted ? 'deleted' : 'active' }} - - -
- - - -
-
Keine Accounts gefunden.
-
- - -
+
+ + +
+ + + + + + + + + {{ row.role | role }} + + + + + {{ row.deleted ? 'deleted' : 'active' }} + + + + +
+ + + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component.scss b/webapp/src/app/modules/accounts/accounts.component.scss index 53149e49..d06f840b 100644 --- a/webapp/src/app/modules/accounts/accounts.component.scss +++ b/webapp/src/app/modules/accounts/accounts.component.scss @@ -145,3 +145,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index f02fa6da..17b62579 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -1,5 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit, inject } from '@angular/core'; +import { + Component, + OnInit, + TemplateRef, + effect, + inject, + input, + viewChild, +} from '@angular/core'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; @@ -10,9 +18,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { finalize } from 'rxjs'; -import { AccountManagementService } from '../../shared/services/account-management.service'; -import type { - AccountProfile, +import { + AccountManagementService, AccountRole, OrganizationProfile, } from '../../shared/services/account-management.service'; @@ -22,6 +29,18 @@ import type { AccountDialogResult, } from './account-dialog.component'; import { RolePipe } from '../../shared/pipes/role.pipe'; +import { + GenericColumn, + DataTableComponent, +} from '../../shared/ui/data-table/data-table.component'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { MatCardModule } from '@angular/material/card'; +import { AccountPage, AccountProfile } from '../../api'; @Component({ selector: 'app-accounts', @@ -36,6 +55,11 @@ import { RolePipe } from '../../shared/pipes/role.pipe'; MatSnackBarModule, MatDialogModule, RolePipe, + DataTableComponent, + QueryParamPaginatorComponent, + QueryParamInputComponent, + QueryParamSelectorComponent, + MatCardModule, ], templateUrl: './accounts.component.html', styleUrl: './accounts.component.scss', @@ -67,9 +91,63 @@ export class AccountsComponent implements OnInit { organizationId: new FormControl(''), }); + accountColumns: GenericColumn[] = []; + accountRoleTmp = viewChild.required>('accountRoleTmp'); + accountStatusTmp = viewChild.required>('accountStatusTmp'); + accountActionsTmp = viewChild.required>('accountActionsTmp'); + + selectorOptions: SelectorOption[] = []; + + accountPage = input.required(); + + constructor() { + effect(() => { + console.log('accountPage changed:', this.accountPage()); + }); + } + ngOnInit(): void { this.loadOrganizations(); this.loadAccounts(); + this.accountColumns = [ + { + id: 'name', + header: 'Name', + type: 'accessor', + accessorKey: 'name', + }, + { + id: 'email', + header: 'E-Mail', + type: 'accessor', + accessorKey: 'email', + }, + { + id: 'organization_name', + header: 'Organisation', + type: 'accessor', + accessorKey: 'organization_name', + }, + { + id: 'role', + header: 'Rolle', + type: 'accessor', + accessorKey: 'role', + cellTemplate: this.accountRoleTmp(), + }, + { + id: 'status', + header: 'Status', + type: 'display', + cellTemplate: this.accountStatusTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.accountActionsTmp(), + }, + ]; } protected loadAccounts(page = this.page): void { @@ -101,6 +179,10 @@ export class AccountsComponent implements OnInit { this.accountService.listOrganizations().subscribe({ next: (organizations) => { this.organizations = organizations; + this.selectorOptions = organizations.map((org) => ({ + value: org.id, + display_name: org.name, + })); }, }); } @@ -199,28 +281,24 @@ export class AccountsComponent implements OnInit { }); } - protected impersonate(account: AccountProfile): void { + protected async impersonate(account: AccountProfile): Promise { if (!this.canImpersonate(account)) { return; } - this.credentialService.impersonateAccount(account.id).subscribe({ - next: () => { - this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { - duration: 4000, - }); - this.router.navigate(['/dashboard']); - }, - error: () => { - this.snackBar.open( - 'Impersonation konnte nicht gestartet werden.', - 'OK', - { - duration: 5000, - }, - ); - }, - }); + try { + await this.credentialService.impersonateAccount(account.id); + this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { + duration: 4000, + }); + this.router.navigate(['/dashboard']); + } catch (error) { + console.error('Impersonation failed:', error); + this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', { + duration: 5000, + }); + return; + } } protected get canPageBack(): boolean { diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 7d3b0cf7..916c5a33 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -1,4 +1,4 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component, effect, OnDestroy } from '@angular/core'; import { FormControl, FormGroup, @@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input'; import { CredentialService } from '../../shared/services/credential.service'; import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; -import { finalize, Subscription } from 'rxjs'; +import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; import { HttpErrorResponse } from '@angular/common/http'; @@ -34,7 +34,7 @@ type LoginStep = 'credentials' | 'otk'; styleUrl: './app-login.component.scss', standalone: true, }) -export class AppLoginComponent implements OnInit, OnDestroy { +export class AppLoginComponent implements OnDestroy { credentialsForm = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ @@ -64,28 +64,21 @@ export class AppLoginComponent implements OnInit, OnDestroy { protected credentialService: CredentialService, protected router: Router, protected snackBar: MatSnackBar, - ) {} - - ngOnInit(): void { - this.subscription = this.credentialService.validating.subscribe( - (validating) => { - if (validating) { - this.credentialsForm.disable(); - this.otkForm.disable(); - } else { - this.credentialsForm.enable(); - this.otkForm.enable(); - this.checkEnter(); - } - }, - ); - if (!this.credentialService.validating.value) { - this.checkEnter(); - } + ) { + effect(() => { + if (this.credentialService.isValidating()) { + this.credentialsForm.disable(); + this.otkForm.disable(); + } else { + this.credentialsForm.enable(); + this.otkForm.enable(); + this.checkEnter(); + } + }); } checkEnter(): void { - if (this.credentialService.isAuthenticated.value) { + if (this.credentialService.isAuthenticated()) { this.router.navigate(['/dashboard']); } } @@ -98,7 +91,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.stopCountdown(); } - requestOtk() { + async requestOtk() { if (this.credentialsForm.invalid || this.isSubmitting) { this.credentialsForm.markAllAsTouched(); return; @@ -110,39 +103,36 @@ export class AppLoginComponent implements OnInit, OnDestroy { const email = this.credentialsForm.controls.email.value ?? ''; const password = this.credentialsForm.controls.password.value ?? ''; - this.credentialService - .requestOtk(email, password) - .pipe( - finalize(() => { - this.isSubmitting = false; - this.credentialsForm.enable(); - }), - ) - .subscribe({ - next: (accountId) => { - if (!accountId) { - return; - } - - this.accountId = accountId; - this.currentStep = 'otk'; - this.otkForm.reset(); - this.startCountdown(); - this.snackBar.open( - 'OTK-Code wurde an die E-Mail-Adresse gesendet.', - 'OK', - { - duration: 4000, - }, - ); + try { + const otkResponse = await this.credentialService.requestOtk( + email, + password, + ); + const accountId = otkResponse.account_id; + this.accountId = accountId; + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open( + 'OTK-Code wurde an die E-Mail-Adresse gesendet.', + 'OK', + { + duration: 4000, }, - error: (error: HttpErrorResponse) => { - this.credentialService.clearLocalAuthState(); - this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { - duration: 5000, - }); + ); + } catch (error: unknown) { + this.credentialService.clearLocalAuthState(); + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, }, - }); + ); + } finally { + this.isSubmitting = false; + this.credentialsForm.enable(); + } } resendCode() { @@ -153,7 +143,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.requestOtk(); } - login() { + async login() { if (this.otkForm.invalid || this.isSubmitting) { this.otkForm.markAllAsTouched(); return; @@ -178,29 +168,25 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.isSubmitting = true; this.otkForm.disable(); - const email = this.credentialsForm.controls.email.value ?? ''; const code = this.otkForm.controls.code.value ?? ''; - this.credentialService - .loginWithOtk(this.accountId, email, code) - .pipe( - finalize(() => { - this.isSubmitting = false; - this.otkForm.enable(); - }), - ) - .subscribe({ - next: () => { - this.stopCountdown(); - this.router.navigate(['/dashboard']); + try { + await this.credentialService.loginWithOtk(this.accountId, code); + this.stopCountdown(); + this.router.navigate(['/dashboard']); + } catch (error: unknown) { + this.credentialService.clearLocalAuthState(); + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, }, - error: (error: HttpErrorResponse) => { - this.credentialService.clearLocalAuthState(); - this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { - duration: 5000, - }); - }, - }); + ); + } finally { + this.isSubmitting = false; + this.otkForm.enable(); + } } editCredentials() { @@ -240,6 +226,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { } private getLoginErrorMessage(error: HttpErrorResponse): string { + console.error('Login error:', error); if (error.status === 401) { return 'E-Mail, Passwort oder OTK-Code ist ungültig.'; } diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts index d4169732..ff05c039 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -5,6 +5,7 @@ import { signal, DestroyRef, OnInit, + effect, } from '@angular/core'; import { CommonModule } from '@angular/common'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @@ -54,7 +55,7 @@ import { InstitutionsService } from '../../api'; templateUrl: './app-register.component.html', styleUrl: './app-register.component.scss', }) -export class AppRegisterComponent implements OnDestroy, OnInit { +export class AppRegisterComponent implements OnDestroy { private readonly fb = inject(FormBuilder); protected readonly credentialService = inject(CredentialService); private readonly router = inject(Router); @@ -73,42 +74,37 @@ export class AppRegisterComponent implements OnDestroy, OnInit { showPassword = false; constructor() { + effect(() => { + if (this.credentialService.isValidating()) { + this.registerForm.disable(); + } else { + this.registerForm.enable(); + this.checkEnter(); + } + }); + this.setupInstitutionAutocomplete(); } - ngOnInit(): void { - this.subscription = this.credentialService.validating.subscribe( - (validating) => { - if (validating) { - this.registerForm.disable(); - } else { - this.registerForm.enable(); - this.checkEnter(); - } - }, - ); - if (!this.credentialService.validating) { - this.checkEnter(); - } - } + ngOnDestroy(): void { this.subscription?.unsubscribe(); } checkEnter(): void { - if (this.credentialService.isAuthenticated.value) { + if (this.credentialService.isAuthenticated()) { this.router.navigate(['/dashboard']); } } submit() { if (this.registerForm.valid) { - this.credentialService.validating.next(true); + this.credentialService.isValidating.set(true); this.registerForm.disable(); this.subscription = this.credentialService .registerAccount(this.registerForm.value) .subscribe({ next: () => { - this.credentialService.validating.next(false); + this.credentialService.isValidating.set(false); this.snackBar.open( 'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.', 'OK', @@ -117,7 +113,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit { this.router.navigate(['/login']); }, error: (err) => { - this.credentialService.validating.next(false); + this.credentialService.isValidating.set(false); this.registerForm.enable(); const message = err.error?.message || diff --git a/webapp/src/app/resolvers/accounts-page.resolver.ts b/webapp/src/app/resolvers/accounts-page.resolver.ts new file mode 100644 index 00000000..1d4be85d --- /dev/null +++ b/webapp/src/app/resolvers/accounts-page.resolver.ts @@ -0,0 +1,19 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { AccountPage, AuthService } from '../api'; + +export const accountsPageResolver: ResolveFn = (route, state) => { + const page = Number(route.queryParamMap.get('page') ?? '0'); + const size = Number(route.queryParamMap.get('size') ?? '10'); + const search = route.queryParamMap.get('search') || undefined; + const organizationId = + route.queryParamMap.get('organization_id') || undefined; + + return inject(AuthService).listAccounts( + page, + size, + undefined, + search, + organizationId, + ); +}; diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index 55e18ca8..a8876ced 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -1,35 +1,36 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const adminGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - switchMap(() => { - if ( - !credentialService.isEffectiveSuperAdmin() && - !credentialService.isEffectiveAdmin() - ) { - void router.navigate(['/dashboard']); - return of(false); - } + ref.destroy(); - return of(true); - }), - catchError(() => of(false)), - ); - }), - ); + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + if (!credentialService.isEffectiveAdmin()) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/super-admin.guard.ts b/webapp/src/app/shared/guards/super-admin.guard.ts index b1936483..993f00a5 100644 --- a/webapp/src/app/shared/guards/super-admin.guard.ts +++ b/webapp/src/app/shared/guards/super-admin.guard.ts @@ -1,31 +1,36 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const superAdminGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - switchMap(() => { - if (!credentialService.isEffectiveSuperAdmin()) { - void router.navigate(['/dashboard']); - return of(false); - } - return of(true); - }), - catchError(() => of(false)), - ); - }), - ); + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + if (!credentialService.isEffectiveSuperAdmin()) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index 190780ae..7145e5ea 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -1,25 +1,30 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, map, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const userGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - map(() => true), - catchError(() => of(false)), - ); - }), - ); + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 130e6c94..194799a2 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -1,86 +1,73 @@ -import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; +import { + HttpErrorResponse, + HttpInterceptorFn, + HttpRequest, +} from '@angular/common/http'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; -import { MatSnackBar } from '@angular/material/snack-bar'; -import { catchError, switchMap, tap, throwError } from 'rxjs'; +import { catchError, throwError } from 'rxjs'; import { CredentialService } from '../services/credential.service'; -import { UiFocusService } from '../services/ui-focus.service'; + +const UNAUTHENTICATED_POST_ENDPOINTS = [ + '/api/auth/v2/request-otk', + '/api/auth/v2/login', + '/institutions/autocomplete', +]; + +const isUnauthenticatedPostRequest = (req: any) => { + const url = req.url.split('?')[0]; + return ( + req.method === 'POST' && + UNAUTHENTICATED_POST_ENDPOINTS.some((endpoint) => url.endsWith(endpoint)) + ); +}; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { const url = req.url.split('?')[0]; - const uiFocusService = inject(UiFocusService); - const isPublicAuthRequest = - req.method === 'POST' && - (url.endsWith('/api/auth/v2/request-otk') || - url.endsWith('/api/auth/v2/login') || - url.endsWith('/api/auth/v2/access') || - url.endsWith('/api/auth/v2/refresh')); - - if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) { + if (isUnauthenticatedPostRequest(req)) { return next(req); } const credentialService = inject(CredentialService); const router = inject(Router); - const snackBar = inject(MatSnackBar); - const tokenProvider = credentialService.getBearerToken(); - const isLogoutRequest = url.endsWith('/api/auth/v2/logout'); - return tokenProvider.pipe( - switchMap((response) => { - if (response == undefined) { - credentialService.clearLocalAuthState(); + if (!credentialService.isActiveIdentityToken()) { + void router.navigate(['/login']); + return throwError(() => new Error('No valid identity token')); + } + const idToken = credentialService.identityToken(); + let bearerToken: string; + if (url.endsWith('/api/auth/v2/access')) { + bearerToken = idToken?.raw_token ?? ''; + } else { + if (!credentialService.isActiveAccessToken()) { + credentialService.refreshAccessToken(idToken!); + } + const accessToken = credentialService.accessToken(); + if (!accessToken) { + void router.navigate(['/login']); + return throwError(() => new Error('No valid access token')); + } + return next(attachToken(req, accessToken.raw_token)); + } + const authorizedRequest = req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + bearerToken), + }); - snackBar.open( - 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/login']); - - return throwError( - () => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), - ); - } - - const authorizedRequest = req.clone({ - headers: req.headers.set('Authorization', 'Bearer ' + response), - }); - - return next(authorizedRequest).pipe( - catchError((error: HttpErrorResponse) => { - if (error.status === 401 && !isLogoutRequest) { - return credentialService.handleUnauthorized().pipe( - tap((result) => { - uiFocusService.blurActiveElement(); - - if (result === 'stopped-impersonating') { - snackBar.open( - 'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/accounts']); - } else if (result === 'logged-out') { - snackBar.open( - 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/login']); - } - }), - switchMap(() => throwError(() => error)), - ); - } - - return throwError(() => error); - }), - ); + return next(authorizedRequest).pipe( + catchError((error: HttpErrorResponse) => { + console.error('Authentication error:', error); + return throwError(() => error); }), ); }; + +const attachToken = ( + req: HttpRequest, + token: string, +): HttpRequest => { + return req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + token), + }); +}; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index f276073c..e578e992 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,56 +1,50 @@ -import { Injectable, computed, inject, signal } from '@angular/core'; -import { filter, take, map, catchError, finalize } from 'rxjs/operators'; -import { - BehaviorSubject, - Observable, - of, - switchMap, - tap, - throwError, -} from 'rxjs'; +import { Injectable, computed, effect, inject, signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { firstValueFrom, Observable, of, switchMap, throwError } from 'rxjs'; import { AccessResponse, AccessToken, AuthService, - Configuration, IdToken, - LoginResponse, AccountProfile, + RefreshToken, + OtkResponse, } from '../../api'; -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import { Router } from '@angular/router'; -type LogoutResult = 'logged-out' | 'stopped-impersonating'; -type UnauthorizedRecoveryResult = - | 'logged-out' - | 'stopped-impersonating' - | 'already-handling'; +import { Router } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class CredentialService { private readonly authService = inject(AuthService); - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - private handlingUnauthorized = false; - private static readonly KEY_GRANT = 'grant'; + private static readonly KEY_IDENTITY_TOKEN = 'identity_token'; + private static readonly KEY_REFRESH_TOKEN = 'refresh_token'; + private static readonly KEY_ACCESS_TOKEN = 'access_token'; - public readonly validating = new BehaviorSubject(false); - public readonly isAuthenticated = new BehaviorSubject(false); + public readonly isValidating = signal(false); + public readonly isAuthenticated = computed( + () => this.accessToken() !== undefined, + ); public readonly isEffectiveSuperAdmin = computed( () => this.accessToken()?.effective_role === 'SUPER_ADMIN', ); public readonly isEffectiveAdmin = computed( - () => this.accessToken()?.effective_role === 'ADMIN', + () => + this.accessToken()?.effective_role === 'ADMIN' || + this.isEffectiveSuperAdmin(), ); public readonly effectiveOrganizationId = computed( () => this.accessToken()?.effective_organization_id, ); - public readonly login = new BehaviorSubject(''); - public readonly email = new BehaviorSubject(''); - public readonly organizationName = new BehaviorSubject(''); + public readonly login = computed( + () => this.accountProfile()?.name ?? this.accountProfile()?.email ?? '', + ); + public readonly email = computed(() => this.accountProfile()?.email ?? ''); + public readonly organizationName = computed( + () => this.accountProfile()?.organization_name ?? '', + ); public readonly realAccountId = computed( () => this.accessToken()?.real_account_id ?? '', @@ -62,298 +56,247 @@ export class CredentialService { () => this.realAccountId() !== this.effectiveAccountId(), ); - private readonly identityToken = signal(undefined); - private readonly accessToken = signal(undefined); + public readonly identityToken = signal(undefined); + public readonly refreshToken = signal(undefined); + public readonly accessToken = signal(undefined); + + public readonly isActiveIdentityToken = computed(() => { + const idToken = this.identityToken(); + return ( + idToken !== undefined && + new Date(idToken.expires_at).getTime() >= Date.now() + ); + }); + + public readonly isActiveAccessToken = computed(() => { + const accessToken = this.accessToken(); + return ( + accessToken !== undefined && + new Date(accessToken.expires_at).getTime() >= Date.now() + ); + }); + + public readonly accountProfile = toSignal( + toObservable(this.isAuthenticated).pipe( + switchMap((isAuthenticated) => + isAuthenticated + ? this.authService.getCurrentAccount() + : of(undefined), + ), + ), + { initialValue: undefined }, + ); private request = 0; + loadTokensFromStorage(): void { + const idTokenData = localStorage.getItem( + CredentialService.KEY_IDENTITY_TOKEN, + ); + const refreshTokenData = localStorage.getItem( + CredentialService.KEY_REFRESH_TOKEN, + ); + const accessTokenData = localStorage.getItem( + CredentialService.KEY_ACCESS_TOKEN, + ); + + if (idTokenData) { + this.identityToken.set(JSON.parse(idTokenData) as IdToken); + } + if (refreshTokenData) { + this.refreshToken.set(JSON.parse(refreshTokenData) as RefreshToken); + } + if (accessTokenData) { + this.accessToken.set(JSON.parse(accessTokenData) as AccessToken); + } + } + + storeIdentityToken(idToken: IdToken): void { + this.identityToken.set(idToken); + localStorage.setItem( + CredentialService.KEY_IDENTITY_TOKEN, + JSON.stringify(idToken), + ); + } + + storeRefreshToken(refreshToken: RefreshToken): void { + this.refreshToken.set(refreshToken); + localStorage.setItem( + CredentialService.KEY_REFRESH_TOKEN, + JSON.stringify(refreshToken), + ); + } + + storeAccessToken(accessToken: AccessToken): void { + this.accessToken.set(accessToken); + localStorage.setItem( + CredentialService.KEY_ACCESS_TOKEN, + JSON.stringify(accessToken), + ); + } + + clearTokensFromStorage(): void { + localStorage.removeItem(CredentialService.KEY_IDENTITY_TOKEN); + localStorage.removeItem(CredentialService.KEY_REFRESH_TOKEN); + localStorage.removeItem(CredentialService.KEY_ACCESS_TOKEN); + } + constructor(private readonly router: Router) { - const data = localStorage.getItem(CredentialService.KEY_GRANT); - const id = data ? (JSON.parse(data) as AccessToken) : undefined; + this.loadTokensFromStorage(); + effect(() => { + console.log('IdToken', this.identityToken()); + console.log('RefreshToken', this.refreshToken()); + console.log('AccessToken', this.accessToken()); + }); + const id = this.identityToken(); if (id && new Date(id.expires_at).getTime() >= Date.now()) { - this.identityToken.set(id); - this.validating.next(true); + this.isValidating.set(true); setTimeout(() => this.refreshAccessToken(id), 0); } } - public validateCurrentSession(): Observable { - return this.loadCurrentProfile(); - } - - public requestOtk(email: string, password: string): Observable { - const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); + public async requestOtk( + email: string, + password: string, + ): Promise { + this.isValidating.set(true); this.identityToken.set(undefined); this.accessToken.set(undefined); - return this.authService - .requestOtk({ email: email.trim().toLowerCase(), password }) - .pipe( - map((response: { account_id?: string }) => { - if (this.request !== request) { - return ''; - } + const otkResponse: OtkResponse = await firstValueFrom( + this.authService.requestOtk({ + email: email.trim().toLowerCase(), + password, + }), + ); - return response.account_id ?? ''; - }), - finalize(() => { - if (this.request === request) { - this.validating.next(false); - } - }), - ); + this.isValidating.set(false); + return otkResponse; } - public loginWithOtk( + public async loginWithOtk( accountId: string, - email: string, emailCode: string, - ): Observable { + ): Promise { const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); + this.isValidating.set(true); - return this.authService - .login({ account_id: accountId, email_code: emailCode.trim() }) - .pipe( - switchMap((response: LoginResponse) => { - if (this.request != request) return of(undefined); + const loginResponse = await firstValueFrom( + this.authService.login({ + account_id: accountId, + email_code: emailCode.trim(), + }), + ); - const idToken = response.id_token; + const idToken = loginResponse.id_token; + this.identityToken.set(idToken); + this.storeIdentityToken(idToken); - this.identityToken.set(idToken); - localStorage.setItem( - CredentialService.KEY_GRANT, - JSON.stringify(idToken), - ); - return this.getAccessGrantForIdentity(idToken, request); - }), - ); + this.isValidating.set(false); + await this.getAccessToken(idToken, request); } - public refreshAccessToken(identityToken: IdToken) { + public async refreshAccessToken(identityToken: IdToken) { const request = ++this.request; - this.validating.next(true); + this.isValidating.set(true); this.accessToken.set(undefined); - this.getAccessGrantForIdentity(identityToken, request).subscribe({ - error: () => { - if (this.request != request) return; + + await this.getAccessToken(identityToken, request).catch((err) => { + if (this.request === request) { this.clearLocalAuthState(); - }, + } + throw err; }); + + this.isValidating.set(false); } - public impersonateAccount(accountId: string): Observable { + public async impersonateAccount(accountId: string): Promise { const idToken = this.identityToken(); if (!idToken) { - return throwError(() => new Error('No identity token available.')); + throw new Error('No identity token available.'); } const request = ++this.request; - this.validating.next(true); + this.isValidating.set(true); this.accessToken.set(undefined); - return this.getAccessGrantForIdentity(idToken, request, accountId).pipe( - tap({ error: () => this.validating.next(false) }), - ); + await this.getAccessToken(idToken, request, accountId).catch((err) => { + if (this.request === request) { + this.clearLocalAuthState(); + } + throw err; + }); + this.isValidating.set(false); } - public stopImpersonating(): Observable { + public async stopImpersonating(): Promise { const idToken = this.identityToken(); if (!idToken) { - return throwError(() => new Error('No identity token available.')); + throw new Error('No identity token available.'); } const request = ++this.request; - this.validating.next(true); + this.isValidating.set(true); this.accessToken.set(undefined); - return this.getAccessGrantForIdentity(idToken, request).pipe( - tap({ error: () => this.validating.next(false) }), - ); + await this.getAccessToken(idToken, request); + this.isValidating.set(false); } - public logoutAccount(): Observable { - const wasImpersonating = this.isImpersonating(); - - return this.authService - .logout('body', false, { transferCache: false }) - .pipe( - catchError((error) => { - console.error('Backend logout failed', error); - return of(null); - }), - switchMap(() => { - if (!wasImpersonating) { - this.clearLocalAuthState(); - return of('logged-out' as const); - } - - return this.stopImpersonating().pipe( - map(() => 'stopped-impersonating' as const), - catchError((error) => { - console.error('Stop impersonating after logout failed', error); - this.clearLocalAuthState(); - return of('logged-out' as const); - }), - ); - }), - ); + public async logoutAccount() { + await firstValueFrom(this.authService.logout()); + this.clearLocalAuthState(); } public clearLocalAuthState(): void { this.request += 1; - localStorage.removeItem(CredentialService.KEY_GRANT); + this.clearTokensFromStorage(); this.identityToken.set(undefined); this.accessToken.set(undefined); - this.isAuthenticated.next(false); - this.validating.next(false); - this.login.next(''); - this.email.next(''); - this.organizationName.next(''); + this.isValidating.set(false); this.router.navigate(['/login'], { replaceUrl: true }); } - public handleUnauthorized(): Observable { - if (this.handlingUnauthorized) { - return of('already-handling' as const); - } - - this.handlingUnauthorized = true; - - const isImpersonating = this.isImpersonating(); - const identityToken = this.identityToken(); - - const recovery$ = - isImpersonating && identityToken - ? this.stopImpersonating().pipe( - map(() => 'stopped-impersonating' as const), - catchError((error) => { - console.error('Failed to stop impersonation after 401', error); - this.clearLocalAuthState(); - return of('logged-out' as const); - }), - ) - : of(null).pipe( - tap(() => this.clearLocalAuthState()), - map(() => 'logged-out' as const), - ); - - return recovery$.pipe( - finalize(() => { - this.handlingUnauthorized = false; - }), - ); - } - - public changePassword( + public async changePassword( currentPassword: string, newPassword: string, - ): Observable { - return this.httpClient - .post( - `${this.apiBasePath}/api/auth/v2/change-password`, - { - current_password: currentPassword, - new_password: newPassword, - }, - { withCredentials: true }, - ) - .pipe( - tap(() => { - this.clearLocalAuthState(); - }), - map(() => undefined), - catchError((err) => { - throw err; - }), - ); + ): Promise { + this.isValidating.set(true); + await firstValueFrom( + this.authService.changePassword({ + current_password: currentPassword, + new_password: newPassword, + }), + ); + this.clearLocalAuthState(); + this.isValidating.set(false); } public registerAccount(_data: unknown): Observable { return throwError(() => new Error('Registration is temporarily disabled.')); } - //review: arman (generated fix) - public getBearerToken(): Observable { - const accessToken = this.accessToken(); - const identityToken = this.identityToken(); - - // 1. If we have a valid access token, return it immediately and complete. - if ( - accessToken && - Date.now() < new Date(accessToken.expires_at).getTime() - ) { - return of(accessToken.raw_token); - } - - // 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh. - if (!this.validating.value) { - if (!identityToken) { - return of(undefined); // No identity token to refresh with. - } - this.refreshAccessToken(identityToken); - } - - // 3. Wait for the validation to finish, then return the resulting token. - return this.validating.pipe( - filter((isValidating) => !isValidating), // Wait until validating becomes false - take(1), // Take exactly 1 emission and then automatically complete() - map(() => this.accessToken()?.raw_token), - ); - } - - private getAccessGrantForIdentity( + private async getAccessToken( idToken: IdToken, request: number, effectiveAccountId?: string, - ): Observable { + ): Promise { + if (this.request !== request) { + return; + } + const realAccountId = idToken.real_account_id; - const headers = new HttpHeaders({ - Authorization: `Bearer ${idToken.raw_token}`, - }); - const payload = { - real_account_id: realAccountId, - effective_account_id: effectiveAccountId ?? realAccountId, - }; - return this.httpClient - .post(`${this.apiBasePath}/api/auth/v2/access`, payload, { - headers, - withCredentials: true, - }) - .pipe( - tap((result: AccessResponse) => { - if (this.request != request) return; + const result: AccessResponse = await firstValueFrom( + this.authService.getAccessToken({ + real_account_id: realAccountId, + effective_account_id: effectiveAccountId ?? realAccountId, + }), + ); - const accessToken = result.access_token; - - this.accessToken.set(accessToken); - this.isAuthenticated.next(true); - this.validating.next(false); - }), - map(() => undefined), - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } - - private loadCurrentProfile(): Observable { - return this.httpClient - .get(`${this.apiBasePath}/api/accounts/me`, { - withCredentials: true, - }) - .pipe( - tap((profile) => { - this.login.next(profile.name ?? profile.email ?? ''); - this.email.next(profile.email ?? ''); - this.organizationName.next(profile.organization_name ?? ''); - }), - map(() => undefined), - ); + this.accessToken.set(result.access_token); + this.refreshToken.set(result.refresh_token); + this.isValidating.set(false); } } diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index f4ae841c..7be187a0 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -3,7 +3,7 @@ - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { } - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { @if (credentialService.isImpersonating()) {
switch_account diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 127f842d..bee7ed7c 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -102,22 +102,21 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.mediaQuery.removeEventListener('change', this.mediaQueryListener); } - logout() { - this.credentialService.logoutAccount().subscribe({ - next: (result) => { - if (result === 'stopped-impersonating') { - this.router.navigate(['/accounts']); - } else { - this.router.navigate(['/login']); - } - }, - }); + async logout() { + const isImpersonating = this.credentialService.isImpersonating(); + + await this.credentialService.stopImpersonating(); + + if (isImpersonating) { + this.router.navigate(['/accounts']); + } else { + this.router.navigate(['/login']); + } } - stopImpersonating(): void { - this.credentialService.stopImpersonating().subscribe({ - next: () => this.router.navigate(['/accounts']), - }); + async stopImpersonating(): Promise { + await this.credentialService.stopImpersonating(); + this.router.navigate(['/accounts']); } navigateBack() { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index b80e7271..a917f40b 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -101,13 +101,13 @@ } @else { @@ -115,13 +115,11 @@ diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 96f2bd12..8d2bea96 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -68,7 +68,7 @@ export class AppMenuComponent { icon: 'groups', route: '/persons', queryParams: { - institutionName: this.credentialService.organizationName.value, + institutionName: this.credentialService.organizationName(), }, disabled: false, }, @@ -166,14 +166,8 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAccount().subscribe({ - next: (result) => { - if (result === 'stopped-impersonating') { - this.router.navigate(['/accounts']); - } else { - this.router.navigate(['/login']); - } - }, + this.credentialService.logoutAccount().then(() => { + this.router.navigate(['/login']); }); }); }