-
Notifications
You must be signed in to change notification settings - Fork 0
/
action.guard.ts
37 lines (35 loc) · 1.25 KB
/
action.guard.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import {
BadRequestException,
CanActivate,
ExecutionContext,
Injectable,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { HEADER_BROKER_TOKEN } from '../constants';
import { PersistenceService } from '../persistence/persistence.service';
import { ActionGuardRequest } from './action-guard-request.interface';
import { actionFactory } from '../intention/dto/action.util';
@Injectable()
export class ActionGuard implements CanActivate {
constructor(private persistenceService: PersistenceService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<ActionGuardRequest>();
const tokenHeader = request.headers[HEADER_BROKER_TOKEN];
const token =
typeof tokenHeader === 'string' ? tokenHeader : tokenHeader[0];
const action = actionFactory(
await this.persistenceService.getIntentionAction(token),
);
const errors = await validate(action, {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
});
if (errors.length > 0) {
console.log(errors[0].children);
throw new BadRequestException('Validation failed');
}
request.brokerActionDto = action;
return !!action;
}
}