import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { AppLogger } from '../../logger'; import { Observable } from 'rxjs'; import { ProjectGuardService } from './services'; import { DecodedToken } from '../dto'; @Injectable() export class ProjectGuard implements CanActivate { private readonly TAG: string = `${this.constructor.name}`; constructor(private readonly projectGuardService: ProjectGuardService) { AppLogger.log('Init', this.TAG); } canActivate( context: ExecutionContext, ): boolean | Promise | Observable { const request = context.switchToHttp().getRequest(); const projectShortId: string = request.params ? request.params.project_short_id : null; if (request && request.headers && request.headers.authorization && projectShortId) { if (this.validateRequest(request.token, projectShortId)) { request.projectShortId = projectShortId; return true; } } AppLogger.error('No Permissions Property on Headers or no project short id on params', this.TAG); throw new UnauthorizedException(); } async validateRequest(token: DecodedToken, projectShortId: string): Promise { try { AppLogger.log(`Verify request for project - ${projectShortId}`, this.TAG); const isValid: boolean = await this.projectGuardService.verify(token, projectShortId); if (!isValid) { throw new UnauthorizedException(); } return isValid; } catch (e) { AppLogger.error(e, this.TAG); throw new UnauthorizedException(); } } }