后端 - 新增 service/mail_quota.js:每个邮箱每天最多 config.email.dailyLimit(默认 10,EMAIL_DAILY_LIMIT)封, 注册验证码与找回密码**共用**额度;按北京时间切日,key TTL 到次日 0 点; 发信失败 / 被 60 秒节流拦下会还回额度;超限返回 429 daily_limit「… 请明天再试」 - service.user.findByEmail() / emailExists():LOWER(email) 查询(大小写不敏感)+ paranoid:false (软删除账号仍占用邮箱),单测环境无 sequelize 时退化为等值查询 - register/code:先判邮箱已占用 → 409 email_taken(含「忘记密码可找回」提示),一封邮件都不发; 发送失败/超限统一返回 429 + status(daily_limit / send_failed) - register:提交时再判一次邮箱占用(防发码后被抢注) - forgot:改用 findByEmail(大小写/软删除一致),日额度与注册共用,超限 429 - 单测:新增「邮箱已使用不发信」「每日 10 封上限(注册/找回)」4 个用例;fake-redis 补 decr 前端 - 登录页获取验证码:先做邮箱格式校验,并展示后端 409/429 的具体文案 - 忘记密码页:邮箱格式校验 + 小写归一,429 文案直接显示 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
244 lines
8.1 KiB
JavaScript
244 lines
8.1 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const { Op } = require('sequelize');
|
||
|
||
const MAX_PAGE_SIZE = 100;
|
||
/** 允许创建/更新的字段白名单 */
|
||
const WRITABLE_FIELDS = [ 'username', 'email', 'nickname', 'avatar', 'phone', 'gender', 'status', 'remark' ];
|
||
/** 需要校验唯一性的字段 */
|
||
const UNIQUE_FIELDS = [ 'username', 'phone', 'email' ];
|
||
/** 默认查询字段:排除密码哈希,避免接口/模板意外外泄 */
|
||
const SAFE_ATTRIBUTES = { exclude: [ 'passwordHash' ] };
|
||
|
||
/** 从查询结果里去掉密码哈希 */
|
||
function sanitize(row) {
|
||
if (!row) return row;
|
||
const { passwordHash, ...rest } = row;
|
||
return rest;
|
||
}
|
||
|
||
class UserService extends Service {
|
||
get User() {
|
||
return this.app.model.User;
|
||
}
|
||
|
||
/** 按主键查询,返回普通对象;不存在返回 null */
|
||
async findById(id) {
|
||
const user = await this.User.findByPk(id, { attributes: SAFE_ATTRIBUTES });
|
||
return user ? user.toJSON() : null;
|
||
}
|
||
|
||
/** 按用户名 / 手机号查询 */
|
||
async findOneBy(where) {
|
||
const user = await this.User.findOne({ where, attributes: SAFE_ATTRIBUTES });
|
||
return user ? user.toJSON() : null;
|
||
}
|
||
|
||
/**
|
||
* 按邮箱查用户(**大小写不敏感**,且包含已软删除的账号)
|
||
*
|
||
* 为什么要这样查:
|
||
* - 用户可能存成 `Foo@X.com`,注册时输入 `foo@x.com` → 直接等值比较会漏,
|
||
* 于是「邮箱已被使用」校验失效,验证码白发了(最终还会在插入时撞唯一键);
|
||
* - 软删除的账号仍占着唯一索引,注册也必须算「已被使用」。
|
||
*
|
||
* @param {string} email 邮箱
|
||
* @return {Promise<object|null>} 用户(普通对象,不含密码哈希;软删除的也能查到)
|
||
*/
|
||
async findByEmail(email) {
|
||
const normalized = String(email || '').trim().toLowerCase();
|
||
if (!normalized) return null;
|
||
|
||
// LOWER(email) = ? 保证大小写不敏感(不依赖列排序规则);
|
||
// 单测里 sequelize 插件是关掉的(app.Sequelize 不存在),这时退化成等值查询
|
||
const sequelize = this.User.sequelize || this.app.Sequelize;
|
||
const where = sequelize && typeof sequelize.where === 'function' && typeof sequelize.fn === 'function'
|
||
? sequelize.where(sequelize.fn('lower', sequelize.col('email')), normalized)
|
||
: { email: normalized };
|
||
|
||
const user = await this.User.findOne({
|
||
where,
|
||
attributes: SAFE_ATTRIBUTES,
|
||
paranoid: false, // 软删除的账号仍占用邮箱唯一键
|
||
});
|
||
return user ? user.toJSON() : null;
|
||
}
|
||
|
||
/** 邮箱是否已被使用(注册发验证码前先查它,避免白发一封邮件) */
|
||
async emailExists(email) {
|
||
return Boolean(await this.findByEmail(email));
|
||
}
|
||
|
||
/**
|
||
* 登录用:按用户名 / 手机号 / 邮箱查询,包含密码哈希(仅鉴权内部使用,不要外传)
|
||
* @return {Promise<object|null>} Sequelize 实例
|
||
*/
|
||
async findByAccount(account) {
|
||
return this.User.findOne({
|
||
where: { [Op.or]: [{ username: account }, { phone: account }, { email: account }] },
|
||
attributes: { include: [ 'passwordHash' ] },
|
||
});
|
||
}
|
||
|
||
/** 写入密码哈希(哈希在 auth service 里生成);顺手记下改密时间,让旧 JWT 立即失效 */
|
||
async setPassword(id, passwordHash) {
|
||
const user = await this.User.findByPk(id);
|
||
if (!user) return false;
|
||
|
||
await user.update({ passwordHash, passwordChangedAt: new Date() });
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 令牌是不是在「设置/重置密码」之前签发的(是 → 旧令牌,应当 401)
|
||
*
|
||
* JWT 的 `iat` 只有秒级精度,所以用严格小于比较:改密那一秒内新签发的令牌仍然有效。
|
||
* `passwordChangedAt` 为空(老数据)→ 不限制。
|
||
* @param {object} user 用户(需含 passwordChangedAt)
|
||
* @param {number} iatSec JWT payload 里的 iat(秒)
|
||
*/
|
||
isTokenStale(user, iatSec) {
|
||
if (!user || !user.passwordChangedAt) return false;
|
||
const changedSec = Math.floor(new Date(user.passwordChangedAt).getTime() / 1000);
|
||
return Number(iatSec || 0) < changedSec;
|
||
}
|
||
|
||
/**
|
||
* 按主键查询并带出密码哈希(仅改密码等鉴权场景内部使用,不要外传)
|
||
* @return {Promise<object|null>} Sequelize 实例
|
||
*/
|
||
async findByIdWithPassword(id) {
|
||
return this.User.findByPk(id, { attributes: { include: [ 'passwordHash' ] } });
|
||
}
|
||
|
||
/** 只保留登录态需要的字段(存 session / 回给页面) */
|
||
toSafeUser(user) {
|
||
return {
|
||
id: user.id,
|
||
username: user.username,
|
||
nickname: user.nickname,
|
||
avatar: user.avatar,
|
||
phone: user.phone,
|
||
status: Number(user.status),
|
||
};
|
||
}
|
||
|
||
/** 总数(首页统计用) */
|
||
async count(where = {}) {
|
||
return this.User.count({ where });
|
||
}
|
||
|
||
/** 通过微信授权反查用户(appid + openid) */
|
||
async findByOpenid(appid, openid) {
|
||
const oauth = await this.app.model.WechatOauth.findOne({
|
||
where: { appid, openid },
|
||
include: [{ model: this.User, as: 'user', required: true, attributes: SAFE_ATTRIBUTES }],
|
||
});
|
||
return oauth && oauth.user ? oauth.user.toJSON() : null;
|
||
}
|
||
|
||
/** 分页查询:keyword 模糊匹配昵称 / 登录名 / 手机号 / 邮箱 */
|
||
async list({ page = 1, pageSize = 20, keyword, status } = {}) {
|
||
const size = Math.min(Number(pageSize) || 20, MAX_PAGE_SIZE);
|
||
const current = Math.max(Number(page) || 1, 1);
|
||
|
||
const where = {};
|
||
if (status !== undefined && status !== '' && status !== null) {
|
||
where.status = Number(status);
|
||
}
|
||
if (keyword) {
|
||
where[Op.or] = [
|
||
{ nickname: { [Op.like]: `%${keyword}%` } },
|
||
{ username: { [Op.like]: `%${keyword}%` } },
|
||
{ phone: { [Op.like]: `%${keyword}%` } },
|
||
{ email: { [Op.like]: `%${keyword}%` } },
|
||
];
|
||
}
|
||
|
||
const { rows, count } = await this.User.findAndCountAll({
|
||
where,
|
||
attributes: SAFE_ATTRIBUTES,
|
||
limit: size,
|
||
offset: (current - 1) * size,
|
||
order: [[ 'id', 'DESC' ]],
|
||
});
|
||
|
||
return {
|
||
list: rows.map(row => row.toJSON()),
|
||
total: count,
|
||
page: current,
|
||
pageSize: size,
|
||
};
|
||
}
|
||
|
||
/** 新增,返回完整记录 */
|
||
async create(data) {
|
||
await this.assertUnique(data);
|
||
const user = await this.User.create(pick(data));
|
||
return sanitize(user.toJSON());
|
||
}
|
||
|
||
/** 更新,返回更新后的记录;记录不存在返回 null */
|
||
async update(id, data) {
|
||
const user = await this.User.findByPk(id);
|
||
if (!user) return null;
|
||
|
||
await this.assertUnique(data, id);
|
||
const fields = pick(data);
|
||
if (Object.keys(fields).length) {
|
||
await user.update(fields);
|
||
}
|
||
return sanitize(user.toJSON());
|
||
}
|
||
|
||
/** 软删除,返回是否删除成功 */
|
||
async remove(id) {
|
||
const affected = await this.User.destroy({ where: { id } });
|
||
return affected > 0;
|
||
}
|
||
|
||
/** 记录一次登录时间 */
|
||
async touchLogin(id) {
|
||
const user = await this.User.findByPk(id);
|
||
if (!user) return null;
|
||
|
||
await user.update({ lastLoginAt: new Date() });
|
||
return user.toJSON();
|
||
}
|
||
|
||
/** username / phone 唯一性校验,冲突抛 409 */
|
||
async assertUnique(data, excludeId) {
|
||
for (const field of UNIQUE_FIELDS) {
|
||
const value = data[field];
|
||
if (value === undefined || value === null || value === '') continue;
|
||
|
||
const where = { [field]: value };
|
||
if (excludeId) where.id = { [Op.ne]: excludeId };
|
||
|
||
const exists = await this.User.findOne({ where });
|
||
if (exists) this.ctx.throw(409, `${field} 已存在:${value}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 只取白名单字段,并做基础类型归一化 */
|
||
function pick(data = {}) {
|
||
const fields = {};
|
||
for (const key of WRITABLE_FIELDS) {
|
||
if (data[key] === undefined) continue;
|
||
if (key === 'gender' || key === 'status') {
|
||
fields[key] = Number(data[key]);
|
||
} else if (key === 'phone' || key === 'email') {
|
||
// 空串统一存 NULL(唯一索引允许多个 NULL);邮箱还做小写归一
|
||
const value = String(data[key] || '').trim();
|
||
fields[key] = value ? (key === 'email' ? value.toLowerCase() : value) : null;
|
||
} else {
|
||
fields[key] = data[key];
|
||
}
|
||
}
|
||
return fields;
|
||
}
|
||
|
||
module.exports = UserService;
|