express-template/middlewares/auth.js

34 lines
779 B
JavaScript

const AuthUtils = require('../utils/auth')
const { Account } = require('../entity/account')
const { getManager } = require('typeorm')
module.exports = async function (req,res,next) {
try{
const session = req.cookies.IM_SESS
if(!session) return res.error('未登录',401)
try{
var payload = AuthUtils.decode(session)
}catch(err) {
return res.error(err.message,401)
}
req.auth_session = payload
const manager = getManager()
const detail = await manager.findOne(Account,{ aid:payload.aid })
if(!detail.isActive) return res.error('账号不可用',403)
req.account_detail = detail
}catch(err) {
console.error('登录认证中间件报错:',err);
return res.error('登录凭证已过期',401)
}
next()
}