liufumingren 08d9ea103b chore(微信): 移除自建微信授权表 wechat_oauth / wechat_mp_accounts
微信侧接入已统一到登录网关,自建的两套都下线:

- 删除表:wechat_oauth(自建公众号网页授权 + 运维手工维护的绑定关系)、
  wechat_mp_accounts(小程序 code2Session 一键登录);迁移 20261029100000(up 删表、down 按原结构重建)
- 删除代码:service/{wechat,wechat_mp}.js、controller/web/wechat_mp.js、model/{wechat_oauth,wechat_mp_account}.js、
  service/user.js#findByOpenid、user 模型的 hasMany WechatOauth、公众号 OAuth 回调与 /api/web/auth/wechat/*
- 删除环境变量:WECHAT_APPID/SECRET/REDIRECT_URI/API_BASE、WX_MP_*(config.wechat 只剩设备扫码登录用到的串码/二维码参数)
- 小程序:去掉「微信一键登录」tab,只留账号密码登录(删 utils/wechat.ts 与 wechatLogin 调用)
- sql/schema.sql 同步去掉 wechat_oauth 建表

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-29 17:20:28 +08:00

237 lines
7.9 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;
}
/**
* 按邮箱查用户(**大小写不敏感**,且包含已软删除的账号)
*
* 为什么要这样查:
* - 用户可能存成 `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 });
}
/** 分页查询: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 };
// ⚠️ 必须带上软删的行:唯一索引不会因为 deleted_at 就放过旧行,
// 否则「查不到 → 直接 insert」会撞唯一键,抛出来只是一句 "Validation error"。
const exists = await this.User.findOne({ where, paranoid: false });
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;