feat(server): add administrator feature (#6995)

This commit is contained in:
forehalo
2024-05-27 11:17:21 +00:00
parent 5ba9e2e9b1
commit aff166a0ef
23 changed files with 305 additions and 293 deletions

View File

@@ -0,0 +1,52 @@
import type {
CanActivate,
ExecutionContext,
OnModuleInit,
} from '@nestjs/common';
import { Injectable, UnauthorizedException, UseGuards } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { getRequestResponseFromContext } from '../../fundamentals';
import { FeatureManagementService } from '../features';
@Injectable()
export class AdminGuard implements CanActivate, OnModuleInit {
private feature!: FeatureManagementService;
constructor(private readonly ref: ModuleRef) {}
onModuleInit() {
this.feature = this.ref.get(FeatureManagementService, { strict: false });
}
async canActivate(context: ExecutionContext) {
const { req } = getRequestResponseFromContext(context);
let allow = false;
if (req.user) {
allow = await this.feature.isAdmin(req.user.id);
}
if (!allow) {
throw new UnauthorizedException('Your operation is not allowed.');
}
return true;
}
}
/**
* This guard is used to protect routes/queries/mutations that require a user to be administrator.
*
* @example
*
* ```typescript
* \@Admin()
* \@Mutation(() => UserType)
* createAccount(userInput: UserInput) {
* // ...
* }
* ```
*/
export const Admin = () => {
return UseGuards(AdminGuard);
};

View File

@@ -0,0 +1 @@
export * from './admin-guard';