import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException, } from '@nestjs/common'; import type { Request } from 'express'; import type { PublicUser } from '../domain/models'; import { authDisabled } from './auth.constants'; // Route guard for operator-level actions (global settings, user management): // requires an admin session - or no gate at all (AUTH_DISABLED single-user // mode, where the local operator is the admin). Runs after the global // SessionAuthGuard, which has already resolved req.user from the cookie. @Injectable() export class AdminGuard implements CanActivate { canActivate(ctx: ExecutionContext): boolean { if (authDisabled()) return true; const req = ctx.switchToHttp().getRequest(); const user = req.user as PublicUser | undefined; if (!user) throw new UnauthorizedException('Not signed in'); if (user.role !== 'admin') throw new ForbiddenException('Requires an admin account'); return true; } }