feat: 开发user、auth相关接口,初始化后台管理项目admin

This commit is contained in:
R524809
2025-11-19 17:42:53 +08:00
parent 7acadf191f
commit d195495449
45 changed files with 3016 additions and 101 deletions

View File

@@ -0,0 +1,44 @@
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles) {
// 如果没有设置角色要求,允许访问
return true;
}
const request = context.switchToHttp().getRequest<{
user?: { role: string };
}>();
const user = request.user;
if (!user) {
throw new ForbiddenException('未授权访问');
}
const hasRole = requiredRoles.some((role) => user.role === role);
if (!hasRole) {
throw new ForbiddenException(
`需要以下角色之一:${requiredRoles.join('、')}`,
);
}
return true;
}
}