31 lines
1.1 KiB
TypeScript
31 lines
1.1 KiB
TypeScript
import { TRPCError } from "@trpc/server";
|
|
import { t } from "../context.js";
|
|
import { authService } from "./auth.service.js";
|
|
|
|
/** 需要登录;解析出 userId 注入 ctx。 */
|
|
export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
|
|
if (!ctx.sessionToken) {
|
|
throw new TRPCError({ code: "UNAUTHORIZED", message: "请先登录" });
|
|
}
|
|
const user = await authService.getSessionUser(ctx.sessionToken);
|
|
if (!user) {
|
|
throw new TRPCError({ code: "UNAUTHORIZED", message: "请先登录" });
|
|
}
|
|
return next({
|
|
ctx: {
|
|
sessionToken: ctx.sessionToken,
|
|
setCookie: ctx.setCookie,
|
|
userId: user.id,
|
|
},
|
|
});
|
|
});
|
|
|
|
/** 需要管理员角色;在 protectedProcedure 基础上校验 role。 */
|
|
export const adminProcedure = protectedProcedure.use(async ({ ctx, next }) => {
|
|
const user = await authService.getSessionUser(ctx.sessionToken);
|
|
if (!user || user.role !== "admin") {
|
|
throw new TRPCError({ code: "FORBIDDEN", message: "需要管理员权限" });
|
|
}
|
|
return next({ ctx: { ...ctx, role: user.role as "admin" } });
|
|
});
|