46 lines
1.4 KiB
TypeScript
46 lines
1.4 KiB
TypeScript
import type { FastifyRequest } from "fastify";
|
|
import { forbidden, unauthorized } from "../../shared/http-error";
|
|
import { authService } from "./auth.service";
|
|
import {
|
|
hasPermission,
|
|
type PermissionCode,
|
|
} from "../permissions/permission.policy";
|
|
|
|
// 统一 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.permissions.includes("*") && user.permissions.length === 0) {
|
|
throw forbidden("当前账号没有后台管理权限");
|
|
}
|
|
}
|
|
|
|
export function permissionGuard(permission: PermissionCode) {
|
|
return async (request: FastifyRequest): Promise<void> => {
|
|
await authGuard(request);
|
|
|
|
const user = await authService.getCurrentUser(request.user);
|
|
|
|
if (!hasPermission(user.permissions, permission)) {
|
|
throw forbidden("当前账号没有权限执行该操作");
|
|
}
|
|
};
|
|
}
|