fix(auth): centralize token handling in auth service (#1534)

This commit is contained in:
Zach
2026-06-01 20:44:35 +00:00
committed by GitHub
parent 02cdaef35e
commit db64539996
8 changed files with 397 additions and 143 deletions
@@ -2,7 +2,7 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { of, throwError } from 'rxjs';
import { firstValueFrom, of, throwError } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { API_CONFIG } from '../../core/config/api-config';
@@ -80,7 +80,7 @@ describe('AuthService', () => {
it('refreshes the token and persists the new values', () => {
localStorage.setItem('refreshToken_Internal', 'refresh-token');
service.internalRefreshToken().subscribe();
service.refreshInternalSession().subscribe();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
expect(request.request.body).toEqual({ refreshToken: 'refresh-token' });
@@ -90,6 +90,176 @@ describe('AuthService', () => {
expect(service.getInternalRefreshToken()).toBe('new-refresh');
});
it('fails refresh when the backend does not return a complete token pair', async () => {
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const refresh = firstValueFrom(service.refreshInternalSession());
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
request.flush({ accessToken: 'new-access', refreshToken: '' });
await expect(refresh).rejects.toThrow('Authentication response did not include a complete token pair');
expect(service.getInternalAccessToken()).toBeNull();
expect(service.getInternalRefreshToken()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
});
it('does not send a refresh request when no refresh token is available', async () => {
await expect(firstValueFrom(service.refreshInternalSession())).rejects.toThrow('No refresh token available');
httpTestingController.expectNone(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
});
it('returns the current access token without refreshing when it is still valid', async () => {
localStorage.setItem('accessToken_Internal', 'access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() + 3600000));
localStorage.setItem('refreshToken_Internal', 'refresh');
await expect(firstValueFrom(service.ensureAccessToken())).resolves.toBe('access');
httpTestingController.expectNone(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
});
it('force-refreshes the access token even when the current token has not expired', async () => {
localStorage.setItem('accessToken_Internal', 'access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() + 3600000));
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const accessToken = firstValueFrom(service.ensureAccessToken({forceRefresh: true}));
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
expect(request.request.body).toEqual({ refreshToken: 'refresh-token' });
request.flush({ accessToken: 'new-access', refreshToken: 'new-refresh' });
await expect(accessToken).resolves.toBe('new-access');
expect(service.getInternalAccessToken()).toBe('new-access');
expect(service.getInternalRefreshToken()).toBe('new-refresh');
});
it('refreshes an expired session before reporting authentication', async () => {
localStorage.setItem('accessToken_Internal', 'expired-access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() - 1000));
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const authenticated = firstValueFrom(service.ensureAuthenticated());
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
expect(request.request.body).toEqual({ refreshToken: 'refresh-token' });
request.flush({ accessToken: 'new-access', refreshToken: 'new-refresh' });
await expect(authenticated).resolves.toBe(true);
expect(service.getInternalAccessToken()).toBe('new-access');
expect(service.getInternalRefreshToken()).toBe('new-refresh');
expect(rxStompService.updateConfig).toHaveBeenCalledOnce();
expect(rxStompService.activate).toHaveBeenCalledOnce();
});
it('shares concurrent refresh attempts through one backend request', async () => {
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const firstRefresh = firstValueFrom(service.refreshInternalSession());
const secondRefresh = firstValueFrom(service.refreshInternalSession());
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
request.flush({ accessToken: 'new-access', refreshToken: 'new-refresh' });
await expect(Promise.all([firstRefresh, secondRefresh])).resolves.toEqual([
{ accessToken: 'new-access', refreshToken: 'new-refresh' },
{ accessToken: 'new-access', refreshToken: 'new-refresh' },
]);
expect(service.getInternalAccessToken()).toBe('new-access');
expect(service.getInternalRefreshToken()).toBe('new-refresh');
});
it('does not restore tokens or websocket state when a refresh resolves after logout', async () => {
localStorage.setItem('accessToken_Internal', 'expired-access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() - 1000));
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const refresh = firstValueFrom(service.refreshInternalSession());
const refreshRequest = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
service.logout();
const logoutRequest = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
expect(logoutRequest.request.body).toEqual({ refreshToken: 'refresh-token' });
refreshRequest.flush({ accessToken: 'late-access', refreshToken: 'late-refresh' });
logoutRequest.flush({ logoutUrl: null });
await expect(refresh).rejects.toThrow('Refresh response belongs to a stale session');
expect(service.getInternalAccessToken()).toBeNull();
expect(service.getInternalRefreshToken()).toBeNull();
expect(rxStompService.updateConfig).not.toHaveBeenCalled();
expect(rxStompService.activate).not.toHaveBeenCalled();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
});
it('keeps the current session when re-login happens while refresh is in flight', async () => {
localStorage.setItem('accessToken_Internal', 'expired-access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() - 1000));
localStorage.setItem('refreshToken_Internal', 'old-refresh');
const accessToken = firstValueFrom(service.ensureAccessToken());
const refreshRequest = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
expect(refreshRequest.request.body).toEqual({ refreshToken: 'old-refresh' });
service.saveInternalTokens('current-access', 'current-refresh');
refreshRequest.flush({ accessToken: 'late-access', refreshToken: 'late-refresh' });
await expect(accessToken).resolves.toBe('current-access');
expect(service.getInternalAccessToken()).toBe('current-access');
expect(service.getInternalRefreshToken()).toBe('current-refresh');
expect(rxStompService.deactivate).not.toHaveBeenCalled();
});
it('clears the session when expired credentials cannot be refreshed', async () => {
localStorage.setItem('accessToken_Internal', 'expired-access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() - 1000));
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const authenticated = firstValueFrom(service.ensureAuthenticated());
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
request.flush('nope', { status: 401, statusText: 'Unauthorized' });
await expect(authenticated).resolves.toBe(false);
expect(service.getInternalAccessToken()).toBeNull();
expect(service.getInternalRefreshToken()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
});
it('clears the session when refresh returns an incomplete token pair', async () => {
localStorage.setItem('accessToken_Internal', 'expired-access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() - 1000));
localStorage.setItem('refreshToken_Internal', 'refresh-token');
const authenticated = firstValueFrom(service.ensureAuthenticated());
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
request.flush({ accessToken: 'new-access', refreshToken: '' });
await expect(authenticated).resolves.toBe(false);
expect(service.getInternalAccessToken()).toBeNull();
expect(service.getInternalRefreshToken()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
});
it('does not refresh when the access token is still current', async () => {
localStorage.setItem('accessToken_Internal', 'access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() + 3600000));
localStorage.setItem('refreshToken_Internal', 'refresh');
await expect(firstValueFrom(service.ensureAuthenticated())).resolves.toBe(true);
httpTestingController.expectNone(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
expect(rxStompService.updateConfig).not.toHaveBeenCalled();
expect(rxStompService.activate).not.toHaveBeenCalled();
});
it('handles remote login the same way as an internal login', () => {
service.remoteLogin().subscribe();
@@ -162,6 +332,16 @@ describe('AuthService', () => {
expect(postLoginInitializer.initialize).not.toHaveBeenCalled();
});
it('skips websocket initialization when the access token is expired', () => {
localStorage.setItem('accessToken_Internal', 'expired-access');
localStorage.setItem('accessToken_Internal_Expiry', String(Date.now() - 1000));
service.initializeWebSocketConnection();
expect(rxStompService.updateConfig).not.toHaveBeenCalled();
expect(postLoginInitializer.initialize).not.toHaveBeenCalled();
});
it('initializes the websocket connection and post-login hooks only once', () => {
service.saveInternalTokens('access', 'refresh');
+94 -15
View File
@@ -1,6 +1,7 @@
import { computed, inject, Injectable, Injector, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, tap, finalize } from 'rxjs';
import { Observable, tap, finalize, of, throwError } from 'rxjs';
import { catchError, map, shareReplay } from 'rxjs/operators';
import { RxStompService } from '../websocket/rx-stomp.service';
import { API_CONFIG } from '../../core/config/api-config';
import { createRxStompConfig } from '../websocket/rx-stomp.config';
@@ -14,6 +15,12 @@ interface AccessTokenResponse {
expires?: number;
}
export class StaleRefreshResponseError extends Error {
constructor() {
super('Refresh response belongs to a stale session');
}
}
@Injectable({
providedIn: 'root',
})
@@ -25,6 +32,7 @@ export class AuthService {
readonly postLoginInitialized = this._postLoginInitialized.asReadonly();
private readonly _logoutInProgress = signal(false);
readonly logoutInProgress = this._logoutInProgress.asReadonly();
private refreshSessionRequest$?: Observable<AccessTokenResponse>;
private http = inject(HttpClient);
private injector = inject(Injector);
@@ -37,22 +45,69 @@ export class AuthService {
internalLogin(credentials: { username: string; password: string }): Observable<AccessTokenResponse> {
return this.http.post<AccessTokenResponse>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
}
this.saveInternalTokenResponse(response);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
})
);
}
internalRefreshToken(): Observable<AccessTokenResponse> {
const refreshToken = this.getInternalRefreshToken();
private internalRefreshToken(refreshToken: string): Observable<AccessTokenResponse> {
return this.http.post<AccessTokenResponse>(`${this.apiUrl}/refresh`, { refreshToken }).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
this.saveInternalTokenResponse(response, refreshToken);
})
);
}
ensureAccessToken(options: {forceRefresh?: boolean} = {}): Observable<string> {
if (!options.forceRefresh && this.hasCurrentAccessToken()) {
return of(this.getInternalAccessToken()!);
}
return this.refreshInternalSession().pipe(
map(response => response.accessToken),
catchError(error => {
if (error instanceof StaleRefreshResponseError && this.hasCurrentAccessToken()) {
return of(this.getInternalAccessToken()!);
}
return throwError(() => error);
})
);
}
refreshInternalSession(): Observable<AccessTokenResponse> {
if (!this.getInternalRefreshToken()) {
return throwError(() => new Error('No refresh token available'));
}
if (!this.refreshSessionRequest$) {
const refreshToken = this.getInternalRefreshToken();
if (!refreshToken) {
return throwError(() => new Error('No refresh token available'));
}
this.refreshSessionRequest$ = this.internalRefreshToken(refreshToken).pipe(
tap(() => this.initializeWebSocketConnection()),
finalize(() => {
this.refreshSessionRequest$ = undefined;
}),
shareReplay({bufferSize: 1, refCount: false})
);
}
return this.refreshSessionRequest$;
}
ensureAuthenticated(): Observable<boolean> {
return this.ensureAccessToken().pipe(
map(() => true),
catchError(() => {
if (this.getInternalAccessToken() || this.getInternalRefreshToken()) {
this.clearSession();
}
return of(false);
})
);
}
@@ -60,11 +115,9 @@ export class AuthService {
remoteLogin(): Observable<AccessTokenResponse> {
return this.http.get<AccessTokenResponse>(`${this.apiUrl}/remote`).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
}
this.saveInternalTokenResponse(response);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
})
);
}
@@ -78,6 +131,19 @@ export class AuthService {
this.token.set(accessToken);
}
private saveInternalTokenResponse(response: AccessTokenResponse, expectedRefreshToken?: string): void {
if (expectedRefreshToken !== undefined && expectedRefreshToken !== this.getInternalRefreshToken()) {
throw new StaleRefreshResponseError();
}
if (!response.accessToken || !response.refreshToken) {
this.clearSession();
throw new Error('Authentication response did not include a complete token pair');
}
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
}
getIsDefaultPassword(): boolean {
const isDefaultPassword = localStorage.getItem('authenticationIsDefaultPassword_Internal') ?? 'false';
return isDefaultPassword === 'true';
@@ -96,6 +162,16 @@ export class AuthService {
return localStorage.getItem('refreshToken_Internal');
}
hasCurrentAccessToken(): boolean {
const accessToken = this.getInternalAccessToken();
if (!accessToken) {
return false;
}
const expiry = this.getInternalAccessTokenExpiry();
return expiry == null || expiry > Date.now();
}
logout(): void {
if (this._logoutInProgress()) return;
this._logoutInProgress.set(true);
@@ -140,6 +216,7 @@ export class AuthService {
}
private clearSession(): void {
this.refreshSessionRequest$ = undefined;
localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('accessToken_Internal_Expiry');
localStorage.removeItem('refreshToken_Internal');
@@ -158,6 +235,8 @@ export class AuthService {
}
initializeWebSocketConnection(): void {
if (!this.hasCurrentAccessToken()) return;
const token = this.getInternalAccessToken();
if (!token) return;