'use strict'; /** * 登录态签发工具。 * 所有登录方式(账号密码、邮箱验证码、微信扫码)签发的 JWT 必须完全一致: * 载荷仅包含 user_id,有效期取 config.jwt.expiresIn。 */ /** * 将有效期配置转换为秒数(如 2h => 7200) * @param {String|Number} expiresIn 有效期,如 2h / 7200 * @return {Number} 有效秒数,无法解析时为 0 */ function parseExpiresIn(expiresIn) { if (typeof expiresIn === 'number') return expiresIn; const matched = /^(\d+)([smhd])$/.exec(String(expiresIn || '')); if (!matched) return 0; const units = { s: 1, m: 60, h: 3600, d: 86400 }; return Number(matched[1]) * units[matched[2]]; } /** * 签发登录态 * @param {Egg.Application} app egg application * @param {Number} userId 用户ID * @return {Object} { token, user_id, expires_in } */ function buildLoginData(app, userId) { const expiresIn = app.config.jwt.expiresIn || '2h'; const token = app.jwt.sign({ user_id: userId }, app.config.jwt.secret, { expiresIn }); return { token, user_id: userId, expires_in: parseExpiresIn(expiresIn) }; } module.exports = { parseExpiresIn, buildLoginData, };