import { Injectable, UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from '../services/auth.service'; import { JwtPayload } from '../interfaces/jwt-payload.interface'; @Injectable() export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh') { constructor( private readonly configService: ConfigService, private readonly authService: AuthService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: configService.get('JWT_REFRESH_SECRET'), passReqToCallback: true, }); } /** * Validate the JWT refresh token payload and return the user */ async validate(req: any, payload: JwtPayload) { try { // Check if this is a refresh token if (!payload.isRefreshToken) { throw new UnauthorizedException('Invalid token type'); } // Extract the refresh token from the request const refreshToken = ExtractJwt.fromAuthHeaderAsBearerToken()(req); if (!refreshToken) { throw new UnauthorizedException('Refresh token not found'); } // Validate the user const user = await this.authService.validateJwtUser(payload); // Attach the refresh token to the user object for later use return { ...user, refreshToken, }; } catch (error) { throw new UnauthorizedException('Invalid refresh token'); } } }