Skip to content

Commit

Permalink
token middleware added
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahmet AYDIN committed Feb 7, 2020
1 parent d0c262a commit dde3be8
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
44 changes: 44 additions & 0 deletions libs/middlewares/token.middleware.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
16 changes: 14 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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: [
Expand All @@ -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 });
}
}

0 comments on commit dde3be8

Please sign in to comment.