37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
import { inject } from '@angular/core';
|
|
import { CanActivateFn, Router } from '@angular/router';
|
|
import { AuthService } from '../services/auth.service';
|
|
import { BootstrapService } from '../services/bootstrap.service';
|
|
import { decideAdminGuard, AdminGuardDecision } from './admin.guard.decision';
|
|
|
|
export { decideAdminGuard } from './admin.guard.decision';
|
|
export type { AdminGuardDecision } from './admin.guard.decision';
|
|
|
|
export interface AdminGuardDeps {
|
|
auth: AuthService;
|
|
bootstrap: BootstrapService;
|
|
router: Router;
|
|
}
|
|
|
|
export async function decideAdminAccessGuard(
|
|
deps: AdminGuardDeps,
|
|
): Promise<true | ReturnType<Router['createUrlTree']>> {
|
|
await deps.bootstrap.ready();
|
|
await deps.auth.waitUntilHydrated();
|
|
|
|
const decision: AdminGuardDecision = decideAdminGuard({
|
|
initialized: deps.bootstrap.initialized(),
|
|
isAuthenticated: deps.auth.isAuthenticated(),
|
|
role: deps.auth.currentUser()?.role,
|
|
});
|
|
|
|
if (decision.kind === 'allow') return true;
|
|
return deps.router.createUrlTree([decision.path]);
|
|
}
|
|
|
|
export const adminGuard: CanActivateFn = () => {
|
|
const auth = inject(AuthService);
|
|
const bootstrap = inject(BootstrapService);
|
|
const router = inject(Router);
|
|
return decideAdminAccessGuard({ auth, bootstrap, router });
|
|
}; |