liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

195 lines
5.8 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 里生成) */
async setPassword(id, passwordHash) {
const user = await this.User.findByPk(id);
if (!user) return false;
await user.update({ passwordHash });
return true;
}
/**
* 按主键查询并带出密码哈希(仅改密码等鉴权场景内部使用,不要外传)
* @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;