新增本地认证与管理接口服务

This commit is contained in:
cat-shark
2026-06-20 10:07:44 +08:00
parent a13b804c7a
commit cf82d606aa
10 changed files with 1057 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
const { verifyToken } = require("./security.cjs");
function publicUser(user) {
if (!user) return null;
const { password, current_token, ...safeUser } = user;
return safeUser;
}
function findUserByToken(db, token) {
const payload = verifyToken(token);
if (!payload?.userId) return null;
return db.users.find(user => Number(user.id) === Number(payload.userId)) || null;
}
function getBearerToken(req) {
const header = req.headers.authorization || "";
const match = String(header).match(/^Bearer\s+(.+)$/i);
return match ? match[1] : "";
}
function requireAdmin(db, req) {
const user = findUserByToken(db, getBearerToken(req));
if (!user || user.status !== "active") return null;
if (user.role !== "admin" && Number(user.is_super_admin || 0) !== 1) return null;
return user;
}
module.exports = {
publicUser,
findUserByToken,
getBearerToken,
requireAdmin,
};