feat(api): add authentication and identity guards
This commit is contained in:
1 parent
e4aa9e6f35
commit
638cae6a76
16 files changed
+592
No files matched your search
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import type { Request } from 'express';
|
||||
import { CommunityRole, UserDocument } 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 as UserDocument | undefined;
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user