jwt.strategy.ts 829 B

1234567891011121314151617181920212223
  1. import { Injectable, UnauthorizedException } from '@nestjs/common';
  2. import { PassportStrategy } from '@nestjs/passport';
  3. import { ExtractJwt, Strategy } from 'passport-jwt';
  4. import { JwtPayload } from './auth-types';
  5. import { AuthService, JWT_SECRET } from './auth.service';
  6. @Injectable()
  7. export class JwtStrategy extends PassportStrategy(Strategy) {
  8. constructor(private readonly authService: AuthService) {
  9. super({
  10. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  11. secretOrKey: JWT_SECRET,
  12. });
  13. }
  14. async validate(payload: JwtPayload, done: (err: Error, user: any) => void) {
  15. const user = await this.authService.validateUser(payload);
  16. if (!user) {
  17. return done(new UnauthorizedException(), false);
  18. }
  19. done(null, user);
  20. }
  21. }