fix: 修复RolesGuard因AuthGuard结构变化导致的不可用的问题
This commit is contained in:
@@ -1,17 +1,27 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
|
||||||
CanActivate,
|
CanActivate,
|
||||||
ExecutionContext,
|
ExecutionContext,
|
||||||
ForbiddenException,
|
ForbiddenException,
|
||||||
Injectable,
|
Injectable,
|
||||||
|
InternalServerErrorException,
|
||||||
|
Logger,
|
||||||
|
UnauthorizedException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Reflector } from '@nestjs/core';
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { AuthUser } from 'src/auth/decorator/current-user.decorator';
|
||||||
import { Role } from 'src/auth/role.enum';
|
import { Role } from 'src/auth/role.enum';
|
||||||
import { User } from 'src/user/entities/user.entity';
|
import { UserService } from 'src/user/user.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class RolesGuard implements CanActivate {
|
export class RolesGuard implements CanActivate {
|
||||||
constructor(private reflector: Reflector) {}
|
|
||||||
|
private logger = new Logger(RolesGuard.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private reflector: Reflector,
|
||||||
|
private readonly userService: UserService,
|
||||||
|
) { }
|
||||||
|
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
const requiredRoles = this.reflector.getAllAndOverride<Role[] | undefined>(
|
const requiredRoles = this.reflector.getAllAndOverride<Role[] | undefined>(
|
||||||
@@ -21,11 +31,23 @@ export class RolesGuard implements CanActivate {
|
|||||||
|
|
||||||
if (!requiredRoles) return true;
|
if (!requiredRoles) return true;
|
||||||
|
|
||||||
const request = context.switchToHttp().getRequest();
|
const request = context.switchToHttp().getRequest<Request>();
|
||||||
const user = request.user as User | void;
|
const authUser = request.user as AuthUser;
|
||||||
|
|
||||||
|
if (!authUser) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Path: ${request.path} has RolesGuard enabled, but it seems AuthGuard was forgotten.`
|
||||||
|
)
|
||||||
|
throw new InternalServerErrorException('服务器内部错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { userId } = authUser;
|
||||||
|
const user = await this.userService.findOne({ userId })
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new BadRequestException('服务器内部错误');
|
this.logger.warn(
|
||||||
|
`UserId: ${user.userId} has a valid login credential, but the user information does not exist.`
|
||||||
|
)
|
||||||
|
throw new UnauthorizedException('用户不存在');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!requiredRoles.some((role) => user.roles.includes(role))) {
|
if (!requiredRoles.some((role) => user.roles.includes(role))) {
|
||||||
|
|||||||
Reference in New Issue
Block a user