-
Notifications
You must be signed in to change notification settings - Fork 228
/
roles.guard.ts
35 lines (29 loc) · 1.03 KB
/
roles.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
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql';
import type { Request } from 'express';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
public canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.getAllAndOverride<string[] | undefined>('roles', [
context.getHandler(), // Method Roles
context.getClass(), // Controller Roles
]);
if (!roles) {
return true;
}
let request: Request;
if (context.getType<GqlContextType>() === 'graphql') {
const ctx = GqlExecutionContext.create(context).getContext<{ req: Request }>();
request = ctx.req;
} else {
request = context.switchToHttp().getRequest<Request>();
}
const { user } = request;
if (!user) {
return false;
}
return user.roles.some((role: string) => roles.includes(role));
}
}