import { Injectable } from '@nestjs/common'; import { AppLogger } from '../../../logger'; import { AclData } from '../../authorization/interfaces/acl-data.interface'; import { AclResourceIdLocation } from '../enums'; @Injectable() export class AclGuardService { private readonly TAG: string = `${this.constructor.name}`; constructor() { AppLogger.log('Init', this.TAG); } public canActivate(request, aclData: AclData): boolean { try { let resourceName: string = null; let resourceId: string = null; if (aclData) { resourceName = this.extractResourceName(aclData.resourceName); if (!resourceName) { return null; } if (aclData.resourceId) { resourceId = this.extractResourceId(request, aclData.resourceId.location, aclData.resourceId.name); if (!resourceId) { return null; } } } request.resourceName = resourceName; request.resourceId = resourceId; return true; } catch (e) { AppLogger.error(e, this.TAG); return null; } } private extractResourceName(resourceName: string): string { if (resourceName) { AppLogger.debug(`Set ACL Resource Name on request - '${resourceName}'`, this.TAG); return resourceName; } else { AppLogger.error(`No resource name received`, this.TAG); return null; } } private extractResourceId(request, resourceIdLocation: AclResourceIdLocation, resourceIdNameInLocation: string): string { if (resourceIdLocation && resourceIdNameInLocation && request[resourceIdLocation][resourceIdNameInLocation]) { const resourceId: string = request[resourceIdLocation][resourceIdNameInLocation]; AppLogger.debug(`Set ACL Resource ID on request - '${resourceId}'`, this.TAG); return resourceId; } else { AppLogger.error(`No resource id found on location - '${resourceIdLocation}', by name - '${resourceIdNameInLocation}'`, this.TAG); AppLogger.error(`location - '${resourceIdLocation}' data received from request - ${JSON.stringify(request[resourceIdLocation])}`, this.TAG); return null; } } }