Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ./src/common/guards/jwt.guard.ts
- import {
- ExecutionContext,
- Injectable,
- UnauthorizedException,
- CanActivate,
- } from '@nestjs/common';
- import { ConfigService } from '@nestjs/config';
- import { verify } from 'jsonwebtoken';
- @Injectable()
- export class JwtGuard implements CanActivate {
- constructor(private configService: ConfigService) {}
- canActivate(context: ExecutionContext): boolean {
- const request = context.switchToHttp().getRequest();
- const {
- headers: { authorization },
- } = request;
- let jwtTokecn: string;
- if (
- authorization &&
- authorization.split(' ')[0] === 'Token'
- ) {
- jwtTokecn = authorization.split(' ')[1];
- }
- try {
- const payload = verify(
- jwtTokecn,
- this.configService.get<string>('JWT_SECRET'),
- );
- request.payload = payload;
- return true;
- } catch (err) {
- throw new UnauthorizedException();
- }
- }
- }
Add Comment
Please, Sign In to add comment