docs: README + optimize auth getSecret, features id fix, token error msg
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user