import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from "@nestjs/common"; import { JwtService } from "@nestjs/jwt"; import { Request } from "express"; import { JwtPayload } from "../types/payload.types"; @Injectable() export class AuthGuard implements CanActivate { constructor(private readonly jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = this.extractTokenFromHeader(request); if (!token) { throw new UnauthorizedException("No token provided"); } try { const payload: JwtPayload = await this.jwtService.verifyAsync(token); request["user"] = payload; } catch { throw new UnauthorizedException("Invalid or expired token"); } return true; } private extractTokenFromHeader(request: Request): string | undefined { const [type, token] = request.headers.authorization?.split(" ") ?? []; return type === "Bearer" ? token : undefined; } }