// 认证 const jwt = require('jsonwebtoken') const key = 'f7mqhTPJSyGBzYMU' /** * 同步创建签名 */ exports.Sign = data => jwt.sign(data, key, { expiresIn: '12h' }) /** * 异步检测jwt信息(中间件),同步验证并解码jwt信息(函数) */ exports.Verify = (ctx, next) => { const token = ctx.header['authorization'] if (token) { try { const decoded = jwt.verify(token, key) if (typeof next === 'undefined') { return decoded } } catch (err) { throw { code: -3, message: 'Invalid Token' } } // 这句不能移到try里面 if (typeof next === 'function') { return new Promise(resolve => resolve(next())) } } else { throw { code: -3, message: 'Authorization Not Found' } } } /** * 同步解码jwt信息,不验证 */ exports.Decode = ctx => { const token = ctx.header['authorization'] if (token) { return jwt.decode(token) } else { throw { code: -3, message: 'Authorization Not Found' } } }