Skip to content

Instantly share code, notes, and snippets.

@ujjwal-kr
Created August 27, 2020 07:52
Show Gist options
  • Save ujjwal-kr/3f70f1ff300e40cd61b18e9fafa59cb2 to your computer and use it in GitHub Desktop.
Save ujjwal-kr/3f70f1ff300e40cd61b18e9fafa59cb2 to your computer and use it in GitHub Desktop.
import { Injectable, NestMiddleware, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';
import * as jwt from 'jsonwebtoken';
import { KEY } from 'src/secret/secret';
@Injectable()
export class AdminMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void): void {
const token = req.headers.authorization;
const decoded: any = jwt.verify(token, KEY);
req.body.userId = decoded._id;
req.body.role == decoded.role;
if (decoded.role == 'admin') {
return next();
}
throw new HttpException("Not Authorized", HttpStatus.UNAUTHORIZED);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment