Advertisement
Guest User

Untitled

a guest
Apr 17th, 2019
485
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { BadRequestException, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
  2. import { PassportStrategy } from '@nestjs/passport';
  3. import { Strategy, ExtractJwt } from 'passport-jwt';
  4. import * as process from "process";
  5. import { JwtPayload } from './auth/auth.service';
  6. import { UsersService } from '../../shared/services/users/users.service';
  7. import { JWT_SECRET_KEY_TOKEN } from '../auth.tokens';
  8.  
  9. @Injectable()
  10. export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  11.  
  12.   constructor(
  13.     private userService: UsersService,
  14.     @Inject(JWT_SECRET_KEY_TOKEN) private secretToken: string
  15.   ) {
  16.     super({
  17.       jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  18.       secretOrKey: secretToken,
  19.     });
  20.   }
  21.  
  22.   async validate(payload: JwtPayload, done: (err?, user?) => void) {
  23.     try {
  24.       const user = (await this.userService.findByEmail(payload.email))[0];
  25.       if (!user) {
  26.         throw new BadRequestException('User doesn\'t exists');
  27.       }
  28.  
  29.       // вторым параметром передается user, его можно получить в контроллере через request.user
  30.       done(null, {...payload, ...user});
  31.     } catch (err) {
  32.       throw new UnauthorizedException('unauthorized', err.message);
  33.     }
  34.   }
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement