|
| 1 | +import { BadRequestException, CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common'; |
| 2 | +import { Observable } from 'rxjs'; |
| 3 | +import { IRequestWithCognitoInfo } from '../authorization/cognito-decoded.interface.js'; |
| 4 | +import { CedarAction } from '../entities/cedar-authorization/cedar-action-map.js'; |
| 5 | +import { CedarAuthorizationService } from '../entities/cedar-authorization/cedar-authorization.service.js'; |
| 6 | +import { Messages } from '../exceptions/text/messages.js'; |
| 7 | +import { ValidationHelper } from '../helpers/validators/validation-helper.js'; |
| 8 | +import { validateUuidByRegex } from './utils/validate-uuid-by-regex.js'; |
| 9 | + |
| 10 | +@Injectable() |
| 11 | +export class ConnectionDiagramGuard implements CanActivate { |
| 12 | + constructor(private readonly cedarAuthService: CedarAuthorizationService) {} |
| 13 | + |
| 14 | + canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { |
| 15 | + return new Promise(async (resolve, reject) => { |
| 16 | + const request: IRequestWithCognitoInfo = context.switchToHttp().getRequest(); |
| 17 | + const cognitoUserName = request.decoded.sub; |
| 18 | + let connectionId: string = request.query.connectionId; |
| 19 | + if (!connectionId || (!validateUuidByRegex(connectionId) && !ValidationHelper.isValidNanoId(connectionId))) { |
| 20 | + connectionId = request.params?.slug || request.params?.connectionId; |
| 21 | + } |
| 22 | + if (!connectionId || (!validateUuidByRegex(connectionId) && !ValidationHelper.isValidNanoId(connectionId))) { |
| 23 | + reject(new BadRequestException(Messages.CONNECTION_ID_MISSING)); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + try { |
| 28 | + const allowed = await this.cedarAuthService.validate({ |
| 29 | + userId: cognitoUserName, |
| 30 | + action: CedarAction.ConnectionDiagram, |
| 31 | + connectionId, |
| 32 | + }); |
| 33 | + if (allowed) { |
| 34 | + resolve(true); |
| 35 | + return; |
| 36 | + } |
| 37 | + reject(new ForbiddenException(Messages.DONT_HAVE_PERMISSIONS)); |
| 38 | + } catch (e) { |
| 39 | + reject(e); |
| 40 | + } |
| 41 | + }); |
| 42 | + } |
| 43 | +} |
0 commit comments