37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
ForbiddenException,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common';
|
|
import { Reflector } from '@nestjs/core';
|
|
import type { Request } from 'express';
|
|
import type { CommunityRole } from '../global/database/schema';
|
|
import { ROLES_KEY } from './roles.decorator';
|
|
import './auth-request';
|
|
|
|
@Injectable()
|
|
export class RolesGuard implements CanActivate {
|
|
constructor(private readonly reflector: Reflector) {}
|
|
|
|
public canActivate(context: ExecutionContext): boolean {
|
|
const requiredRoles = this.reflector.getAllAndOverride<CommunityRole[]>(
|
|
ROLES_KEY,
|
|
[context.getHandler(), context.getClass()],
|
|
);
|
|
if (!requiredRoles || requiredRoles.length === 0) return true;
|
|
|
|
const req = context.switchToHttp().getRequest<Request>();
|
|
const user = req.user;
|
|
if (!user && req.identity) {
|
|
throw new ForbiddenException('No membership in this community.');
|
|
}
|
|
if (!user) throw new UnauthorizedException('Authentication required.');
|
|
if (!requiredRoles.includes(user.role)) {
|
|
throw new ForbiddenException('Insufficient role.');
|
|
}
|
|
return true;
|
|
}
|
|
}
|