feat: 增加登录鉴权和固定角色权限
This commit is contained in:
+24
-4
@@ -1,6 +1,10 @@
|
||||
import Fastify from "fastify";
|
||||
import fastifyJwt from "@fastify/jwt";
|
||||
import { ZodError } from "zod";
|
||||
import { env } from "./config/env";
|
||||
import { pingDatabase } from "./db/pool";
|
||||
import { authRoutes } from "./modules/auth/auth.controller";
|
||||
import { managementGuard } from "./modules/auth/auth.guard";
|
||||
import { catalogRoutes } from "./modules/catalog/catalog.controller";
|
||||
import { employeeRoutes } from "./modules/employees/employee.controller";
|
||||
import { HttpError } from "./shared/http-error";
|
||||
@@ -31,6 +35,14 @@ export function createApp() {
|
||||
},
|
||||
);
|
||||
|
||||
// 注册 JWT 能力。登录接口负责签发 token,受保护接口通过 authGuard 校验 token。
|
||||
app.register(fastifyJwt, {
|
||||
secret: env.JWT_SECRET,
|
||||
sign: {
|
||||
expiresIn: env.JWT_EXPIRES_IN,
|
||||
},
|
||||
});
|
||||
|
||||
// 健康检查接口,供负载均衡器和监控系统使用。
|
||||
app.get("/health", async () => {
|
||||
await pingDatabase();
|
||||
@@ -42,10 +54,18 @@ export function createApp() {
|
||||
});
|
||||
});
|
||||
|
||||
// 注册业务路由,所有接口都以 /api 开头,便于区分静态资源和 API 请求。
|
||||
app.register(catalogRoutes, { prefix: "/api" });
|
||||
// 员工管理相关接口,包含员工的增删改查和状态更新等功能。
|
||||
app.register(employeeRoutes, { prefix: "/api" });
|
||||
// 登录接口不需要 token;/auth/me 在 authRoutes 内部单独加了 authGuard。
|
||||
app.register(authRoutes, { prefix: "/api" });
|
||||
|
||||
// 业务管理接口统一要求后台权限:超级管理员或拥有 admin 角色的员工。
|
||||
app.register(
|
||||
async (protectedApp) => {
|
||||
protectedApp.addHook("preHandler", managementGuard);
|
||||
protectedApp.register(catalogRoutes);
|
||||
protectedApp.register(employeeRoutes);
|
||||
},
|
||||
{ prefix: "/api" },
|
||||
);
|
||||
|
||||
// 全局错误处理器,捕获所有未处理的异常,并根据错误类型返回合适的 HTTP 状态码和错误信息。
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
|
||||
Reference in New Issue
Block a user