import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import type { Request } from 'express'; import type { JwtPayload } from './jwt-payload.interface'; export interface AuthenticatedRequest extends Request { user: JwtPayload; } @Injectable() export class JwtAuthGuard implements CanActivate { constructor(private readonly jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const authHeader = request.headers.authorization; const token = authHeader?.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : undefined; if (!token) throw new UnauthorizedException('Jeton manquant'); try { request.user = await this.jwtService.verifyAsync(token); return true; } catch { throw new UnauthorizedException('Jeton invalide ou expire'); } } }