import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config'; import { UserService } from '../user/user.service'; import { SafeUser } from '../user/dto/user-safe.dto'; // Import SafeUser @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private configService: ConfigService, private userService: UserService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: configService.get('JWT_SECRET')!, }); } // Passport first verifies the JWT's signature and expiration, then calls this method. async validate(payload: { sub: string; username: string; }): Promise { const user = await this.userService.findOneByUsername(payload.username); if (user) { const { password, ...result } = user; return result as SafeUser; } return null; } }