Flatten the admin route guard to guard clauses
Angular · Angular · intermediate · modification
Tidies adminGuard by dropping the braces on each `if` and letting the guard fall through as flat early-return clauses. Pure readability pass on a functional CanActivateFn, behavior is unchanged, and the routing tests still pass.
adminGuard protects the /admin route tree (user management, billing, feature flags). Returning true activates the route, so any user the guard approves reaches the admin console.
Requirements
- adminGuard must return `true` (activate the route) only for a signed-in user whose `roles` include `'admin'`.
- An unauthenticated visitor (no current user) is redirected to `/login`; a signed-in user without the `admin` role is redirected to `/forbidden`.
- Refactor the braced `if` blocks into flat early-return guard clauses; the authorization logic itself must not change.
Files touched
- src/app/guards/admin.guard.ts
--- src/app/guards/admin.guard.ts
const user = auth.currentUser();
- if (!user) {
+ if (!user)
return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
- }
+ return true;
- if (!user.roles.includes('admin')) {
+ if (!user.roles.includes('admin'))
return router.createUrlTree(['/forbidden']);
- }
return true;