Initial commit of the WeChat mini program, Express backend, and admin console. Co-authored-by: Cursor <cursoragent@cursor.com>
38 lines
1.2 KiB
JavaScript
38 lines
1.2 KiB
JavaScript
const db = require('./db')
|
|
const { fail } = require('./http')
|
|
|
|
function headerToken(req) {
|
|
return String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim()
|
|
}
|
|
|
|
function isAdmin(openid, data) {
|
|
return (data || db.read()).adminAllowlist.includes(openid)
|
|
}
|
|
|
|
function userAuth(req, res, next) {
|
|
const token = headerToken(req)
|
|
const user = token && db.read().users.find((item) => item.token === token)
|
|
if (!user) return fail(res, 401, '请先登录')
|
|
req.user = user
|
|
next()
|
|
}
|
|
|
|
function requireUserAdmin(req, res, next) {
|
|
if (!req.user || !isAdmin(req.user.openid)) return fail(res, 403, '仅管理员可操作')
|
|
next()
|
|
}
|
|
|
|
// Query tokens are only accepted where a plain link must work (CSV download).
|
|
function adminAuth(options) {
|
|
const allowQuery = !!(options && options.allowQueryToken)
|
|
return (req, res, next) => {
|
|
const token = headerToken(req) || (allowQuery ? String(req.query.token || '').trim() : '')
|
|
const admin = token && db.read().admins.find((item) => item.token === token)
|
|
if (!admin) return fail(res, 401, '请先登录管理后台')
|
|
req.admin = admin
|
|
next()
|
|
}
|
|
}
|
|
|
|
module.exports = { userAuth, requireUserAdmin, adminAuth, isAdmin }
|