nodejsdeveloperskh

do not user passportjs in nestjs

Sep 13th, 2021 (edited)
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ./src/common/guards/jwt.guard.ts
  2.  
  3. import {
  4.     ExecutionContext,
  5.     Injectable,
  6.     UnauthorizedException,
  7.     CanActivate,
  8. } from '@nestjs/common';
  9. import { ConfigService } from '@nestjs/config';
  10. import { verify } from 'jsonwebtoken';
  11.  
  12.  
  13. @Injectable()
  14. export class JwtGuard implements CanActivate {
  15.     constructor(private configService: ConfigService) {}
  16.     canActivate(context: ExecutionContext): boolean {
  17.         const request = context.switchToHttp().getRequest();
  18.         const {
  19.             headers: { authorization },
  20.         } = request;
  21.         let jwtTokecn: string;
  22.         if (
  23.             authorization &&
  24.             authorization.split(' ')[0] === 'Token'
  25.         ) {
  26.             jwtTokecn = authorization.split(' ')[1];
  27.         }
  28.  
  29.         try {
  30.             const payload = verify(
  31.                 jwtTokecn,
  32.                 this.configService.get<string>('JWT_SECRET'),
  33.             );
  34.             request.payload = payload;
  35.             return true;
  36.         } catch (err) {
  37.             throw new UnauthorizedException();
  38.         }
  39.     }
  40. }
  41.  
Add Comment
Please, Sign In to add comment