import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { Observable } from 'rxjs'; import { GuardMetadata } from '../enums'; import { MicroServiceSub } from '../enums'; import { MicroServiceGuardService } from './services'; import { AppLogger } from '../../logger'; @Injectable() export class MicroServiceGuard implements CanActivate { private readonly TAG: string = `${this.constructor.name}`; constructor(private readonly reflector: Reflector, private readonly microServiceGuardService: MicroServiceGuardService) { AppLogger.log('Init', this.TAG); } canActivate( context: ExecutionContext, ): boolean | Promise | Observable { const request: any = context.switchToHttp().getRequest(); if (request && request.headers && request.headers.authorization) { const jwt: string = request.headers.authorization; const microServiceAllowed: MicroServiceSub = this.reflector.get(GuardMetadata.MICRO_SERVICE, context.getHandler()); const microServiceSub: string = this.microServiceGuardService.getMicroServiceSub(microServiceAllowed); return this.validateRequest(jwt, microServiceSub); } throw new UnauthorizedException(); } async validateRequest(token: string, microServiceAllowed: string): Promise { try { const isValid: boolean = await this.microServiceGuardService.verify(token, microServiceAllowed); if (!isValid) { throw new UnauthorizedException(); } return isValid; } catch (e) { throw new UnauthorizedException(); } } }