import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config'; import { JwtPayload } from '../interfaces/jwt-payload.interface'; import { UsersService } from '../../users/users.service'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private readonly configService: ConfigService, private readonly usersService: UsersService, ) { const secret = configService.get('JWT_SECRET'); if (!secret) { throw new Error('JWT_SECRET is not defined'); } super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: secret, }); } async validate(payload: JwtPayload): Promise { // Optionally validate that the user still exists and is active try { const user = await this.usersService.findOne(payload.sub); if (!user.isActive) { throw new UnauthorizedException('User account is deactivated'); } // Return the payload to be attached to the request return { sub: payload.sub, email: payload.email, roles: payload.roles, }; } catch { throw new UnauthorizedException('Invalid token'); } } }