From 4119dc04fcf3736c2da05aac4e61dcee7a73d487 Mon Sep 17 00:00:00 2001 From: FORESTIER Fabien <fabien.forestier@soprasteria.com> Date: Tue, 26 Feb 2019 16:33:14 +0100 Subject: [PATCH] Add microservice middleware --- src/app.module.ts | 13 +++++++++++-- src/middlewares/microservice.middleware.ts | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 src/middlewares/microservice.middleware.ts diff --git a/src/app.module.ts b/src/app.module.ts index 5c47c89..a7e95e2 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,10 +1,19 @@ -import { Module } from '@nestjs/common'; +import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'; import { EmailModule } from './email/email.module'; import { ConfigModule } from './configuration/config.module'; +import { microserviceMiddleware } from './middlewares/microservice.middleware'; @Module({ imports: [ConfigModule, EmailModule], controllers: [], providers: [], }) -export class AppModule {} +export class AppModule { + configure(consumer: MiddlewareConsumer) { + // Applying the middleware that takes the Authorization header jwt payload and put it in the request headers + consumer + .apply(microserviceMiddleware).forRoutes( + { path: 'email/send', method: RequestMethod.POST }, + ); + } +} diff --git a/src/middlewares/microservice.middleware.ts b/src/middlewares/microservice.middleware.ts new file mode 100644 index 0000000..91704bb --- /dev/null +++ b/src/middlewares/microservice.middleware.ts @@ -0,0 +1,17 @@ +import { Logger, ForbiddenException } from '@nestjs/common'; + +export function microserviceMiddleware(req, res, next) { + Logger.log('[-] Untokenise middleware called'); + if (req.headers['x-consumer-groups']) { + const arr = req.headers['x-consumer-groups'].split(','); + arr.map(e => e.trim()); + const group = arr.find(e => e === 'microservice'); + if (group === undefined) { + throw new ForbiddenException('You can\'t access this ressource.'); + } else { + next(); + } + } else { + throw new ForbiddenException('You can\'t access this ressource.'); + } +} \ No newline at end of file -- GitLab