All files / src/auth jwt.strategy.ts

0% Statements 0/14
0% Branches 0/9
0% Functions 0/2
0% Lines 0/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                                                                       
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
 
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET || 'devsecret',
      passReqToCallback: true, // agar req bisa diakses di validate
    });
  }
 
  async validate(req: Request, payload: any) {
    // Ambil token dari header Authorization
    const authHeader = req.headers['authorization'] || '';
    const token = Array.isArray(authHeader)
      ? authHeader[0]?.replace('Bearer ', '')
      : authHeader.replace('Bearer ', '');
 
    // Cek blacklist
    Iif (token && this.authService.isTokenBlacklisted(token)) {
      throw new UnauthorizedException('Token revoked');
    }
 
    return {
      userId: payload.sub,
      username: payload.username,
      role: payload.role,
    };
  }
}