jwt.strategy.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. role?: string;
  24. tenantId?: string;
  25. }): Promise<SafeUser | null> {
  26. const user = await this.userService.findOneByUsername(payload.username);
  27. if (user) {
  28. const { password, ...result } = user;
  29. return {
  30. ...result,
  31. role: payload.role || result.role,
  32. tenantId: payload.tenantId || result.tenantId
  33. } as SafeUser;
  34. }
  35. return null;
  36. }
  37. }