jwt.strategy.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. import { Injectable } from '@nestjs/common';
  2. import { PassportStrategy } from '@nestjs/passport';
  3. import { ExtractJwt, Strategy } from 'passport-jwt';
  4. import { ConfigService } from '@nestjs/config';
  5. import { UserService } from '../user/user.service';
  6. import { SafeUser } from '../user/dto/user-safe.dto'; // Import SafeUser
  7. @Injectable()
  8. export class JwtStrategy extends PassportStrategy(Strategy) {
  9. constructor(
  10. private configService: ConfigService,
  11. private userService: UserService,
  12. ) {
  13. super({
  14. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  15. ignoreExpiration: false,
  16. secretOrKey: configService.get<string>('JWT_SECRET')!,
  17. });
  18. }
  19. // Passport first verifies the JWT's signature and expiration, then calls this method.
  20. async validate(payload: {
  21. sub: string;
  22. username: string;
  23. }): Promise<SafeUser | null> {
  24. const user = await this.userService.findOneByUsername(payload.username);
  25. if (user) {
  26. const { password, ...result } = user;
  27. return result as SafeUser;
  28. }
  29. return null;
  30. }
  31. }