iboard/server/middleware.js
2026-08-03 18:05:50 +08:00

31 lines
955 B
JavaScript

import jwt from 'jsonwebtoken'
// 简易 JWT 鉴权: 解析 Authorization: Bearer xxx, 注入 req.user
// 失败时统一返回 401
export const JWT_SECRET = process.env.JWT_SECRET || 'iboard-dev-secret-change-me'
const TOKEN_TTL = '7d' // 7 天, 与"记住登录"语义一致
export function signToken(payload) {
return jwt.sign(payload, JWT_SECRET, { expiresIn: TOKEN_TTL })
}
export function authRequired(req, res, next) {
const h = req.headers.authorization || ''
const m = h.match(/^Bearer\s+(.+)$/)
if (!m) return res.status(401).json({ error: '未登录' })
try {
req.user = jwt.verify(m[1], JWT_SECRET)
next()
} catch (e) {
return res.status(401).json({ error: '登录已过期' })
}
}
export function authOptional(req, _res, next) {
const h = req.headers.authorization || ''
const m = h.match(/^Bearer\s+(.+)$/)
if (m) {
try { req.user = jwt.verify(m[1], JWT_SECRET) } catch { /* ignore */ }
}
next()
}