26 lines
778 B
TypeScript
26 lines
778 B
TypeScript
import { UserInfo, matchPrivileges } from '@freeblox/shared';
|
|
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
|
import { Reflector } from '@nestjs/core';
|
|
import { Response } from 'express';
|
|
|
|
@Injectable()
|
|
export class PrivilegesGuard implements CanActivate {
|
|
constructor(private reflector: Reflector) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const privileges = this.reflector.get<string[]>(
|
|
'privileges',
|
|
context.getHandler(),
|
|
);
|
|
|
|
if (!privileges) {
|
|
return true;
|
|
}
|
|
|
|
const response = context.switchToHttp().getResponse() as Response;
|
|
const user = response.locals.user as UserInfo;
|
|
if (!user) return false;
|
|
return matchPrivileges(privileges, user.privileges || []);
|
|
}
|
|
}
|