UNPKG

hwj-common-lib

Version:

微信小程序云开发通用模块库,支持灵活的环境配置

45 lines (39 loc) 924 B
const jwt = require('jsonwebtoken') const { TOKEN_SECRET, TOKEN_EXPIRES_IN } = require('./env') const { TokenError } = require('./error') // 生成 token function generateToken(payload) { return jwt.sign(payload, TOKEN_SECRET, { expiresIn: TOKEN_EXPIRES_IN }) } // 验证 token function verifyToken(token) { try { return jwt.verify(token, TOKEN_SECRET) } catch (error) { throw new TokenError('无效的token') } } // 身份验证中间件 async function auth(event) { const { token } = event if (!token) { throw new TokenError('缺少token') } try { const decoded = verifyToken(token) return { success: true, data: { userId: decoded.userId, openId: decoded.openId } } } catch (error) { throw new TokenError('token验证失败') } } module.exports = { generateToken, verifyToken, auth }