| 123456789101112131415161718192021222324252627282930313233 |
- import { Injectable } from '@nestjs/common';
- import { PassportStrategy } from '@nestjs/passport';
- import { ExtractJwt, Strategy } from 'passport-jwt';
- import { ConfigService } from '@nestjs/config';
- import { UserService } from '../user/user.service';
- import { SafeUser } from '../user/dto/user-safe.dto'; // Import SafeUser
- @Injectable()
- export class JwtStrategy extends PassportStrategy(Strategy) {
- constructor(
- private configService: ConfigService,
- private userService: UserService,
- ) {
- super({
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
- ignoreExpiration: false,
- secretOrKey: configService.get<string>('JWT_SECRET')!,
- });
- }
- // Passport first verifies the JWT's signature and expiration, then calls this method.
- async validate(payload: {
- sub: string;
- username: string;
- }): Promise<SafeUser | null> {
- const user = await this.userService.findOneByUsername(payload.username);
- if (user) {
- const { password, ...result } = user;
- return result as SafeUser;
- }
- return null;
- }
- }
|