414 lines
11 KiB
TypeScript
414 lines
11 KiB
TypeScript
import { Injectable, computed, effect, inject, signal } from '@angular/core';
|
|
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
|
import {
|
|
catchError,
|
|
finalize,
|
|
firstValueFrom,
|
|
map,
|
|
Observable,
|
|
of,
|
|
shareReplay,
|
|
switchMap,
|
|
tap,
|
|
throwError,
|
|
} from 'rxjs';
|
|
import {
|
|
AccessResponse,
|
|
AuthService,
|
|
AccountProfile,
|
|
OtkResponse,
|
|
IdTokenMetadata,
|
|
AccessToken,
|
|
LoginResponse,
|
|
UserRole,
|
|
} from '../../api';
|
|
|
|
import { Router } from '@angular/router';
|
|
import { HttpContext, HttpContextToken } from '@angular/common/http';
|
|
|
|
export const TOKEN_TYPE = {
|
|
ACCESS_TOKEN: 'ACCESS_TOKEN',
|
|
ID_TOKEN_COOKIE: 'ID_TOKEN_COOKIE',
|
|
REFRESH_TOKEN_COOKIE: 'REFRESH_TOKEN_COOKIE',
|
|
NONE: 'NONE',
|
|
} as const;
|
|
|
|
export type TokenContextType = (typeof TOKEN_TYPE)[keyof typeof TOKEN_TYPE];
|
|
|
|
export const REQUIRED_TOKEN_TYPE = new HttpContextToken<TokenContextType>(
|
|
() => TOKEN_TYPE.ACCESS_TOKEN,
|
|
);
|
|
|
|
const STORAGE_KEY = 'auth_state';
|
|
|
|
export const clearStoredAuthState = (): void => {
|
|
localStorage.removeItem(STORAGE_KEY);
|
|
};
|
|
|
|
export interface StoredAuthState {
|
|
idTokenMetadata: IdTokenMetadata | null;
|
|
accessToken: AccessToken | null;
|
|
}
|
|
|
|
export interface PasswordResetRequestResponse {
|
|
status: string;
|
|
reset_link_created: boolean;
|
|
rate_limited: boolean;
|
|
retry_after_seconds?: number;
|
|
}
|
|
|
|
export interface ResetPasswordResponse {
|
|
status: string;
|
|
}
|
|
|
|
const EXPIRY_SKEW_MS = 10 * 1000; // 10 seconds
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class CredentialService {
|
|
private readonly authService = inject(AuthService);
|
|
|
|
public readonly isValidating = signal<boolean>(false);
|
|
public readonly isAuthenticated = computed(
|
|
() => this.accessToken() !== undefined,
|
|
);
|
|
public readonly isEffectiveSuperAdmin = computed(
|
|
() =>
|
|
this.accessToken()?.effective_roles?.includes(UserRole.SuperAdmin) ??
|
|
false,
|
|
);
|
|
public readonly isEffectiveAdmin = computed(
|
|
() =>
|
|
this.accessToken()?.effective_roles?.includes(UserRole.Admin) ?? false,
|
|
);
|
|
public readonly isEffectiveManager = computed(
|
|
() =>
|
|
this.accessToken()?.effective_roles?.includes(UserRole.Manager) ?? false,
|
|
);
|
|
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 accessToken = signal<AccessToken | undefined>(undefined);
|
|
|
|
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.accessToken).pipe(
|
|
switchMap((accessToken) =>
|
|
accessToken
|
|
? this.authService.getCurrentAccount()
|
|
: of<AccountProfile | undefined>(undefined),
|
|
),
|
|
),
|
|
{ initialValue: undefined },
|
|
);
|
|
|
|
private refreshInFlight$: Observable<AccessToken> | null = null;
|
|
|
|
private request = 0;
|
|
|
|
constructor(private readonly router: Router) {
|
|
this.restoreAuthState();
|
|
|
|
effect(() => {
|
|
console.log('Access token changed:', this.accessToken());
|
|
});
|
|
|
|
const storedAccessToken = this.getStoredAccessToken();
|
|
if (storedAccessToken && this.isExpired(storedAccessToken)) {
|
|
this.refreshAccessToken().subscribe({
|
|
error: (err) => {
|
|
console.error('Error refreshing access token on init:', err);
|
|
this.logout();
|
|
this.router.navigate(['/login'], { replaceUrl: true });
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
private restoreAuthState(): void {
|
|
this.accessToken.set(this.getStoredAccessToken() ?? undefined);
|
|
}
|
|
|
|
private readAuthState(): StoredAuthState {
|
|
const raw = localStorage.getItem(STORAGE_KEY);
|
|
if (!raw) {
|
|
return { idTokenMetadata: null, accessToken: null };
|
|
}
|
|
try {
|
|
return JSON.parse(raw) as StoredAuthState;
|
|
} catch {
|
|
return { idTokenMetadata: null, accessToken: null };
|
|
}
|
|
}
|
|
|
|
private writeAuthState(patch: Partial<StoredAuthState>): void {
|
|
const next: StoredAuthState = {
|
|
...this.readAuthState(),
|
|
...patch,
|
|
};
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
|
}
|
|
|
|
private persistAccessToken(accessToken: AccessToken | null): void {
|
|
this.writeAuthState({ accessToken });
|
|
this.accessToken.set(accessToken ?? undefined);
|
|
}
|
|
|
|
private getStoredIdTokenMetadata(): IdTokenMetadata | null {
|
|
return this.readAuthState().idTokenMetadata;
|
|
}
|
|
|
|
private getStoredAccessToken(): AccessToken | null {
|
|
return this.readAuthState().accessToken;
|
|
}
|
|
|
|
private isExpired(token: { expires_at: string }): boolean {
|
|
return new Date(token.expires_at).getTime() < Date.now() + EXPIRY_SKEW_MS;
|
|
}
|
|
|
|
public accessTokenIsExpired(): boolean {
|
|
const accessToken = this.getStoredAccessToken();
|
|
return !accessToken || this.isExpired(accessToken);
|
|
}
|
|
|
|
public logout() {
|
|
clearStoredAuthState();
|
|
this.accessToken.set(undefined);
|
|
this.refreshInFlight$ = null;
|
|
}
|
|
|
|
public requestOtk(email: string, password: string): Observable<OtkResponse> {
|
|
return this.authService.requestOtk(
|
|
{
|
|
email: email.trim(),
|
|
password: password.trim(),
|
|
},
|
|
undefined,
|
|
undefined,
|
|
{ context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
|
|
);
|
|
}
|
|
|
|
public requestPasswordReset(
|
|
email: string,
|
|
): Observable<PasswordResetRequestResponse> {
|
|
return this.authService.requestPasswordReset(
|
|
{
|
|
email: email.trim().toLowerCase(),
|
|
},
|
|
undefined,
|
|
undefined,
|
|
{ context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
|
|
) as Observable<PasswordResetRequestResponse>;
|
|
}
|
|
|
|
public resetPassword(
|
|
resetToken: string,
|
|
newPassword: string,
|
|
): Observable<ResetPasswordResponse> {
|
|
return this.authService.resetPassword(
|
|
{
|
|
reset_token: resetToken,
|
|
new_password: newPassword,
|
|
},
|
|
undefined,
|
|
undefined,
|
|
{ context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) },
|
|
) as Observable<ResetPasswordResponse>;
|
|
}
|
|
|
|
public loginWithOtk(
|
|
accountId: string,
|
|
emailCode: string,
|
|
): Observable<LoginResponse> {
|
|
return this.authService
|
|
.login(
|
|
{
|
|
account_id: accountId,
|
|
email_code: emailCode.trim(),
|
|
},
|
|
undefined,
|
|
undefined,
|
|
{
|
|
context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE),
|
|
},
|
|
)
|
|
.pipe(
|
|
tap(({ id_token }) =>
|
|
this.writeAuthState({ idTokenMetadata: id_token }),
|
|
),
|
|
);
|
|
}
|
|
|
|
public requestAccess(
|
|
realAccountId: string,
|
|
effectiveAccountId?: string,
|
|
): Observable<AccessResponse> {
|
|
return this.authService
|
|
.getAccessToken(
|
|
{
|
|
real_account_id: realAccountId,
|
|
effective_account_id: effectiveAccountId ?? realAccountId,
|
|
},
|
|
undefined,
|
|
'body',
|
|
undefined,
|
|
{
|
|
context: new HttpContext().set(
|
|
REQUIRED_TOKEN_TYPE,
|
|
TOKEN_TYPE.ID_TOKEN_COOKIE,
|
|
),
|
|
},
|
|
)
|
|
.pipe(
|
|
tap(({ access_token }) => {
|
|
this.persistAccessToken(access_token);
|
|
}),
|
|
);
|
|
}
|
|
|
|
public changePassword(
|
|
currentPassword: string,
|
|
newPassword: string,
|
|
): Observable<void> {
|
|
this.isValidating.set(true);
|
|
return this.authService
|
|
.changePassword({
|
|
current_password: currentPassword,
|
|
new_password: newPassword,
|
|
})
|
|
.pipe(
|
|
tap(() => this.isValidating.set(false)),
|
|
catchError((err) => {
|
|
this.isValidating.set(false);
|
|
return throwError(() => err);
|
|
}),
|
|
);
|
|
}
|
|
|
|
public refreshAccessToken(): Observable<AccessToken> {
|
|
if (this.refreshInFlight$) {
|
|
return this.refreshInFlight$;
|
|
}
|
|
|
|
this.refreshInFlight$ = this.authService
|
|
.refreshAccessToken(undefined, 'body', undefined, {
|
|
context: new HttpContext().set(
|
|
REQUIRED_TOKEN_TYPE,
|
|
TOKEN_TYPE.REFRESH_TOKEN_COOKIE, // 'REFRESH_TOKEN_COOKIE' and NOT 'REFRESH_COOKIE', + 30 Minutes debugging this shit, changed to types
|
|
),
|
|
})
|
|
.pipe(
|
|
tap((accessToken) => {
|
|
this.persistAccessToken(accessToken);
|
|
}),
|
|
catchError(() => this.reauthenticateViaIdToken()),
|
|
finalize(() => {
|
|
this.refreshInFlight$ = null;
|
|
}),
|
|
shareReplay(1),
|
|
);
|
|
|
|
return this.refreshInFlight$;
|
|
}
|
|
|
|
reauthenticateViaIdToken(): Observable<AccessToken> {
|
|
const idTokenMetadata = this.getStoredIdTokenMetadata();
|
|
|
|
if (!idTokenMetadata || this.isExpired(idTokenMetadata)) {
|
|
this.logout();
|
|
return throwError(
|
|
() => new Error('No valid ID token metadata available.'),
|
|
);
|
|
}
|
|
|
|
return this.requestAccess(
|
|
idTokenMetadata.real_account_id,
|
|
idTokenMetadata.real_account_id,
|
|
).pipe(
|
|
map(({ access_token }) => access_token),
|
|
catchError((err) => {
|
|
console.error('Error reauthenticating via ID token:', err);
|
|
this.logout();
|
|
return throwError(() => err);
|
|
}),
|
|
);
|
|
}
|
|
|
|
public getRawAccessToken(): string | undefined {
|
|
return this.getStoredAccessToken()?.raw_token;
|
|
}
|
|
|
|
public async impersonateAccount(effectiveAccountId: string): Promise<void> {
|
|
const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id;
|
|
if (!realAccountId) {
|
|
throw new Error('No real account ID available.');
|
|
}
|
|
|
|
const request = ++this.request;
|
|
this.isValidating.set(true);
|
|
|
|
try {
|
|
await firstValueFrom(
|
|
this.requestAccess(realAccountId, effectiveAccountId),
|
|
);
|
|
} finally {
|
|
if (request === this.request) {
|
|
this.isValidating.set(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
public async stopImpersonating(): Promise<void> {
|
|
this.isValidating.set(true);
|
|
|
|
const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id;
|
|
if (!realAccountId) {
|
|
throw new Error('No real account ID available.');
|
|
}
|
|
|
|
try {
|
|
await firstValueFrom(this.requestAccess(realAccountId, realAccountId));
|
|
} finally {
|
|
this.isValidating.set(false);
|
|
}
|
|
}
|
|
|
|
public async logoutAccount(): Promise<void> {
|
|
try {
|
|
await firstValueFrom(this.authService.logout());
|
|
} catch (err) {
|
|
console.error('Error logging out on the server:', err);
|
|
} finally {
|
|
this.logout();
|
|
await this.router.navigate(['/login'], { replaceUrl: true });
|
|
}
|
|
}
|
|
}
|