账号密码登录、微信小程序登录共用同一套:客户端归一、协议校验(428)、 落库同意记录、签发令牌 + 主体列表。auth 控制器只保留参数校验与业务编排。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
204 lines
8.0 KiB
JavaScript
204 lines
8.0 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
|
||
/** 邮箱格式(与页面版保持一致,宽松校验) */
|
||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||
|
||
/**
|
||
* web 用户端:登录 / 注册 / 找回密码 / 重置密码(**JSON 接口**,给前端 SPA 调)
|
||
*
|
||
* 鉴权走 **header 令牌**(`Authorization: Bearer <user JWT>`),不依赖 cookie/session:
|
||
* 前端与后端不同源也没问题,也天然不受 CSRF 影响(`/api/*` 不过 CSRF)。
|
||
*
|
||
* 统一响应:成功 `{ ok:true, data }`;失败 `{ ok:false, status?, message }`。
|
||
*/
|
||
class WebAuthController extends Controller {
|
||
/** 签发令牌 + 返回脱敏用户(登录 / 注册成功后都走它) */
|
||
async issue(user) {
|
||
return this.ctx.service.login.issue(user);
|
||
}
|
||
|
||
/**
|
||
* POST /api/web/auth/login
|
||
* body: `{ account, password, client?, agreements? }`
|
||
* - account 支持 用户名 / 手机号 / 邮箱
|
||
* - client = 'mini_program' 时必须同意当前协议版本(见 config.agreement.enforce)
|
||
* - agreements = `[{ code, versionId }]`,登录成功后按用户 + 版本落库
|
||
* → `{ token, tokenType, expiresIn, user, subjects, agreements? }`
|
||
*/
|
||
async login() {
|
||
const { ctx } = this;
|
||
const body = ctx.request.body || {};
|
||
const { account, password } = body;
|
||
const client = ctx.service.login.normalizeClient(body.client);
|
||
if (!account || !password) {
|
||
ctx.status = 422;
|
||
ctx.body = { ok: false, message: '请填写账号和密码' };
|
||
return;
|
||
}
|
||
|
||
let accepted = null;
|
||
if (ctx.service.login.shouldEnforceAgreement(client)) {
|
||
accepted = await ctx.service.login.requireAgreements(body.agreements);
|
||
if (!accepted) return;
|
||
}
|
||
|
||
const user = await ctx.service.auth.login(String(account).trim(), password);
|
||
if (!user) {
|
||
ctx.status = 401;
|
||
ctx.body = { ok: false, status: 'unauthorized', message: '账号或密码错误' };
|
||
return;
|
||
}
|
||
|
||
ctx.logger.info('[web] %s 登录成功(API, client=%s)', user.username || account, client || 'unknown');
|
||
const data = await this.issue(user);
|
||
if (accepted) {
|
||
data.agreements = await ctx.service.login.recordAgreements(user, accepted, client);
|
||
ctx.logger.info('[web] 用户 %s 同意协议:%s', user.id, accepted.map(item => `${item.code}@${item.version}`).join(', '));
|
||
}
|
||
ctx.body = { ok: true, data };
|
||
}
|
||
|
||
/**
|
||
* POST /api/web/auth/register/code
|
||
* body: `{ email }` → 发 6 位邮箱验证码(开发模式直接返回 `code`)
|
||
*/
|
||
async sendRegisterCode() {
|
||
const { ctx } = this;
|
||
const email = String((ctx.request.body || {}).email || '').trim().toLowerCase();
|
||
|
||
if (!ctx.app.config.register.enable) {
|
||
ctx.throw(403, '注册已关闭,请联系管理员开通账号');
|
||
}
|
||
if (!EMAIL_RE.test(email)) {
|
||
ctx.throw(422, '请填写正确的邮箱');
|
||
}
|
||
|
||
const exists = await ctx.service.user.findOneBy({ email });
|
||
if (exists) ctx.throw(409, '该邮箱已被使用');
|
||
|
||
const result = await ctx.service.verifyCode.send('register', email);
|
||
if (!result.ok) ctx.throw(429, result.message);
|
||
|
||
ctx.logger.info('[web] 注册验证码已发送到 %s', email);
|
||
ctx.body = {
|
||
ok: true,
|
||
data: {
|
||
email,
|
||
// 开发模式(未配 SMTP)把验证码带回来,前端可直接提示;生产不返回
|
||
devMode: Boolean(result.devMode),
|
||
code: result.devMode ? result.code : undefined,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* POST /api/web/auth/register
|
||
* body: `{ username, email, code, password, nickname?, phone? }` → 建成即登录(返回令牌)
|
||
*/
|
||
async register() {
|
||
const { ctx } = this;
|
||
const body = ctx.request.body || {};
|
||
const username = String(body.username || '').trim();
|
||
const email = String(body.email || '').trim().toLowerCase();
|
||
const code = String(body.code || '').trim();
|
||
const password = String(body.password || '');
|
||
const nickname = String(body.nickname || '').trim();
|
||
const phone = String(body.phone || '').trim();
|
||
|
||
if (!ctx.app.config.register.enable) ctx.throw(403, '注册已关闭,请联系管理员开通账号');
|
||
if (!/^[A-Za-z0-9_]{3,32}$/.test(username)) ctx.throw(422, '用户名需 3-32 位字母、数字或下划线');
|
||
if (!EMAIL_RE.test(email)) ctx.throw(422, '邮箱格式不正确');
|
||
if (!/^\d{6}$/.test(code)) ctx.throw(422, '请填写 6 位邮箱验证码');
|
||
if (password.length < 6) ctx.throw(422, '密码至少 6 位');
|
||
if (phone && !/^[0-9+\-]{6,20}$/.test(phone)) ctx.throw(422, '手机号格式不正确');
|
||
|
||
const checked = await ctx.service.verifyCode.check('register', email, code);
|
||
if (!checked.ok) ctx.throw(422, checked.message);
|
||
|
||
try {
|
||
const user = await ctx.service.auth.register({ username, password, nickname, email, phone: phone || null });
|
||
// 注册成功才消费验证码(用户名/邮箱冲突时可改完重提,不用重新收码)
|
||
await ctx.service.verifyCode.consume('register', email);
|
||
ctx.logger.info('[web] %s 注册成功(API,id=%s)', username, user.id);
|
||
ctx.body = { ok: true, data: await this.issue(user) };
|
||
} catch (err) {
|
||
// 唯一键冲突(409):翻成页面能直接显示的文案
|
||
if (err.status === 409) {
|
||
const message = String(err.message || '');
|
||
ctx.status = 409;
|
||
ctx.body = {
|
||
ok: false,
|
||
message: message.startsWith('username') ? '该用户名已被使用'
|
||
: message.startsWith('email') ? '该邮箱已被使用'
|
||
: message.startsWith('phone') ? '该手机号已被注册'
|
||
: '注册失败,请稍后重试',
|
||
};
|
||
return;
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* POST /api/web/auth/forgot
|
||
* body: `{ email }` → 发重置链接(**防账号枚举**:邮箱没注册也返回成功)
|
||
*/
|
||
async forgot() {
|
||
const { ctx } = this;
|
||
const email = String((ctx.request.body || {}).email || '').trim().toLowerCase();
|
||
if (!EMAIL_RE.test(email)) ctx.throw(422, '请填写正确的邮箱');
|
||
|
||
const user = await ctx.service.user.findOneBy({ email });
|
||
if (user && Number(user.status) === 1) {
|
||
const origin = ctx.app.config.email.siteUrl || ctx.origin;
|
||
const result = await ctx.service.passwordReset.send(user, origin);
|
||
if (!result.ok) {
|
||
// 直接回状态码 + 原文(不走 ctx.throw:5xx 会被 error_handler 盖成「服务器内部错误」)
|
||
// 节流 → 429(前端把 message 展示给用户);Redis/发信异常 → 503
|
||
ctx.status = result.reason === 'throttled' ? 429 : 503;
|
||
ctx.body = { ok: false, status: result.reason || 'error', message: result.message };
|
||
return;
|
||
}
|
||
|
||
ctx.logger.info('[web] 已向 %s 发送重置密码链接', email);
|
||
ctx.body = {
|
||
ok: true,
|
||
data: {
|
||
sent: true,
|
||
// 开发模式(未配 SMTP)把链接返回,前端可直接点开
|
||
devMode: Boolean(result.devMode),
|
||
url: result.devMode ? result.url : undefined,
|
||
},
|
||
};
|
||
return;
|
||
}
|
||
|
||
if (user) ctx.logger.warn('[web] 账号已禁用,不发送重置链接: %s', email);
|
||
ctx.body = { ok: true, data: { sent: true } };
|
||
}
|
||
|
||
/**
|
||
* POST /api/web/auth/reset
|
||
* body: `{ token, password }` → 用邮件里的令牌设新密码(令牌一次性)
|
||
*/
|
||
async reset() {
|
||
const { ctx } = this;
|
||
const body = ctx.request.body || {};
|
||
const token = String(body.token || '');
|
||
const password = String(body.password || '');
|
||
|
||
const userId = await ctx.service.passwordReset.verify(token);
|
||
if (!userId) ctx.throw(410, '重置链接无效或已过期,请重新获取');
|
||
if (password.length < 6) ctx.throw(422, '密码至少 6 位');
|
||
|
||
await ctx.service.auth.setPassword(userId, password);
|
||
await ctx.service.passwordReset.consume(token, userId);
|
||
ctx.logger.info('[web] 用户 %s 通过邮件链接重置了密码(API)', userId);
|
||
ctx.body = { ok: true, data: { id: userId } };
|
||
}
|
||
}
|
||
|
||
module.exports = WebAuthController;
|