feat: add admin module
This commit is contained in:
@@ -1,8 +1,14 @@
|
||||
import { IS_PUBLIC_KEY } from '../constants';
|
||||
import { Role } from '@/common/enums/roles.enum';
|
||||
import { IS_PUBLIC_KEY, ROLES_KEY } from '../constants';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import { ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import type { Request } from 'express';
|
||||
import { User } from '@/modules/users/entities/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class GlobalAuthGuard extends JwtAuthGuard {
|
||||
@@ -15,9 +21,7 @@ export class GlobalAuthGuard extends JwtAuthGuard {
|
||||
super();
|
||||
}
|
||||
|
||||
canActivate(
|
||||
context: ExecutionContext,
|
||||
): boolean | Promise<boolean> | Observable<boolean> {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
@@ -27,6 +31,24 @@ export class GlobalAuthGuard extends JwtAuthGuard {
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.canActivate(context);
|
||||
await super.canActivate(context);
|
||||
|
||||
const requiredRoles = this.reflector.getAllAndOverride<Array<Role>>(
|
||||
ROLES_KEY,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
|
||||
if (requiredRoles && requiredRoles.length > 0) {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const user = request.user as User;
|
||||
|
||||
const hasRole = requiredRoles.includes(user.role);
|
||||
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('auth.errors.accessDenied');
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user