import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import type { Request } from 'express'; import type { PublicUser } from '../domain/models'; import { IS_PUBLIC_KEY, authDisabled, sessionIdFrom } from './auth.constants'; import { SessionService } from './session.service'; // The app-wide gate (registered as APP_GUARD). Every request must carry a // valid session (signed cookie, or bearer token for cookie-less clients) // unless the handler is @Public() or auth is disabled. // It resolves the session to a user and attaches it as req.user so handlers / // the @CurrentUser() decorator can read it. @Injectable() export class SessionAuthGuard implements CanActivate { constructor( private readonly reflector: Reflector, private readonly sessions: SessionService, ) {} async canActivate(context: ExecutionContext): Promise { const req = context .switchToHttp() .getRequest }>(); // @Public() on the handler or its controller opts out of the gate. We // still resolve any present session so @CurrentUser() works on public // routes (e.g. /auth/me), but never reject. const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass(), ]); const sessionId = sessionIdFrom(req); const user = await this.sessions.resolve(sessionId); if (user) req.user = user; if (authDisabled() || isPublic) return true; if (!user) throw new UnauthorizedException('Authentication required'); return true; } }