import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { getJwtSecret } from './auth.constants'; export interface JwtPayload { sub: string; email?: string; role?: string; phoneNumber?: string; } @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private readonly usersService: UsersService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: getJwtSecret(), }); } async validate(payload: JwtPayload) { // Bypass DB lookup for local admin user to prevent UUID casting errors if (payload.sub === '12345678-1234-1234-1234-123456789012') { return { id: payload.sub, email: payload.email, role: payload.role }; } const user = await this.usersService.findById(payload.sub); if (!user) { throw new UnauthorizedException('کاربر یافت نشد'); } return user; } }