Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142import { 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<boolean> { const req = context .switchToHttp() .getRequest<Request & { user?: PublicUser; signedCookies?: Record<string, string> }>();
// @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<boolean>(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; }}