feat(admin): auth 层加 role 字段 + requireAdmin 中间件(查库验角色)

This commit is contained in:
Sisyphus committed 2026-08-22 21:40:54 +08:00
1 parent 079fcd230b
commit 89466d08a8
3 files changed
+45 -1

No files matched your search

+41 -1
View File
@@ -11,6 +11,8 @@
import type { NextFunction, Request, RequestHandler, Response } from "express";
import { verifyToken } from "./jwt.js";
import { getDb } from "../db/index.js";
import { findUserById } from "./service.js";
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
@@ -46,4 +48,42 @@ export function requireAuth(req: Request, res: Response, next: NextFunction): vo
/** 短路用;路由测试可直接引用该中间件类型。 */
export type { RequestHandler };
export const requireAuthHandler: RequestHandler = requireAuth;
export const requireAuthHandler: RequestHandler = requireAuth;
export const AUTH_PERMISSION_DENIED_MESSAGE = "无权限访问";
/**
* 要求管理员的中间件。先走 requireAuth 同款鉴权,再从数据库查 role 校验(不信任 JWT 载荷)。
* 无 token / token 无效 → 401 "请先登录";非管理员 → 403 "无权限访问"。
*/
export async function requireAdmin(
req: Request,
res: Response,
next: NextFunction,
): Promise<void> {
// 鉴权逻辑与 requireAuth 一致(内联,避免重复调用 next())
const header = req.headers.authorization;
if (typeof header !== "string" || !header.startsWith("Bearer ")) {
res.status(401).json({ error: AUTH_REQUIRED_MESSAGE });
return;
}
const token = header.slice("Bearer ".length).trim();
const payload = verifyToken(token);
if (payload === undefined) {
res.status(401).json({ error: AUTH_REQUIRED_MESSAGE });
return;
}
req.userId = payload.sub;
req.userPhone = payload.phone;
// 查询数据库确认角色(不信任 JWT 载荷——角色变更需即时生效)
const row = await findUserById(getDb(), payload.sub);
if (row === undefined || row.role !== "admin") {
res.status(403).json({ error: AUTH_PERMISSION_DENIED_MESSAGE });
return;
}
next();
}
/** 短路用;路由测试可直接引用该中间件类型。 */
export const requireAdminHandler: RequestHandler = requireAdmin;
+1
View File
@@ -96,6 +96,7 @@ export function createAuthRouter(injectedDb?: Db): Router {
id: row.id,
phone: row.phone,
nickname: row.nickname,
role: row.role || "user",
createdAt: row.created_at,
},
});
+3
View File
@@ -28,6 +28,7 @@ export interface PublicUser {
id: string;
phone: string;
nickname: string | null;
role: string;
createdAt: string;
}
@@ -37,6 +38,7 @@ export interface UserRow {
phone: string;
password_hash: string;
nickname: string | null;
role: string;
created_at: string;
}
@@ -78,6 +80,7 @@ export function toPublicUser(row: UserRow): PublicUser {
id: row.id,
phone: row.phone,
nickname: row.nickname,
role: row.role || "user",
createdAt: row.created_at,
};
}