2026-01-28 13:03:28 +08:00
|
|
|
import {
|
|
|
|
|
Injectable,
|
|
|
|
|
CanActivate,
|
|
|
|
|
ExecutionContext,
|
|
|
|
|
ForbiddenException,
|
|
|
|
|
} from "@nestjs/common";
|
|
|
|
|
import { Reflector } from "@nestjs/core";
|
|
|
|
|
import { ROLES_KEY } from "../decorators/roles.decorator";
|
|
|
|
|
import { UserRole } from "../enums";
|
|
|
|
|
import { ErrorCode, ErrorMessage } from "../interfaces/response.interface";
|
2026-01-28 10:42:06 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 角色守卫
|
|
|
|
|
* 检查用户是否拥有所需的角色
|
|
|
|
|
*/
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class RolesGuard implements CanActivate {
|
|
|
|
|
constructor(private reflector: Reflector) {}
|
|
|
|
|
|
|
|
|
|
canActivate(context: ExecutionContext): boolean {
|
|
|
|
|
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(
|
|
|
|
|
ROLES_KEY,
|
|
|
|
|
[context.getHandler(), context.getClass()],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!requiredRoles) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { user } = context.switchToHttp().getRequest();
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
throw new ForbiddenException({
|
|
|
|
|
code: ErrorCode.UNAUTHORIZED,
|
|
|
|
|
message: ErrorMessage[ErrorCode.UNAUTHORIZED],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const hasRole = requiredRoles.some((role) => user.role === role);
|
|
|
|
|
|
|
|
|
|
if (!hasRole) {
|
|
|
|
|
throw new ForbiddenException({
|
|
|
|
|
code: ErrorCode.NO_PERMISSION,
|
|
|
|
|
message: ErrorMessage[ErrorCode.NO_PERMISSION],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|