9247e5e02e
brings the spa auth track to the level of polish the bff surface
deserves. before this pr the header reflected sign-in state but
there were no protected routes and no global handling of session
drift; this pr lands one guard, two interceptors, and a demo
consumer that exercises the loop end-to-end.
authGuard (CanActivateFn):
gates routes on AuthService.state. waits out the bootstrap
`loading` state (filter+firstValueFrom on toObservable(state)),
allows when `authenticated`, redirects via auth.login() (full-
page navigation to the bff's /auth/login → entra round-trip)
when `anonymous` or `error`. error → same redirect as anonymous:
the bff-side login screen surfaces diagnostics more usefully
than a generic spa outage page would.
bffCredentialsInterceptor:
flips withCredentials: true on every request whose url starts
with AUTH_BFF_BASE_URL. replaces the per-call flag added in
#114 with a single point of truth; future bff calls inherit it
automatically.
bffUnauthorizedInterceptor:
calls AuthService.refresh() when a bff route (other than
/auth/me) answers 401. keeps the spa state in sync after
server-side session destruction (absolute-timeout, manual
revoke, idle-ttl expiry). /me is deliberately excluded —
refresh() itself calls /me, a 401 there would loop.
notable: the interceptor injects Injector and resolves
AuthService lazily inside catchError. injecting it eagerly at
the top would re-enter di while AuthService's own constructor
is still firing the bootstrap /me through this same
interceptor, raising a circular-construction error that
swallowed the request before the testing backend could record
it. standard angular pattern for "interceptor depends on a
service that uses HttpClient".
/profile demo route:
first real consumer of authGuard. lazy-loaded angular component
that renders the curated CurrentUser payload (displayName,
username, oid, tid). exercises the full loop guard → bff /me
→ spa render.
removed the per-call withCredentials: true from AuthService.refresh()
— the credentials interceptor handles it uniformly now. the spec
that pinned the per-call flag moved to
bff-credentials.interceptor.spec.ts where it belongs.
i18n: 6 new message ids + route.profile.title shipped with fr
translations in messages.fr.xlf.
19/19 feature-auth + 34/34 portal-shell + 123/123 portal-bff under
the clean-env ci repro (env -u redis_url … etc.). bundle main is
492 kb raw / 131 kb transfer — well under the 300 kb gzip budget
per adr-0017.
out of scope, landing in follow-ups:
- a real user-profile feature (settings, preferences, etc.)
- showing the auth-loading state on the route the guard blocks
(today the user sees the previous route until /me resolves)
126 lines
4.4 KiB
TypeScript
126 lines
4.4 KiB
TypeScript
import { provideHttpClient } from '@angular/common/http';
|
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { AUTH_BFF_BASE_URL, AUTH_NAVIGATOR } from './auth.config';
|
|
import { AuthService } from './auth.service';
|
|
import type { CurrentUser } from './auth.types';
|
|
|
|
const BFF_BASE = 'http://bff.test/api';
|
|
const ME_URL = `${BFF_BASE}/auth/me`;
|
|
|
|
const USER: CurrentUser = {
|
|
oid: 'user-oid',
|
|
tid: 'tenant-id',
|
|
username: 'jane.doe@apf.example',
|
|
displayName: 'Jane Doe',
|
|
};
|
|
|
|
interface Fixture {
|
|
service: AuthService;
|
|
http: HttpTestingController;
|
|
navigate: ReturnType<typeof vi.fn>;
|
|
}
|
|
|
|
function setup(): Fixture {
|
|
const navigate = vi.fn();
|
|
TestBed.configureTestingModule({
|
|
providers: [
|
|
provideHttpClient(),
|
|
provideHttpClientTesting(),
|
|
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
|
|
{ provide: AUTH_NAVIGATOR, useValue: navigate },
|
|
AuthService,
|
|
],
|
|
});
|
|
const service = TestBed.inject(AuthService);
|
|
const http = TestBed.inject(HttpTestingController);
|
|
return { service, http, navigate };
|
|
}
|
|
|
|
describe('AuthService', () => {
|
|
afterEach(() => {
|
|
TestBed.resetTestingModule();
|
|
});
|
|
|
|
describe('bootstrap fetch', () => {
|
|
it('starts in the loading state before /me resolves', () => {
|
|
const { service, http } = setup();
|
|
expect(service.state().kind).toBe('loading');
|
|
expect(service.isLoading()).toBe(true);
|
|
expect(service.currentUser()).toBeNull();
|
|
// Drain the in-flight bootstrap request to keep the controller clean.
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
|
|
it('transitions to authenticated when /me returns the user', async () => {
|
|
const { service, http } = setup();
|
|
http.expectOne(ME_URL).flush(USER);
|
|
// Let the awaited firstValueFrom commit the state.
|
|
await Promise.resolve();
|
|
expect(service.state()).toEqual({ kind: 'authenticated', user: USER });
|
|
expect(service.currentUser()).toEqual(USER);
|
|
expect(service.isLoading()).toBe(false);
|
|
});
|
|
|
|
it('transitions to anonymous on 401', async () => {
|
|
const { service, http } = setup();
|
|
http
|
|
.expectOne(ME_URL)
|
|
.flush({ error: 'unauthenticated' }, { status: 401, statusText: 'Unauthorized' });
|
|
await Promise.resolve();
|
|
expect(service.state().kind).toBe('anonymous');
|
|
expect(service.currentUser()).toBeNull();
|
|
});
|
|
|
|
it('transitions to error on a non-401 failure (network / 5xx / malformed)', async () => {
|
|
const { service, http } = setup();
|
|
http.expectOne(ME_URL).flush('boom', { status: 500, statusText: 'Internal Server Error' });
|
|
await Promise.resolve();
|
|
expect(service.state().kind).toBe('error');
|
|
expect(service.currentUser()).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('refresh()', () => {
|
|
it('can be called again after the bootstrap fetch and re-fetches /me', async () => {
|
|
const { service, http } = setup();
|
|
http.expectOne(ME_URL).flush(USER);
|
|
await Promise.resolve();
|
|
expect(service.state().kind).toBe('authenticated');
|
|
|
|
const promise = service.refresh();
|
|
http
|
|
.expectOne(ME_URL)
|
|
.flush({ error: 'unauthenticated' }, { status: 401, statusText: 'Unauthorized' });
|
|
await promise;
|
|
expect(service.state().kind).toBe('anonymous');
|
|
});
|
|
});
|
|
|
|
describe('URL accessors', () => {
|
|
it('derives me / login / logout URLs from the injected base', () => {
|
|
const { service, http } = setup();
|
|
expect(service.meUrl).toBe(`${BFF_BASE}/auth/me`);
|
|
expect(service.loginUrl).toBe(`${BFF_BASE}/auth/login`);
|
|
expect(service.logoutUrl).toBe(`${BFF_BASE}/auth/logout`);
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
});
|
|
|
|
describe('login() / logout()', () => {
|
|
it('navigates to /auth/login via AUTH_NAVIGATOR', () => {
|
|
const { service, http, navigate } = setup();
|
|
service.login();
|
|
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/auth/login`);
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
|
|
it('navigates to /auth/logout via AUTH_NAVIGATOR', () => {
|
|
const { service, http, navigate } = setup();
|
|
service.logout();
|
|
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/auth/logout`);
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
});
|
|
});
|