209 lines
6.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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;
}
/**
* 登录用:按用户名 / 手机号 / 邮箱查询,包含密码哈希(仅鉴权内部使用,不要外传)
* @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;