From dde3be8abd3ad630999cc04269d029830fbe7a99 Mon Sep 17 00:00:00 2001 From: Ahmet AYDIN Date: Fri, 7 Feb 2020 21:46:57 +0300 Subject: [PATCH] token middleware added --- libs/middlewares/token.middleware.ts | 44 ++++++++++++++++++++++++++++ src/app.module.ts | 16 ++++++++-- 2 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 libs/middlewares/token.middleware.ts diff --git a/libs/middlewares/token.middleware.ts b/libs/middlewares/token.middleware.ts new file mode 100644 index 0000000..8f906cb --- /dev/null +++ b/libs/middlewares/token.middleware.ts @@ -0,0 +1,44 @@ +import { + Injectable, + NestMiddleware, + HttpException, + HttpStatus, +} from '@nestjs/common'; +import { Request, Response } from 'express'; +import * as jwt from 'jsonwebtoken'; +import environment from 'tools/environment/environment'; + +@Injectable() +export class TokenMiddleware implements NestMiddleware { + use(req: Request, res: Response, next: Function) { + const authJsonWebToken = req.headers.authorization; + + if (req.baseUrl !== '/api/login') { + if (!authJsonWebToken) { + next(); + throw new HttpException('Jwt could not found!', HttpStatus.FORBIDDEN); + } else { + try { + const user = jwt.verify( + authJsonWebToken.slice(7, authJsonWebToken.length), + environment.jwtText, + ); + if (user) { + req['user'] = user; + next(); + } else { + throw new HttpException( + 'something went wrong !', + HttpStatus.GATEWAY_TIMEOUT, + ); + } + } catch (ex) { + throw new HttpException(ex.message, HttpStatus.UNAUTHORIZED); + } + } + } else { + next(); + return; + } + } +} diff --git a/src/app.module.ts b/src/app.module.ts index ab5c7e5..7875f24 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,4 +1,9 @@ -import { Module } from '@nestjs/common'; +import { + Module, + NestModule, + MiddlewareConsumer, + RequestMethod, +} from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { UserModule } from './user/user.module'; @@ -17,6 +22,7 @@ import { ProductModule } from './product/product.module'; import { RoleModule } from './role/role.module'; import { TotalModule } from './total/total.module'; import { LoginModule } from './login/login.module'; +import { TokenMiddleware } from 'libs/middlewares/token.middleware'; @Module({ imports: [ @@ -39,4 +45,10 @@ import { LoginModule } from './login/login.module'; controllers: [AppController], providers: [AppService], }) -export class AppModule {} +export class AppModule implements NestModule { + configure(consumer: MiddlewareConsumer) { + consumer + .apply(TokenMiddleware) + .forRoutes({ path: '*', method: RequestMethod.ALL }); + } +}