From 89e99dc9e9ba3a5343b053cf09738eb336acbc60 Mon Sep 17 00:00:00 2001 From: tone Date: Fri, 19 Dec 2025 19:01:00 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DRolesGuard=E5=9B=A0Aut?= =?UTF-8?q?hGuard=E7=BB=93=E6=9E=84=E5=8F=98=E5=8C=96=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E7=9A=84=E4=B8=8D=E5=8F=AF=E7=94=A8=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/backend/src/common/guard/roles.guard.ts | 34 ++++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/apps/backend/src/common/guard/roles.guard.ts b/apps/backend/src/common/guard/roles.guard.ts index 65340e2..9c3f072 100644 --- a/apps/backend/src/common/guard/roles.guard.ts +++ b/apps/backend/src/common/guard/roles.guard.ts @@ -1,17 +1,27 @@ import { - BadRequestException, CanActivate, ExecutionContext, ForbiddenException, Injectable, + InternalServerErrorException, + Logger, + UnauthorizedException, } from '@nestjs/common'; 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 { User } from 'src/user/entities/user.entity'; +import { UserService } from 'src/user/user.service'; @Injectable() 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 { const requiredRoles = this.reflector.getAllAndOverride( @@ -21,11 +31,23 @@ export class RolesGuard implements CanActivate { if (!requiredRoles) return true; - const request = context.switchToHttp().getRequest(); - const user = request.user as User | void; + const request = context.switchToHttp().getRequest(); + 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) { - 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))) {