'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} 用户(普通对象,不含密码哈希;软删除的也能查到) */ 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} 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} 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;