UNPKG

@bitloops/bl-boilerplate-infra-nest-auth-passport

Version:
58 lines (57 loc) 2.73 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { Injectable } from '@nestjs/common'; import { asyncLocalStorage } from '@bitloops/bl-boilerplate-core'; let AsyncLocalStorageInterceptor = class AsyncLocalStorageInterceptor { intercept(context, next) { if (context.getType() === 'http') { // do something that is only important in the context of regular HTTP requests (REST) const request = context.switchToHttp().getRequest(); const store = asyncLocalStorage.getStore(); if (!store) throw new Error('No store found, did you forget to attach correlation middleware?'); if (!request.user) { return next.handle(); } const token = this.getJWTToken(request); const email = request.user.email; const userId = request.user.userId; store.set('context', { userId, email, jwt: token }); return next.handle(); } else if (context.getType() === 'rpc') { // do something that is only important in the context of Microservice requests const data = context.switchToRpc().getData(); const requestContext = context.switchToRpc().getContext(); const { decodedToken, jwt } = requestContext; const store = asyncLocalStorage.getStore(); if (!store) throw new Error('No store found, did you forget to attach correlation middleware?'); if (!decodedToken) { return next.handle(); } const email = decodedToken.email; const userId = decodedToken.sub; store.set('context', { userId, email, jwt }); return next.handle(); } // TODO Handle graphQL return next.handle(); } getJWTToken(req) { const authHeader = req.headers['authorization']; if (authHeader) { const token = authHeader.split('Bearer ')[1]; return token; } return ''; } }; AsyncLocalStorageInterceptor = __decorate([ Injectable() ], AsyncLocalStorageInterceptor); export { AsyncLocalStorageInterceptor };