Updated credential service to modern signal api
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Mats Paul Tončik
2026-06-27 11:57:30 +02:00
parent f951eba7e4
commit b993862afb
10 changed files with 87 additions and 126 deletions
@@ -4,7 +4,11 @@
<h1>Accounts</h1>
<p>Account-Zugänge verwalten, Rollen setzen und Impersonation starten.</p>
</div>
<button mat-flat-button color="primary" type="button" (click)="startCreate()">
<button
mat-flat-button
color="primary"
type="button"
(click)="startCreate()">
<mat-icon>person_add</mat-icon>
Neuer Account
</button>
@@ -16,7 +20,7 @@
<input matInput formControlName="search" />
</mat-form-field>
@if (credentialService.superadmin | async) {
@if (credentialService.isEffectiveSuperAdmin()) {
<mat-form-field appearance="outline">
<mat-label>Organisation</mat-label>
<mat-select formControlName="organizationId">
@@ -74,7 +78,9 @@
</td>
<td>{{ account.email }}</td>
<td>{{ account.organization_name }}</td>
<td><span class="role">{{ account.role }}</span></td>
<td>
<span class="role">{{ account.role }}</span>
</td>
<td>
<span class="status" [class.status--deleted]="account.deleted">
{{ account.deleted ? 'deleted' : 'active' }}
@@ -47,7 +47,7 @@ export class AccountsComponent implements OnInit {
private readonly dialog = inject(MatDialog);
protected get availableRoles(): AccountRole[] {
if (this.credentialService.superadmin.value) {
if (this.credentialService.isEffectiveSuperAdmin()) {
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
}
@@ -164,7 +164,8 @@ export class AccountsComponent implements OnInit {
data: {
...data,
organizations: this.organizations,
canSelectOrganization: this.credentialService.superadmin.value,
canSelectOrganization:
this.credentialService.isEffectiveSuperAdmin(),
roles: this.availableRoles,
},
});
@@ -234,12 +235,12 @@ export class AccountsComponent implements OnInit {
return false;
}
if (this.credentialService.superadmin.value) {
if (this.credentialService.isEffectiveSuperAdmin()) {
return true;
}
return (
this.credentialService.admin.value &&
this.credentialService.isEffectiveAdmin() &&
(account.role === 'MANAGER' || account.role === 'USER')
);
}
@@ -85,7 +85,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
}
checkEnter(): void {
if (this.credentialService.authenticated.value) {
if (this.credentialService.isAuthenticated.value) {
this.router.navigate(['/dashboard']);
}
}
@@ -95,7 +95,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
}
checkEnter(): void {
if (this.credentialService.authenticated.value) {
if (this.credentialService.isAuthenticated.value) {
this.router.navigate(['/dashboard']);
}
}
+3 -3
View File
@@ -11,7 +11,7 @@ export const adminGuard: CanActivateFn = () => {
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.authenticated.value) {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
@@ -19,8 +19,8 @@ export const adminGuard: CanActivateFn = () => {
return credentialService.validateCurrentSession().pipe(
switchMap(() => {
if (
!credentialService.superadmin.value &&
!credentialService.admin.value
!credentialService.isEffectiveSuperAdmin() &&
!credentialService.isEffectiveAdmin()
) {
void router.navigate(['/dashboard']);
return of(false);
+1 -1
View File
@@ -11,7 +11,7 @@ export const userGuard: CanActivateFn = () => {
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.authenticated.value) {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
@@ -1,4 +1,4 @@
import { Injectable, inject } from '@angular/core';
import { Injectable, computed, inject, signal } from '@angular/core';
import { filter, take, map, catchError, finalize } from 'rxjs/operators';
import {
BehaviorSubject,
@@ -36,57 +36,40 @@ export class CredentialService {
private static readonly KEY_GRANT = 'grant';
public readonly validating = new BehaviorSubject<boolean>(false);
public readonly authenticated = new BehaviorSubject<boolean>(false);
public readonly superadmin = new BehaviorSubject<boolean>(false);
public readonly admin = new BehaviorSubject<boolean>(false);
public readonly organization = new BehaviorSubject<string | undefined>(
undefined,
public readonly isAuthenticated = new BehaviorSubject<boolean>(false);
public readonly isEffectiveSuperAdmin = computed(
() => this.accessToken()?.effective_role === 'SUPER_ADMIN',
);
public readonly isEffectiveAdmin = computed(
() => this.accessToken()?.effective_role === 'ADMIN',
);
public readonly effectiveOrganizationId = computed(
() => this.accessToken()?.effective_organization_id,
);
public readonly login = new BehaviorSubject<string>('');
public readonly email = new BehaviorSubject<string>('');
public readonly organizationName = new BehaviorSubject<string>('');
public readonly impersonating = new BehaviorSubject<boolean>(false);
public readonly realAccountId = new BehaviorSubject<string>('');
public readonly effectiveAccountId = new BehaviorSubject<string>('');
private readonly identityToken = new BehaviorSubject<IdToken | undefined>(
undefined,
public readonly realAccountId = computed(
() => this.accessToken()?.real_account_id ?? '',
);
private readonly accessToken = new BehaviorSubject<AccessToken | undefined>(
undefined,
public readonly effectiveAccountId = computed(
() => this.accessToken()?.effective_account_id ?? '',
);
public readonly isImpersonating = computed(
() => this.realAccountId() !== this.effectiveAccountId(),
);
private readonly identityToken = signal<IdToken | undefined>(undefined);
private readonly accessToken = signal<AccessToken | undefined>(undefined);
private request = 0;
constructor() {
this.accessToken.subscribe((token: AccessToken | undefined) => {
if (token) {
this.superadmin.next(token.effective_role === 'SUPER_ADMIN');
this.admin.next(token.effective_role === 'ADMIN');
// this.login.next(token.grant.scope.a?.l ?? '');
// this.email.next(token.grant.scope.a?.e ?? '');
// this.organizationName.next(token.grant.scope.a?.on ?? '');
this.impersonating.next(
token.real_account_id !== token.effective_account_id,
);
this.realAccountId.next(token.real_account_id);
this.effectiveAccountId.next(token.effective_account_id);
} else {
this.superadmin.next(false);
this.admin.next(false);
this.login.next('');
this.email.next('');
this.organizationName.next('');
this.impersonating.next(false);
this.realAccountId.next('');
this.effectiveAccountId.next('');
}
});
const data = localStorage.getItem(CredentialService.KEY_GRANT);
const id = data ? (JSON.parse(data) as AccessToken) : undefined;
if (id && new Date(id.expires_at).getTime() >= Date.now()) {
this.identityToken.next(id);
this.identityToken.set(id);
this.validating.next(true);
setTimeout(() => this.refreshAccessToken(id), 0);
}
@@ -101,12 +84,9 @@ export class CredentialService {
public requestOtk(email: string, password: string): Observable<string> {
const request = ++this.request;
this.validating.next(true);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.admin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
this.isAuthenticated.next(false);
this.identityToken.set(undefined);
this.accessToken.set(undefined);
return this.authService
.requestOtk({ email: email.trim().toLowerCase(), password })
@@ -133,12 +113,7 @@ export class CredentialService {
): Observable<void> {
const request = ++this.request;
this.validating.next(true);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.admin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
this.isAuthenticated.next(false);
return this.authService
.login({ account_id: accountId, email_code: emailCode.trim() })
@@ -148,21 +123,7 @@ export class CredentialService {
const idToken = response.id_token;
// const token: TimedIdentityGrant = {
// accountId,
// grant: {
// token_type: 'ID',
// access_token: response.id_token.raw_token,
// expires_in: Math.max(
// new Date(response.id_token.expires_at).getTime() -
// Math.floor(Date.now() / 1000),
// 0,
// ),
// scope: this.buildIdentityScope(accountId, email),
// },
// expiration: new Date(response.id_token.expires_at).getTime(),
// };
this.identityToken.next(idToken);
this.identityToken.set(idToken);
localStorage.setItem(
CredentialService.KEY_GRANT,
JSON.stringify(idToken),
@@ -175,51 +136,47 @@ export class CredentialService {
public refreshAccessToken(identityToken: IdToken) {
const request = ++this.request;
this.validating.next(true);
this.accessToken.next(undefined);
this.accessToken.set(undefined);
this.getAccessGrantForIdentity(identityToken, request).subscribe({
error: () => {
if (this.request != request) return;
this.identityToken.next(undefined);
this.organization.next(undefined);
this.authenticated.next(false);
this.superadmin.next(false);
this.admin.next(false);
this.validating.next(false);
this.identityToken.set(undefined);
},
});
}
public impersonateAccount(accountId: string): Observable<void> {
if (!this.identityToken.value) {
const idToken = this.identityToken();
if (!idToken) {
return throwError(() => new Error('No identity token available.'));
}
const request = ++this.request;
this.validating.next(true);
this.accessToken.next(undefined);
return this.getAccessGrantForIdentity(
this.identityToken.value,
request,
accountId,
).pipe(tap({ error: () => this.validating.next(false) }));
this.accessToken.set(undefined);
return this.getAccessGrantForIdentity(idToken, request, accountId).pipe(
tap({ error: () => this.validating.next(false) }),
);
}
public stopImpersonating(): Observable<void> {
if (!this.identityToken.value) {
const idToken = this.identityToken();
if (!idToken) {
return throwError(() => new Error('No identity token available.'));
}
const request = ++this.request;
this.validating.next(true);
this.accessToken.next(undefined);
return this.getAccessGrantForIdentity(
this.identityToken.value,
request,
).pipe(tap({ error: () => this.validating.next(false) }));
this.accessToken.set(undefined);
return this.getAccessGrantForIdentity(idToken, request).pipe(
tap({ error: () => this.validating.next(false) }),
);
}
public logoutAccount(): Observable<LogoutResult> {
const wasImpersonating = this.impersonating.value;
const wasImpersonating = this.isImpersonating();
return this.authService
.logout('body', false, { transferCache: false })
@@ -249,13 +206,8 @@ export class CredentialService {
public clearLocalAuthState(): void {
this.request += 1;
localStorage.removeItem(CredentialService.KEY_GRANT);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.admin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
this.validating.next(false);
this.identityToken.set(undefined);
this.accessToken.set(undefined);
}
public handleUnauthorized(): Observable<UnauthorizedRecoveryResult> {
@@ -265,8 +217,11 @@ export class CredentialService {
this.handlingUnauthorized = true;
const isImpersonating = this.isImpersonating();
const identityToken = this.identityToken();
const recovery$ =
this.impersonating.value && this.identityToken.value
isImpersonating && identityToken
? this.stopImpersonating().pipe(
map(() => 'stopped-impersonating' as const),
catchError((error) => {
@@ -312,29 +267,30 @@ export class CredentialService {
//review: arman (generated fix)
public getBearerToken(): Observable<string | undefined> {
const accessToken = this.accessToken();
const identityToken = this.identityToken();
// 1. If we have a valid access token, return it immediately and complete.
if (
this.accessToken.value &&
Date.now() < new Date(this.accessToken.value.expires_at).getTime()
accessToken &&
Date.now() < new Date(accessToken.expires_at).getTime()
) {
return of(this.accessToken.value.raw_token);
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 (!this.identityToken.value) {
if (!identityToken) {
return of(undefined); // No identity token to refresh with.
}
this.refreshAccessToken(this.identityToken.value);
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.value ? this.accessToken.value.raw_token : undefined,
),
map(() => (accessToken ? accessToken.raw_token : undefined)),
);
}
@@ -363,9 +319,8 @@ export class CredentialService {
const accessToken = result.access_token;
this.accessToken.next(accessToken);
this.organization.next(accessToken.effective_organization_id);
this.authenticated.next(true);
this.accessToken.set(accessToken);
this.isAuthenticated.next(true);
this.validating.next(false);
}),
map(() => undefined),
@@ -3,7 +3,7 @@
<mat-drawer-container
class="drawer-container"
[autosize]="!mediaQuery.matches">
@if (credentialService.authenticated | async) {
@if (credentialService.isAuthenticated | async) {
<mat-drawer
class="drawer"
[class.drawer--collapsed]="isSidebarCollapsed()"
@@ -18,8 +18,8 @@
</mat-drawer>
}
<mat-drawer-content class="content-shell">
@if (credentialService.authenticated | async) {
@if (credentialService.impersonating | async) {
@if (credentialService.isAuthenticated | async) {
@if (credentialService.isImpersonating()) {
<div class="impersonation-banner">
<mat-icon>switch_account</mat-icon>
<span>Impersonation aktiv</span>
@@ -6,7 +6,7 @@ import {
ViewChild,
inject,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { CommonModule, Location } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
@@ -16,7 +16,6 @@ import { MediaMatcher } from '@angular/cdk/layout';
import { AppMenuComponent } from '../app-menu/app-menu.component';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CredentialService } from '../../services/credential.service';
import { Location } from '@angular/common';
import { AppSearchbarComponent } from '../app-searchbar/app-searchbar.component';
import { ResolverStateService } from '../../services/resolver-state.service';
import { LoadingComponent } from '../loading/loading.component';
@@ -52,7 +51,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
constructor(
public credentialService: CredentialService,
public router: Router,
private location: Location,
private readonly location: Location,
public changeDetector: ChangeDetectorRef,
media: MediaMatcher,
) {
@@ -44,8 +44,8 @@
@for (item of navItems; track item.label) {
@if (
!item.adminOnly ||
(credentialService.superadmin | async) ||
(credentialService.admin | async)
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin()
) {
@if (collapsed()) {
<a