docs: README + optimize auth getSecret, features id fix, token error msg

This commit is contained in:
2026-07-14 03:19:36 +08:00
parent 4913984391
commit f277711082
3 changed files with 104 additions and 11 deletions

View File

@@ -1,16 +1,15 @@
const jwt = require('jsonwebtoken');
const { getConfig } = require('../db');
let cachedSecret = null;
function getSecret() {
if (cachedSecret) return cachedSecret;
try {
const cfg = getConfig();
const secret = cfg?.jwt_secret || process.env.JWT_SECRET;
if (secret) return secret;
throw new Error('JWT_SECRET not configured');
} catch (e) {
if (e.message === 'JWT_SECRET not configured') throw e;
return process.env.JWT_SECRET || (() => { throw new Error('JWT_SECRET not configured'); })();
}
cachedSecret = getConfig()?.jwt_secret || process.env.JWT_SECRET;
} catch {}
if (!cachedSecret) throw new Error('JWT_SECRET not configured');
return cachedSecret;
}
function generateToken(user) {
@@ -22,7 +21,8 @@ function verifyToken(token) { return jwt.verify(token, getSecret()); }
function authenticate(req, res, next) {
const h = req.headers.authorization;
if (!h || !h.startsWith('Bearer ')) return res.status(401).json({ error: '请先登录' });
try { req.user = verifyToken(h.split(' ')[1]); next(); } catch { return res.status(401).json({ error: '登录已过期' }); }
try { req.user = verifyToken(h.split(' ')[1]); next(); }
catch (e) { return res.status(401).json({ error: e.name === 'TokenExpiredError' ? '登录已过期,请重新登录' : '无效的认证信息' }); }
}
function requireRole(...roles) {