import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { AccessStore } from '@shared/application/access.store'; import { Capability } from '@shared/domain/capability'; import { SessionStore } from './application/session.store'; /** Route guard: only let authenticated users in; otherwise redirect to /login. */ export const authGuard: CanActivateFn = () => { const store = inject(SessionStore); const router = inject(Router); return store.isAuthenticated() ? true : router.createUrlTree(['/login']); }; /** * Route guard factory (PRD-0002 §6): authenticated AND holding `capability`, else * redirect. Used by the admin pages (`/brief/huisstijl`, `/beheer/stamdata`). * * **Async on purpose:** `can()` is deny-by-default, so it must not be read while `/me` * is still loading — it would deny an entitled admin and bounce them. We await * `AccessStore.whenReady()` (caps resolved) before deciding. An unauthenticated user * goes to `/login`; an authenticated-but-unentitled user goes to `/dashboard` (they're * logged in, just not allowed here — no re-login loop). The backend re-enforces * regardless (403); this guard is the UX pre-gate. */ export function capabilityGuard(capability: Capability): CanActivateFn { return async () => { const session = inject(SessionStore); const access = inject(AccessStore); const router = inject(Router); if (!session.isAuthenticated()) return router.createUrlTree(['/login']); await access.whenReady(); return access.can(capability) ? true : router.createUrlTree(['/dashboard']); }; }