fix(auth): add global error handler and PWA update service, and update auth logout to force full page reload (prevent reload-hell) (#741)

This commit is contained in:
brios
2026-04-22 17:27:47 -04:00
committed by Zach Yale
parent 10afe3c826
commit 62434c590d
8 changed files with 243 additions and 111 deletions
@@ -1,14 +1,14 @@
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 {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {API_CONFIG} from '../../core/config/api-config';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
import {RxStompService} from '../websocket/rx-stomp.service';
import {AuthService, websocketInitializer} from './auth.service';
import { API_CONFIG } from '../../core/config/api-config';
import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service';
import { RxStompService } from '../websocket/rx-stomp.service';
import { AuthService, websocketInitializer } from './auth.service';
describe('AuthService', () => {
const router = {
@@ -34,9 +34,9 @@ describe('AuthService', () => {
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{provide: Router, useValue: router},
{provide: RxStompService, useValue: rxStompService},
{provide: PostLoginInitializerService, useValue: postLoginInitializer},
{ provide: Router, useValue: router },
{ provide: RxStompService, useValue: rxStompService },
{ provide: PostLoginInitializerService, useValue: postLoginInitializer },
AuthService,
]
});
@@ -49,6 +49,10 @@ describe('AuthService', () => {
service = TestBed.inject(AuthService);
httpTestingController = TestBed.inject(HttpTestingController);
// Mock redirectTo for all tests using a narrow test-only type to access protected method
vi.spyOn(service as unknown as { redirectTo: AuthService['redirectTo'] }, 'redirectTo')
.mockImplementation(() => undefined);
});
afterEach(() => {
@@ -58,12 +62,12 @@ describe('AuthService', () => {
});
it('logs in with internal credentials and initializes the authenticated session', () => {
service.internalLogin({username: 'admin', password: 'secret'}).subscribe();
service.internalLogin({ username: 'admin', password: 'secret' }).subscribe();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/login`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({username: 'admin', password: 'secret'});
request.flush({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'});
expect(request.request.body).toEqual({ username: 'admin', password: 'secret' });
request.flush({ accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false' });
expect(service.getInternalAccessToken()).toBe('access');
expect(service.getInternalRefreshToken()).toBe('refresh');
@@ -79,8 +83,8 @@ describe('AuthService', () => {
service.internalRefreshToken().subscribe();
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'});
expect(request.request.body).toEqual({ refreshToken: 'refresh-token' });
request.flush({ accessToken: 'new-access', refreshToken: 'new-refresh' });
expect(service.getInternalAccessToken()).toBe('new-access');
expect(service.getInternalRefreshToken()).toBe('new-refresh');
@@ -91,7 +95,7 @@ describe('AuthService', () => {
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`);
expect(request.request.method).toBe('GET');
request.flush({accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false'});
request.flush({ accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false' });
expect(service.getInternalAccessToken()).toBe('remote-access');
expect(rxStompService.activate).toHaveBeenCalledOnce();
@@ -105,13 +109,13 @@ describe('AuthService', () => {
service.logout();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
request.flush({logoutUrl: null});
request.flush({ logoutUrl: null });
await Promise.resolve();
expect(service.token()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
expect(router.navigate).toHaveBeenCalledWith(['/login']);
expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login', true);
});
it('logs out locally when the backend logout request fails', async () => {
@@ -121,13 +125,13 @@ describe('AuthService', () => {
service.logout();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
request.flush('boom', {status: 500, statusText: 'Server Error'});
request.flush('boom', { status: 500, statusText: 'Server Error' });
await Promise.resolve();
expect(service.token()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
expect(router.navigate).toHaveBeenCalledWith(['/login']);
expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login', true);
});
it('clears the session and navigates with a reason during force logout', () => {
@@ -138,9 +142,7 @@ describe('AuthService', () => {
expect(service.token()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce();
expect(router.navigate).toHaveBeenCalledWith(['/login'], {
queryParams: {reason: 'session_revoked'},
});
expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login?reason=session_revoked', true);
});
it('clears the session when the login page is opened', () => {
+47 -28
View File
@@ -1,11 +1,11 @@
import {computed, inject, Injectable, Injector, signal} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, tap} from 'rxjs';
import {RxStompService} from '../websocket/rx-stomp.service';
import {API_CONFIG} from '../../core/config/api-config';
import {createRxStompConfig} from '../websocket/rx-stomp.config';
import {Router} from '@angular/router';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
import { computed, inject, Injectable, Injector, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, tap, finalize } from 'rxjs';
import { RxStompService } from '../websocket/rx-stomp.service';
import { API_CONFIG } from '../../core/config/api-config';
import { createRxStompConfig } from '../websocket/rx-stomp.config';
import { Router } from '@angular/router';
import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service';
@Injectable({
providedIn: 'root',
@@ -14,7 +14,10 @@ export class AuthService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`;
private rxStompService?: RxStompService;
private postLoginInitialized = false;
private readonly _postLoginInitialized = signal(false);
readonly postLoginInitialized = this._postLoginInitialized.asReadonly();
private readonly _logoutInProgress = signal(false);
readonly logoutInProgress = this._logoutInProgress.asReadonly();
private http = inject(HttpClient);
private injector = inject(Injector);
@@ -38,7 +41,7 @@ export class AuthService {
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
const refreshToken = this.getInternalRefreshToken();
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, { refreshToken }).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
@@ -74,26 +77,42 @@ export class AuthService {
}
logout(): void {
if (this._logoutInProgress()) return;
this._logoutInProgress.set(true);
const refreshToken = this.getInternalRefreshToken();
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, {refreshToken}).subscribe({
next: (response) => {
if (response.logoutUrl) {
window.location.href = response.logoutUrl;
} else {
this.clearSession();
this.router.navigate(['/login']).then(() => window.location.reload());
this.clearSession();
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, { refreshToken })
.pipe(finalize(() => {
this._logoutInProgress.set(false);
}))
.subscribe({
next: (response) => {
if (response.logoutUrl) {
this.redirectTo(response.logoutUrl, true);
} else {
this.redirectTo('/login', true);
}
},
error: () => {
this.redirectTo('/login', true);
}
},
error: () => {
this.clearSession();
this.router.navigate(['/login']).then(() => window.location.reload());
}
});
});
}
forceLogout(reason: string): void {
this._logoutInProgress.set(true);
this.clearSession();
this.router.navigate(['/login'], {queryParams: {reason}});
this.redirectTo(`/login?reason=${encodeURIComponent(reason)}`, true);
}
protected redirectTo(url: string, replace = false): void {
if (replace) {
window.location.replace(url);
} else {
window.location.href = url;
}
}
clearSessionOnLoginPage(): void {
@@ -104,7 +123,7 @@ export class AuthService {
localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal');
this.token.set(null);
this.postLoginInitialized = false;
this._postLoginInitialized.set(false);
this.getRxStompService().deactivate();
}
@@ -124,14 +143,14 @@ export class AuthService {
stompService.updateConfig(config);
stompService.activate();
if (!this.postLoginInitialized) {
if (!this._postLoginInitialized()) {
this.handleSuccessfulAuth();
}
}
private handleSuccessfulAuth() {
if (this.postLoginInitialized) return;
this.postLoginInitialized = true;
if (this._postLoginInitialized()) return;
this._postLoginInitialized.set(true);
this.postLoginInitializer.initialize().subscribe({
next: () => console.log('AuthService: Post-login initialization completed'),
error: (err) => console.error('AuthService: Post-login initialization failed:', err)