'use strict'; const { Controller } = require('egg'); const { generateSalt, hashPassword } = require('../lib/password'); const { CODE_TTL, sendCode, verifyCode } = require('../lib/emailCode'); const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; /** * @controller AuthController 登录鉴权 */ class AuthController extends Controller { /** * @summary 发送邮箱验证码 * @description 注册前置步骤:校验邮箱格式与唯一性后,发送 6 位验证码(10 分钟内有效); * 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429 * @router post /api/auth/email-code * @request body sendEmailCodeRequest *body * @response 200 baseResponse success */ async sendEmailCode() { const { ctx, app } = this; const { email } = ctx.request.body; if (!email || !EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; } const exist = await ctx.model.User.findOne({ where: { email } }); if (exist) { ctx.status = 400; ctx.body = { code: 400, message: '邮箱已被注册' }; return; } const result = await sendCode(app, email, { ip: ctx.ip, scene: 'register' }); if (!result.ok) { ctx.status = 429; ctx.body = { code: 429, message: result.message }; return; } ctx.body = { code: 0, message: 'success', data: { email, expires_in: CODE_TTL }, }; } /** * @summary 账号密码登录(支持用户名或邮箱) * @description 校验登录账号或邮箱(account 字段)与加盐密码,成功后签发 JWT;token 载荷仅包含 user_id,不含敏感信息 * @router post /api/auth/login * @request body loginRequest *body * @response 200 loginResponse success */ async login() { const { ctx, app } = this; const { account, password } = ctx.request.body; if (!account || !password) { ctx.status = 400; ctx.body = { code: 400, message: 'account 与 password 为必填项' }; return; } const user = await ctx.model.User.findOne({ where: { [app.Sequelize.Op.or]: [{ username: account }, { email: account }], }, }); if (!user) { ctx.status = 401; ctx.body = { code: 401, message: '账号或密码错误' }; return; } if (Number(user.status) !== 1) { ctx.status = 403; ctx.body = { code: 403, message: '账号已禁用' }; return; } if (hashPassword(password, user.salt) !== user.password) { ctx.status = 401; ctx.body = { code: 401, message: '账号或密码错误' }; return; } const expiresIn = app.config.jwt.expiresIn || '2h'; const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn }); await user.update({ last_login_at: new Date() }); // 登录时间变更,失效用户缓存,下次请求重新加载 await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, message: 'success', data: { token, user_id: user.id, expires_in: this.parseExpiresIn(expiresIn), }, }; } /** * @summary 用户注册 * @description 公开接口,无需登录;需先调用发送邮箱验证码接口完成邮箱认证,邮箱全局唯一; * 密码加盐存储,注册成功后直接返回 token * @router post /api/auth/register * @request body registerRequest *body * @response 200 loginResponse success */ async register() { const { ctx, app } = this; const { username, password, email, code, nickname, phone } = ctx.request.body; if (!username || !password || !email || !code) { ctx.status = 400; ctx.body = { code: 400, message: 'username、password、email、code 为必填项' }; return; } if (String(password).length < 6) { ctx.status = 400; ctx.body = { code: 400, message: '密码长度不能少于 6 位' }; return; } if (!EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; } const usernameExist = await ctx.model.User.findOne({ where: { username } }); if (usernameExist) { ctx.status = 400; ctx.body = { code: 400, message: '账号已存在' }; return; } const emailExist = await ctx.model.User.findOne({ where: { email } }); if (emailExist) { ctx.status = 400; ctx.body = { code: 400, message: '邮箱已被注册' }; return; } // 邮箱认证:校验验证码,通过后该验证码立即失效 const verified = await verifyCode(app, email, code); if (!verified) { ctx.status = 400; ctx.body = { code: 400, message: '邮箱验证码错误或已过期' }; return; } const salt = generateSalt(); const user = await ctx.model.User.create({ username, nickname: nickname || username, email, phone, salt, password: hashPassword(password, salt), status: 1, }); const expiresIn = app.config.jwt.expiresIn || '2h'; const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn }); ctx.body = { code: 0, message: 'success', data: { token, user_id: user.id, expires_in: this.parseExpiresIn(expiresIn), }, }; } /** * @summary 当前登录用户信息 * @description 需要登录:请求头 Authorization: Bearer * @router get /api/auth/profile * @apikey * @response 200 baseResponse success */ async profile() { const { ctx } = this; // JWT 中间件已从缓存加载用户,这里不再查库 const user = ctx.user || await ctx.service.cache.getUser(ctx.userId); if (!user) { ctx.status = 404; ctx.body = { code: 404, message: '用户不存在' }; return; } // 返回用户所属主体列表,供前端判断是否已创建主体(多租户隔离);走缓存的可选主体列表 const options = await ctx.service.cache.getUserPrincipalOptions(ctx.userId); const principals = options.map(item => ({ id: item.id, name: item.name })); ctx.body = { code: 0, message: 'success', data: { ...user, principals } }; } /** * @summary 发送邮箱登录验证码 * @description 公开接口,无需登录:邮箱必须已注册,发送 6 位数字验证码(10 分钟有效); * 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429 * @router post /api/auth/email-login/code * @request body sendLoginCodeRequest *body * @response 200 baseResponse success */ async sendLoginCode() { const { ctx, app } = this; const { email } = ctx.request.body; if (!email || !EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; } const user = await ctx.model.User.findOne({ where: { email } }); if (!user) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' }; return; } const result = await sendCode(app, email, { userId: user.id, ip: ctx.ip, scene: 'login', length: 6, subject: 'OMS 邮箱登录验证码', }); if (!result.ok) { ctx.status = 429; ctx.body = { code: 429, message: result.message }; return; } ctx.body = { code: 0, message: 'success', data: { email, expires_in: CODE_TTL }, }; } /** * @summary 邮箱验证码登录 * @description 公开接口,无需登录:校验 6 位验证码(通过后立即失效), * 校验通过后直接签发 JWT;账号被禁用时返回 403 * @router post /api/auth/email-login * @request body emailLoginRequest *body * @response 200 loginResponse success */ async loginByEmailCode() { const { ctx, app } = this; const { email, code } = ctx.request.body; if (!email || !EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; } if (!code) { ctx.status = 400; ctx.body = { code: 400, message: 'email 与 code 为必填项' }; return; } const user = await ctx.model.User.findOne({ where: { email } }); if (!user) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' }; return; } if (Number(user.status) !== 1) { ctx.status = 403; ctx.body = { code: 403, message: '账号已禁用' }; return; } const verified = await verifyCode(app, email, code, 'login'); if (!verified) { ctx.status = 400; ctx.body = { code: 400, message: '验证码错误或已过期' }; return; } const expiresIn = app.config.jwt.expiresIn || '2h'; const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn }); await user.update({ last_login_at: new Date() }); ctx.body = { code: 0, message: 'success', data: { token, user_id: user.id, expires_in: this.parseExpiresIn(expiresIn), }, }; } /** * @summary 发送密码重置验证码 * @description 公开接口,无需登录:邮箱必须已注册,发送 4 位数字验证码(10 分钟有效); * 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429 * @router post /api/auth/reset-password/code * @request body sendResetCodeRequest *body * @response 200 baseResponse success */ async sendResetCode() { const { ctx, app } = this; const { email } = ctx.request.body; if (!email || !EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; } // 找回密码:邮箱必须已注册 const user = await ctx.model.User.findOne({ where: { email } }); if (!user) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱未注册' }; return; } const result = await sendCode(app, email, { userId: user.id, ip: ctx.ip, scene: 'reset-password', length: 4, subject: 'OMS 密码重置验证码', }); if (!result.ok) { ctx.status = 429; ctx.body = { code: 429, message: result.message }; return; } ctx.body = { code: 0, message: 'success', data: { email, expires_in: CODE_TTL }, }; } /** * @summary 通过邮箱验证码重置密码 * @description 公开接口,无需登录:校验 4 位验证码(通过后立即失效), * 然后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位 * @router post /api/auth/reset-password * @request body resetPasswordByCodeRequest *body * @response 200 baseResponse success */ async resetPasswordByCode() { const { ctx, app } = this; const { email, code, password } = ctx.request.body; if (!email || !EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; return; } if (!code || !password) { ctx.status = 400; ctx.body = { code: 400, message: '验证码与新密码均为必填项' }; return; } if (String(password).length < 6) { ctx.status = 400; ctx.body = { code: 400, message: '新密码长度不能少于 6 位' }; return; } const user = await ctx.model.User.findOne({ where: { email } }); if (!user) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱未注册' }; return; } const verified = await verifyCode(app, email, code, 'reset-password'); if (!verified) { ctx.status = 400; ctx.body = { code: 400, message: '验证码错误或已过期' }; return; } const salt = generateSalt(); await user.update({ salt, password: hashPassword(password, salt) }); await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, message: 'success', data: { id: user.id } }; } /** * @summary 修改当前登录用户资料 * @description 自助服务:仅可修改昵称、邮箱、手机号与头像,不涉及密码、账号与状态; * 邮箱需校验格式与全局唯一性(排除自身) * @router put /api/auth/profile * @apikey * @request body updateProfileRequest *body * @response 200 baseResponse success */ async updateProfile() { const { ctx } = this; const user = await ctx.model.User.findByPk(ctx.userId); if (!user) { ctx.status = 404; ctx.body = { code: 404, message: '用户不存在' }; return; } const { nickname, email, phone, avatar } = ctx.request.body; if (email && !EMAIL_REGEX.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '邮箱格式不正确' }; return; } if (email) { const exist = await ctx.model.User.findOne({ where: { email } }); if (exist && Number(exist.id) !== Number(user.id)) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱已被使用' }; return; } } const patch = {}; if (nickname !== undefined) patch.nickname = nickname; if (email !== undefined) patch.email = email; if (phone !== undefined) patch.phone = phone; if (avatar !== undefined) patch.avatar = avatar; await user.update(patch); await ctx.service.cache.invalidateUser(user.id); const updated = await ctx.model.User.findByPk(user.id, { attributes: { exclude: [ 'password', 'salt' ] }, }); ctx.body = { code: 0, message: 'success', data: updated }; } /** * @summary 修改当前登录用户密码 * @description 自助服务:需校验原密码,通过后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位且不能与原密码相同 * @router put /api/auth/password * @apikey * @request body changePasswordRequest *body * @response 200 baseResponse success */ async changePassword() { const { ctx } = this; const { old_password: oldPassword, password } = ctx.request.body; if (!oldPassword || !password) { ctx.status = 400; ctx.body = { code: 400, message: '原密码与新密码均为必填项' }; return; } if (String(password).length < 6) { ctx.status = 400; ctx.body = { code: 400, message: '新密码长度不少于 6 位' }; return; } const user = await ctx.model.User.findByPk(ctx.userId); if (!user) { ctx.status = 404; ctx.body = { code: 404, message: '用户不存在' }; return; } if (hashPassword(oldPassword, user.salt) !== user.password) { ctx.status = 400; ctx.body = { code: 400, message: '原密码不正确' }; return; } if (oldPassword === password) { ctx.status = 400; ctx.body = { code: 400, message: '新密码不能与原密码相同' }; return; } const salt = generateSalt(); await user.update({ salt, password: hashPassword(password, salt) }); await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, message: 'success', data: { id: user.id } }; } /** * 将有效期配置转换为秒数(如 2h => 7200) * @param {String|Number} expiresIn 有效期,如 2h / 7200 * @return {Number} 有效秒数 */ parseExpiresIn(expiresIn) { if (typeof expiresIn === 'number') return expiresIn; const matched = /^(\d+)([smhd])$/.exec(expiresIn); if (!matched) return 0; const units = { s: 1, m: 60, h: 3600, d: 86400 }; return Number(matched[1]) * units[matched[2]]; } } module.exports = AuthController;