import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common' import { Reflector } from '@nestjs/core' import { JwtService } from '@nestjs/jwt' import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator' import { IWithJWTPayloadRequest } from '../../common/models/token-model' @Injectable() export class JwtAuthGuard implements CanActivate { constructor( private jwt: JwtService, private reflector: Reflector, ) {} async canActivate(context: ExecutionContext): Promise { const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass(), ]) if (isPublic) return true const req = context.switchToHttp().getRequest() // Log headers to inspect whether Authorization is present // Try token from cookie first, then from Authorization header (Bearer) let token: string | undefined = req.cookies?.accessToken if (!token) { const authHeader = (req.headers.authorization || req.headers.Authorization) as | string | undefined if (authHeader && authHeader.startsWith('Bearer ')) { token = authHeader.slice(7) } } if (!token) throw new UnauthorizedException('Missing access token') try { const payload = this.jwt.verify(token, { secret: process.env.JWT_SECRET || 'secret', }) console.log(payload) if (payload.type !== 'POS') throw new UnauthorizedException('Invalid or expired token') // Set the typed dataPayload to the request req.dataPayload = payload return true } catch (err) { console.log(err) throw new UnauthorizedException('Invalid or expired token') } } }