Files
smartguide/webapp/src/app/shared/services/credential.service.ts
T
Mats Paul Tončik 1297f85124
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
feat(auth): started auth restructure
2026-07-03 16:56:17 +02:00

303 lines
8.5 KiB
TypeScript

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,
IdToken,
AccountProfile,
RefreshToken,
OtkResponse,
} from '../../api';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class CredentialService {
private readonly authService = inject(AuthService);
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 isValidating = signal<boolean>(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.isEffectiveSuperAdmin(),
);
public readonly effectiveOrganizationId = computed(
() => this.accessToken()?.effective_organization_id,
);
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 ?? '',
);
public readonly effectiveAccountId = computed(
() => this.accessToken()?.effective_account_id ?? '',
);
public readonly isImpersonating = computed(
() => this.realAccountId() !== this.effectiveAccountId(),
);
public readonly identityToken = signal<IdToken | undefined>(undefined);
public readonly refreshToken = signal<RefreshToken | undefined>(undefined);
public readonly accessToken = signal<AccessToken | undefined>(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<AccountProfile | undefined>(
toObservable(this.isAuthenticated).pipe(
switchMap((isAuthenticated) =>
isAuthenticated
? this.authService.getCurrentAccount()
: of<AccountProfile | undefined>(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) {
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.isValidating.set(true);
setTimeout(() => this.refreshAccessToken(id), 0);
}
}
public async requestOtk(
email: string,
password: string,
): Promise<OtkResponse> {
this.isValidating.set(true);
this.identityToken.set(undefined);
this.accessToken.set(undefined);
const otkResponse: OtkResponse = await firstValueFrom(
this.authService.requestOtk({
email: email.trim().toLowerCase(),
password,
}),
);
this.isValidating.set(false);
return otkResponse;
}
public async loginWithOtk(
accountId: string,
emailCode: string,
): Promise<void> {
const request = ++this.request;
this.isValidating.set(true);
const loginResponse = await firstValueFrom(
this.authService.login({
account_id: accountId,
email_code: emailCode.trim(),
}),
);
const idToken = loginResponse.id_token;
this.identityToken.set(idToken);
this.storeIdentityToken(idToken);
this.isValidating.set(false);
await this.getAccessToken(idToken, request);
}
public async refreshAccessToken(identityToken: IdToken) {
const request = ++this.request;
this.isValidating.set(true);
this.accessToken.set(undefined);
await this.getAccessToken(identityToken, request).catch((err) => {
if (this.request === request) {
this.clearLocalAuthState();
}
throw err;
});
this.isValidating.set(false);
}
public async impersonateAccount(accountId: string): Promise<void> {
const idToken = this.identityToken();
if (!idToken) {
throw new Error('No identity token available.');
}
const request = ++this.request;
this.isValidating.set(true);
this.accessToken.set(undefined);
await this.getAccessToken(idToken, request, accountId).catch((err) => {
if (this.request === request) {
this.clearLocalAuthState();
}
throw err;
});
this.isValidating.set(false);
}
public async stopImpersonating(): Promise<void> {
const idToken = this.identityToken();
if (!idToken) {
throw new Error('No identity token available.');
}
const request = ++this.request;
this.isValidating.set(true);
this.accessToken.set(undefined);
await this.getAccessToken(idToken, request);
this.isValidating.set(false);
}
public async logoutAccount() {
await firstValueFrom(this.authService.logout());
this.clearLocalAuthState();
}
public clearLocalAuthState(): void {
this.request += 1;
this.clearTokensFromStorage();
this.identityToken.set(undefined);
this.accessToken.set(undefined);
this.isValidating.set(false);
this.router.navigate(['/login'], { replaceUrl: true });
}
public async changePassword(
currentPassword: string,
newPassword: string,
): Promise<void> {
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<never> {
return throwError(() => new Error('Registration is temporarily disabled.'));
}
private async getAccessToken(
idToken: IdToken,
request: number,
effectiveAccountId?: string,
): Promise<void> {
if (this.request !== request) {
return;
}
const realAccountId = idToken.real_account_id;
const result: AccessResponse = await firstValueFrom(
this.authService.getAccessToken({
real_account_id: realAccountId,
effective_account_id: effectiveAccountId ?? realAccountId,
}),
);
this.accessToken.set(result.access_token);
this.refreshToken.set(result.refresh_token);
this.isValidating.set(false);
}
}