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
+6 -5
View File
@@ -1,7 +1,7 @@
import {describe, expect, it} from 'vitest';
import {routes} from './app.routes';
import {AuthGuard} from './core/security/auth.guard';
import {AuthChildGuard, AuthGuard} from './core/security/auth.guard';
import {BookdropGuard} from './core/security/guards/bookdrop.guard';
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
import {LibraryStatsGuard} from './core/security/guards/library-stats.guard';
@@ -28,10 +28,11 @@ describe('app routes', () => {
const children = shellRoute?.children ?? [];
expect(children).toHaveLength(17);
expect(children.find(route => route.path === 'dashboard')?.canActivate).toEqual([AuthGuard]);
expect(children.find(route => route.path === 'all-books')?.canActivate).toEqual([AuthGuard]);
expect(children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.canActivate).toEqual([AuthGuard]);
expect(children.find(route => route.path === 'notebook')?.canActivate).toEqual([AuthGuard]);
expect(shellRoute?.canActivateChild).toEqual([AuthChildGuard]);
expect(children.find(route => route.path === 'dashboard')?.canActivate).toBeUndefined();
expect(children.find(route => route.path === 'all-books')?.canActivate).toBeUndefined();
expect(children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.canActivate).toBeUndefined();
expect(children.find(route => route.path === 'notebook')?.canActivate).toBeUndefined();
expect(typeof children.find(route => route.path === 'all-books')?.loadComponent).toBe('function');
expect(typeof children.find(route => route.path === 'library/:libraryId/books')?.loadComponent).toBe('function');
expect(typeof children.find(route => route.path === 'shelf/:shelfId/books')?.loadComponent).toBe('function');
+15 -14
View File
@@ -1,7 +1,7 @@
import {Routes} from '@angular/router';
import {AppLayoutComponent} from './shared/layout/layout-main/app.layout.component';
import {LoginComponent} from './shared/components/login/login.component';
import {AuthGuard} from './core/security/auth.guard';
import {AuthChildGuard, AuthGuard} from './core/security/auth.guard';
import {ChangePasswordComponent} from './shared/components/change-password/change-password.component';
import {SetupComponent} from './shared/components/setup/setup.component';
import {SetupGuard} from './shared/components/setup/setup.guard';
@@ -34,24 +34,25 @@ export const routes: Routes = [
{
path: '',
component: AppLayoutComponent,
canActivateChild: [AuthChildGuard],
children: [
{path: 'dashboard', component: MainDashboardComponent, canActivate: [AuthGuard]},
{path: 'all-books', loadComponent: loadBookBrowserComponent, canActivate: [AuthGuard]},
{path: 'settings', loadComponent: () => import('./features/settings/settings.component').then(m => m.SettingsComponent), canActivate: [AuthGuard]},
{path: 'library/:libraryId/books', loadComponent: loadBookBrowserComponent, canActivate: [AuthGuard]},
{path: 'shelf/:shelfId/books', loadComponent: loadBookBrowserComponent, canActivate: [AuthGuard]},
{path: 'unshelved-books', loadComponent: loadBookBrowserComponent, canActivate: [AuthGuard]},
{path: 'series', loadComponent: () => import('./features/series-browser/components/series-browser/series-browser.component').then(m => m.SeriesBrowserComponent), canActivate: [AuthGuard]},
{path: 'series/:seriesName', loadComponent: () => import('./features/book/components/series-page/series-page.component').then(m => m.SeriesPageComponent), canActivate: [AuthGuard]},
{path: 'authors', loadComponent: () => import('./features/author-browser/components/author-browser/author-browser.component').then(m => m.AuthorBrowserComponent), canActivate: [AuthGuard]},
{path: 'author/:authorId', loadComponent: () => import('./features/author-browser/components/author-detail/author-detail.component').then(m => m.AuthorDetailComponent), canActivate: [AuthGuard]},
{path: 'magic-shelf/:magicShelfId/books', loadComponent: loadBookBrowserComponent, canActivate: [AuthGuard]},
{path: 'book/:bookId', loadComponent: () => import('./features/metadata/component/book-metadata-center/book-metadata-center.component').then(m => m.BookMetadataCenterComponent), canActivate: [AuthGuard]},
{path: 'dashboard', component: MainDashboardComponent},
{path: 'all-books', loadComponent: loadBookBrowserComponent},
{path: 'settings', loadComponent: () => import('./features/settings/settings.component').then(m => m.SettingsComponent)},
{path: 'library/:libraryId/books', loadComponent: loadBookBrowserComponent},
{path: 'shelf/:shelfId/books', loadComponent: loadBookBrowserComponent},
{path: 'unshelved-books', loadComponent: loadBookBrowserComponent},
{path: 'series', loadComponent: () => import('./features/series-browser/components/series-browser/series-browser.component').then(m => m.SeriesBrowserComponent)},
{path: 'series/:seriesName', loadComponent: () => import('./features/book/components/series-page/series-page.component').then(m => m.SeriesPageComponent)},
{path: 'authors', loadComponent: () => import('./features/author-browser/components/author-browser/author-browser.component').then(m => m.AuthorBrowserComponent)},
{path: 'author/:authorId', loadComponent: () => import('./features/author-browser/components/author-detail/author-detail.component').then(m => m.AuthorDetailComponent)},
{path: 'magic-shelf/:magicShelfId/books', loadComponent: loadBookBrowserComponent},
{path: 'book/:bookId', loadComponent: () => import('./features/metadata/component/book-metadata-center/book-metadata-center.component').then(m => m.BookMetadataCenterComponent)},
{path: 'bookdrop', loadComponent: () => import('./features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component').then(m => m.BookdropFileReviewComponent), canActivate: [BookdropGuard]},
{path: 'metadata-manager', loadComponent: () => import('./features/metadata/component/metadata-manager/metadata-manager.component').then(m => m.MetadataManagerComponent), canActivate: [EditMetadataGuard]},
{path: 'library-stats', loadComponent: () => import('./features/stats/component/library-stats/library-stats.component').then(m => m.LibraryStatsComponent), canActivate: [LibraryStatsGuard]},
{path: 'reading-stats', loadComponent: () => import('./features/stats/component/user-stats/user-stats.component').then(m => m.UserStatsComponent), canActivate: [UserStatsGuard]},
{path: 'notebook', loadComponent: () => import('./features/notebook/components/notebook/notebook.component').then(m => m.NotebookComponent), canActivate: [AuthGuard]},
{path: 'notebook', loadComponent: () => import('./features/notebook/components/notebook/notebook.component').then(m => m.NotebookComponent)},
]
},
{
@@ -10,8 +10,7 @@ import { AuthInterceptorService } from './auth-interceptor.service';
describe('AuthInterceptorService', () => {
const authService = {
getInternalAccessToken: vi.fn<() => string | null>(),
internalRefreshToken: vi.fn<() => Observable<{ accessToken: string; refreshToken: string }>>(),
saveInternalTokens: vi.fn<(accessToken: string, refreshToken: string) => void>(),
ensureAccessToken: vi.fn<(options?: {forceRefresh?: boolean}) => Observable<string>>(),
logout: vi.fn<() => void>(),
};
@@ -21,8 +20,7 @@ describe('AuthInterceptorService', () => {
beforeEach(() => {
vi.restoreAllMocks();
authService.getInternalAccessToken.mockReset();
authService.internalRefreshToken.mockReset();
authService.saveInternalTokens.mockReset();
authService.ensureAccessToken.mockReset();
authService.logout.mockReset();
TestBed.resetTestingModule();
@@ -82,7 +80,7 @@ describe('AuthInterceptorService', () => {
it('retries a 401 request after a successful refresh', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token');
authService.internalRefreshToken.mockReturnValue(of({ accessToken: 'fresh-token', refreshToken: 'refresh-token' }));
authService.ensureAccessToken.mockReturnValue(of('fresh-token'));
const next = vi.fn((request: HttpRequest<unknown>) => {
const authHeader = request.headers.get('Authorization');
@@ -97,34 +95,47 @@ describe('AuthInterceptorService', () => {
next
));
expect(authService.internalRefreshToken).toHaveBeenCalledOnce();
expect(authService.saveInternalTokens).toHaveBeenCalledWith('fresh-token', 'refresh-token');
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
expect((response as HttpResponse<string>).body).toBe('Bearer fresh-token');
});
it('retries a 401 request without persisting tokens when the refresh response is incomplete', async () => {
it('logs out when AuthService cannot refresh a complete token pair', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token');
authService.internalRefreshToken.mockReturnValue(of({ accessToken: 'fresh-token', refreshToken: '' }));
authService.ensureAccessToken.mockReturnValue(throwError(() => new Error('Authentication response did not include a complete token pair')));
const next = vi.fn(() => throwError(() => new HttpErrorResponse({ status: 401 })));
await expect(firstValueFrom(interceptor(
new HttpRequest('GET', `${apiUrl}/books`),
next
))).rejects.toBeInstanceOf(Error);
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
expect(authService.logout).toHaveBeenCalledOnce();
});
it('does not log out when the retried request fails after refresh succeeds', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token');
authService.ensureAccessToken.mockReturnValue(of('fresh-token'));
const next = vi.fn((request: HttpRequest<unknown>) => {
if (request.headers.get('Authorization') === 'Bearer fresh-token') {
return of(new HttpResponse({ status: 200, body: request.headers.get('Authorization') }));
return throwError(() => new HttpErrorResponse({ status: 500 }));
}
return throwError(() => new HttpErrorResponse({ status: 401 }));
});
const response = await firstValueFrom(interceptor(
await expect(firstValueFrom(interceptor(
new HttpRequest('GET', `${apiUrl}/books`),
next
));
))).rejects.toBeInstanceOf(HttpErrorResponse);
expect(authService.saveInternalTokens).not.toHaveBeenCalled();
expect((response as HttpResponse<string>).body).toBe('Bearer fresh-token');
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
expect(authService.logout).not.toHaveBeenCalled();
});
it('logs out when the refresh request fails', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token');
authService.internalRefreshToken.mockReturnValue(
authService.ensureAccessToken.mockReturnValue(
throwError(() => new HttpErrorResponse({ status: 500 }))
);
@@ -147,14 +158,14 @@ describe('AuthInterceptorService', () => {
next
))).rejects.toBeInstanceOf(HttpErrorResponse);
expect(authService.internalRefreshToken).not.toHaveBeenCalled();
expect(authService.ensureAccessToken).not.toHaveBeenCalled();
expect(authService.logout).not.toHaveBeenCalled();
});
it('queues concurrent 401s behind a single refresh operation', async () => {
it('delegates concurrent 401 refresh coordination to AuthService', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token');
const refreshSubject = new Subject<{ accessToken: string; refreshToken: string }>();
authService.internalRefreshToken.mockReturnValue(refreshSubject.asObservable());
const refreshSubject = new Subject<string>();
authService.ensureAccessToken.mockReturnValue(refreshSubject.asObservable());
const next = vi.fn((request: HttpRequest<unknown>) => {
const authHeader = request.headers.get('Authorization');
@@ -167,12 +178,13 @@ describe('AuthInterceptorService', () => {
const firstRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/books`), next));
const secondRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/libraries`), next));
refreshSubject.next({ accessToken: 'refreshed-token', refreshToken: 'refresh-token' });
refreshSubject.next('refreshed-token');
refreshSubject.complete();
const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]);
expect(authService.internalRefreshToken).toHaveBeenCalledOnce();
expect(authService.ensureAccessToken).toHaveBeenCalledTimes(2);
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
expect((firstResponse as HttpResponse<string>).body).toBe('Bearer refreshed-token');
expect((secondResponse as HttpResponse<string>).body).toBe('Bearer refreshed-token');
});
@@ -1,13 +1,10 @@
import { HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, filter, switchMap, take } from 'rxjs/operators';
import { BehaviorSubject, Observable, throwError, defer } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { Observable, throwError, defer } from 'rxjs';
import { AuthService } from '../../shared/service/auth.service';
import { API_CONFIG } from '../config/api-config';
let isRefreshing = false;
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
const authService = inject(AuthService);
@@ -42,36 +39,14 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
return defer(() => {
if (!isRefreshing) {
isRefreshing = true;
refreshTokenSubject.next(null);
return authService.internalRefreshToken().pipe(
switchMap(response => {
isRefreshing = false;
const { accessToken, refreshToken } = response;
if (accessToken && refreshToken) {
authService.saveInternalTokens(accessToken, refreshToken);
refreshTokenSubject.next(accessToken);
}
return next(request.clone({
setHeaders: { Authorization: `Bearer ${accessToken}` }
}));
}),
catchError(err => {
isRefreshing = false;
forceLogout(authService);
return throwError(() => err);
})
);
}
return refreshTokenSubject.pipe(
filter(token => token !== null),
take(1),
switchMap(token =>
return authService.ensureAccessToken({forceRefresh: true}).pipe(
catchError(err => {
forceLogout(authService);
return throwError(() => err);
}),
switchMap(accessToken =>
next(request.clone({
setHeaders: { Authorization: `Bearer ${token}` }
setHeaders: { Authorization: `Bearer ${accessToken}` }
}))
)
);
@@ -1,9 +1,10 @@
import {TestBed} from '@angular/core/testing';
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {firstValueFrom, Observable, of} from 'rxjs';
import {AuthService} from '../../shared/service/auth.service';
import {AuthGuard} from './auth.guard';
import {AuthChildGuard, AuthGuard} from './auth.guard';
describe('AuthGuard', () => {
const route = {} as ActivatedRouteSnapshot;
@@ -14,8 +15,7 @@ describe('AuthGuard', () => {
};
const authService = {
getInternalAccessToken: vi.fn<() => string | null>(),
getInternalAccessTokenExpiry: vi.fn<() => number | null>(),
ensureAuthenticated: vi.fn(),
getIsDefaultPassword: vi.fn<() => boolean>(),
};
@@ -24,8 +24,7 @@ describe('AuthGuard', () => {
localStorage.clear();
router.createUrlTree.mockClear();
router.navigate.mockClear();
authService.getInternalAccessToken.mockReset();
authService.getInternalAccessTokenExpiry.mockReset();
authService.ensureAuthenticated.mockReset();
authService.getIsDefaultPassword.mockReset();
TestBed.configureTestingModule({
@@ -40,45 +39,61 @@ describe('AuthGuard', () => {
localStorage.clear();
});
it('allows navigation for a valid non-default-password token', () => {
authService.getInternalAccessToken.mockReturnValue('bearer token');
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() + 3600000);
function runGuard(): Observable<unknown> {
return TestBed.runInInjectionContext(() => AuthGuard(route, state)) as Observable<unknown>;
}
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
it('allows navigation for an authenticated non-default-password session', async () => {
authService.ensureAuthenticated.mockReturnValue(of(true));
authService.getIsDefaultPassword.mockReturnValue(false);
const result = await firstValueFrom(runGuard());
expect(result).toBe(true);
expect(authService.ensureAuthenticated).toHaveBeenCalledOnce();
expect(router.navigate).not.toHaveBeenCalled();
});
it('redirects to login when there is no token', () => {
authService.getInternalAccessToken.mockReturnValue(null);
it('redirects to login when the session cannot be authenticated', async () => {
authService.ensureAuthenticated.mockReturnValue(of(false));
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
expect(result).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/login']);
});
it('returns a login UrlTree for expired tokens', () => {
localStorage.setItem('accessToken_Internal', 'stale-token');
authService.getInternalAccessToken.mockReturnValue('stale-token');
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() - 10000);
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
const result = await firstValueFrom(runGuard());
expect(router.createUrlTree).toHaveBeenCalledWith(['/login']);
expect(result).toEqual({commands: ['/login']});
expect(localStorage.getItem('accessToken_Internal')).toBeNull();
expect(router.navigate).not.toHaveBeenCalled();
});
it('redirects to the change-password flow for default-password tokens', () => {
authService.getInternalAccessToken.mockReturnValue('bearer token');
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() + 3600000);
it('allows navigation when AuthService refreshes an expired token', async () => {
authService.ensureAuthenticated.mockReturnValue(of(true));
authService.getIsDefaultPassword.mockReturnValue(false);
const result = await firstValueFrom(runGuard());
expect(result).toBe(true);
expect(router.createUrlTree).not.toHaveBeenCalledWith(['/login']);
});
it('redirects to the change-password flow for default-password sessions', async () => {
authService.ensureAuthenticated.mockReturnValue(of(true));
authService.getIsDefaultPassword.mockReturnValue(true);
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
const result = await firstValueFrom(runGuard());
expect(result).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
expect(router.createUrlTree).toHaveBeenCalledWith(['/change-password']);
expect(result).toEqual({commands: ['/change-password']});
expect(router.navigate).not.toHaveBeenCalled();
});
it('uses the same authentication flow for child routes', async () => {
authService.ensureAuthenticated.mockReturnValue(of(true));
authService.getIsDefaultPassword.mockReturnValue(false);
const result = await firstValueFrom(
TestBed.runInInjectionContext(() => AuthChildGuard(route, state)) as Observable<unknown>
);
expect(result).toBe(true);
expect(authService.ensureAuthenticated).toHaveBeenCalledOnce();
});
});
+13 -22
View File
@@ -1,38 +1,29 @@
import {inject} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
import {ActivatedRouteSnapshot, CanActivateChildFn, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
import {AuthService} from '../../shared/service/auth.service';
import {map} from 'rxjs/operators';
export const AuthGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const authenticateRoute = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
void route;
void state;
const router = inject(Router);
const authService = inject(AuthService);
const internalAccessToken = authService.getInternalAccessToken();
if (internalAccessToken) {
try {
const isDefaultPassword = authService.getIsDefaultPassword();
const internalAccessTokenExpiry = authService.getInternalAccessTokenExpiry();
if (internalAccessTokenExpiry != null && internalAccessTokenExpiry < Date.now()) {
localStorage.removeItem('accessToken_Internal');
return authService.ensureAuthenticated().pipe(
map(isAuthenticated => {
if (!isAuthenticated) {
return router.createUrlTree(['/login']);
}
const isDefaultPassword = authService.getIsDefaultPassword();
if (isDefaultPassword) {
router.navigate(['/change-password']);
return false;
return router.createUrlTree(['/change-password']);
}
return true;
} catch {
localStorage.removeItem('accessToken_Internal');
router.navigate(['/login']);
return false;
}
}
router.navigate(['/login']);
return false;
})
);
};
export const AuthGuard: CanActivateFn = authenticateRoute;
export const AuthChildGuard: CanActivateChildFn = authenticateRoute;
@@ -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;