mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 00:52:50 +00:00
39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
ForbiddenException,
|
|
Injectable,
|
|
Type,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common';
|
|
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
|
|
|
|
import { hasFreightPermission } from './freight-permission.util';
|
|
|
|
export function FreightPermissionGuard(
|
|
permissions: string[],
|
|
): Type<CanActivate> {
|
|
@Injectable()
|
|
class FreightPermissionsGuard implements CanActivate {
|
|
canActivate(context: ExecutionContext): boolean {
|
|
const request = context.switchToHttp().getRequest<{ user?: TCurrentUser }>();
|
|
const user = request.user;
|
|
|
|
if (!permissions?.length) return true;
|
|
if (!user) {
|
|
throw new UnauthorizedException('Authentication required');
|
|
}
|
|
|
|
if (permissions.some((p) => hasFreightPermission(user, p))) {
|
|
return true;
|
|
}
|
|
|
|
throw new ForbiddenException(
|
|
`Missing permission. Required one of: ${permissions.join(', ')}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
return FreightPermissionsGuard;
|
|
}
|