feat: 增加登录鉴权和固定角色权限

This commit is contained in:
湛兮
2026-05-26 12:14:33 +08:00
parent 643244abab
commit 55b99b5307
21 changed files with 957 additions and 250 deletions
+29
View File
@@ -0,0 +1,29 @@
import type { FastifyRequest } from "fastify";
import { forbidden, unauthorized } from "../../shared/http-error";
import { authService } from "./auth.service";
// 统一 JWT 鉴权入口。后续新增需要登录的路由,复用这个 guard 即可。
export async function authGuard(request: FastifyRequest): Promise<void> {
const authorization = request.headers.authorization;
if (!authorization?.startsWith("Bearer ")) {
throw unauthorized("请先登录");
}
try {
await request.jwtVerify();
} catch {
throw unauthorized("登录已过期,请重新登录");
}
}
// 后台管理系统只允许超级管理员和拥有 admin 角色的员工访问。
export async function managementGuard(request: FastifyRequest): Promise<void> {
await authGuard(request);
const user = await authService.getCurrentUser(request.user);
if (!user.canManage) {
throw forbidden("当前账号没有后台管理权限");
}
}