diff --git a/backend/app/controller/web/wechat_mp.js b/backend/app/controller/web/wechat_mp.js deleted file mode 100644 index 10f6a9e..0000000 --- a/backend/app/controller/web/wechat_mp.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const { Controller } = require('egg'); - -/** 路径参数转正整数,非法返回 null */ -function toId(value) { - const id = Number(value); - return Number.isInteger(id) && id > 0 ? id : null; -} - -/** - * web 用户端:微信小程序登录 / 绑定 - * - * - `POST /api/web/auth/wechat/login`(公开):`uni.login()` 的 code 换 openid, - * 未绑定就自动建账号;小程序客户端同样要先同意协议(与账号密码登录一致) - * - `POST /api/web/auth/wechat/bind`(需令牌):把微信绑到当前账号 - * - `GET /api/web/auth/wechat/bindings`(需令牌):当前账号的微信绑定 - * - `DELETE /api/web/auth/wechat/bindings/:id`(需令牌):解绑 - */ -class WebWechatMpController extends Controller { - /** - * POST /api/web/auth/wechat/login - * body: `{ code, userInfo?: { nickname, avatar }, client?, agreements? }` - * → `{ token, tokenType, expiresIn, user, subjects, firstTime, wechat, agreements? }` - */ - async login() { - const { ctx } = this; - const body = ctx.request.body || {}; - const client = ctx.service.login.normalizeClient(body.client) || 'mini_program'; - - let accepted = null; - if (ctx.service.login.shouldEnforceAgreement(client)) { - accepted = await ctx.service.login.requireAgreements(body.agreements); - if (!accepted) return; - } - - const result = await ctx.service.wechatMp.login({ - code: body.code, - userInfo: body.userInfo, - }); - - const data = await ctx.service.login.issue(result.user); - data.firstTime = result.firstTime; - data.wechat = result.binding; - if (accepted) { - data.agreements = await ctx.service.login.recordAgreements(result.user, accepted, client); - } - ctx.body = { ok: true, data }; - } - - /** - * POST /api/web/auth/wechat/bind - * body: `{ code, userInfo? }` → 绑定详情 - */ - async bind() { - const { ctx } = this; - const body = ctx.request.body || {}; - const data = await ctx.service.wechatMp.bind(ctx.state.user.id, { - code: body.code, - userInfo: body.userInfo, - }); - ctx.body = { ok: true, data }; - } - - /** GET /api/web/auth/wechat/bindings —— 当前账号的微信绑定 */ - async bindings() { - const { ctx } = this; - const list = await ctx.service.wechatMp.listByUser(ctx.state.user.id); - ctx.body = { ok: true, data: { list } }; - } - - /** DELETE /api/web/auth/wechat/bindings/:id —— 解绑 */ - async unbind() { - const { ctx } = this; - const id = toId(ctx.params.id); - if (!id) ctx.throw(400, 'id 必须是正整数'); - - const data = await ctx.service.wechatMp.unbind(ctx.state.user.id, id); - ctx.body = { ok: true, data }; - } -} - -module.exports = WebWechatMpController; diff --git a/backend/app/model/user.js b/backend/app/model/user.js index a49de75..a00ebcc 100644 --- a/backend/app/model/user.js +++ b/backend/app/model/user.js @@ -32,7 +32,6 @@ module.exports = (app) => { }); User.associate = function() { - app.model.User.hasMany(app.model.WechatOauth, { foreignKey: 'user_id', as: 'wechats' }); app.model.User.hasMany(app.model.Scanner, { foreignKey: 'user_id', as: 'scanners' }); }; diff --git a/backend/app/model/wechat_mp_account.js b/backend/app/model/wechat_mp_account.js deleted file mode 100644 index ae05909..0000000 --- a/backend/app/model/wechat_mp_account.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -/** - * 微信小程序授权账号(wechat_mp_accounts) - * - * 一行 = 某个小程序 appid 下的一个 openid,以及它绑定的平台账号(`user_id`)。 - * 解绑后 `user_id` 置空,记录保留(重新绑定 / 审计用)。 - */ -module.exports = (app) => { - const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; - - const WechatMpAccount = app.model.define('wechat_mp_account', { - id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, - userId: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定的平台账号 users.id(解绑后为空)' }, - appid: { type: STRING(64), allowNull: false, comment: '小程序 appid' }, - openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' }, - unionid: { type: STRING(64), allowNull: true, comment: '开放平台 unionid' }, - nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '微信昵称(有授权时)' }, - avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '微信头像(有授权时)' }, - sessionKey: { type: STRING(128), allowNull: true, comment: 'jscode2session 返回的 session_key' }, - lastLoginAt: { type: DATE, allowNull: true, comment: '最近一次微信登录时间' }, - loginCount: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '微信登录次数' }, - status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0停用' }, - }, { - tableName: 'wechat_mp_accounts', - paranoid: true, - comment: '微信小程序授权账号表', - }); - - WechatMpAccount.associate = function() { - app.model.WechatMpAccount.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' }); - }; - - return WechatMpAccount; -}; diff --git a/backend/app/model/wechat_oauth.js b/backend/app/model/wechat_oauth.js deleted file mode 100644 index 87e3efc..0000000 --- a/backend/app/model/wechat_oauth.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -/** - * 微信授权表模型(wechat_oauth) - * - * 一条记录 = 某个用户在某个 appid 下的一次微信授权, - * 因此一个用户可绑定多个微信(公众号 / 小程序 / 开放平台)。 - * 关联:WechatOauth.belongsTo(User, { as: 'user' }), - * 可通过 { include: [{ model: app.model.User, as: 'user' }] } 取出对应用户。 - */ -module.exports = (app) => { - const { BIGINT, STRING, DATE } = app.Sequelize; - - const WechatOauth = app.model.define('wechatOauth', { - id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, - // 下划线映射由 config.sequelize.define.underscored 统一处理(userId -> user_id) - userId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '关联 users.id' }, - appid: { type: STRING(64), allowNull: false, comment: '微信 appid' }, - openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' }, - unionid: { type: STRING(64), comment: '开放平台 unionid' }, - nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '授权时微信昵称' }, - avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '授权时微信头像' }, - sessionKey: { type: STRING(128), comment: '小程序 session_key' }, - accessToken: { type: STRING(512), comment: '网页授权 access_token' }, - refreshToken: { type: STRING(512), comment: '刷新令牌' }, - scope: { type: STRING(64), comment: '授权 scope' }, - tokenExpiresAt: { type: DATE, comment: 'access_token 过期时间' }, - lastAuthAt: { type: DATE, comment: '最近授权时间' }, - }, { - tableName: 'wechat_oauth', - paranoid: true, - comment: '微信授权表', - }); - - WechatOauth.associate = function() { - app.model.WechatOauth.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' }); - }; - - return WechatOauth; -}; diff --git a/backend/app/service/user.js b/backend/app/service/user.js index 51cb522..689db37 100644 --- a/backend/app/service/user.js +++ b/backend/app/service/user.js @@ -129,15 +129,6 @@ class UserService extends Service { 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); @@ -216,7 +207,9 @@ class UserService extends Service { const where = { [field]: value }; if (excludeId) where.id = { [Op.ne]: excludeId }; - const exists = await this.User.findOne({ where }); + // ⚠️ 必须带上软删的行:唯一索引不会因为 deleted_at 就放过旧行, + // 否则「查不到 → 直接 insert」会撞唯一键,抛出来只是一句 "Validation error"。 + const exists = await this.User.findOne({ where, paranoid: false }); if (exists) this.ctx.throw(409, `${field} 已存在:${value}`); } } diff --git a/backend/app/service/wechat.js b/backend/app/service/wechat.js deleted file mode 100644 index fdf4b49..0000000 --- a/backend/app/service/wechat.js +++ /dev/null @@ -1,97 +0,0 @@ -'use strict'; - -const { Service } = require('egg'); - -/** 拼装写库的授权信息(只写入明确传入的字段,避免把旧值覆盖成空) */ -function buildPayload(data) { - const payload = {}; - if (data.unionid !== undefined) payload.unionid = data.unionid || null; - if (data.nickname !== undefined) payload.nickname = data.nickname || ''; - if (data.avatar !== undefined) payload.avatar = data.avatar || ''; - if (data.sessionKey !== undefined) payload.sessionKey = data.sessionKey || null; - if (data.accessToken !== undefined) payload.accessToken = data.accessToken || null; - if (data.refreshToken !== undefined) payload.refreshToken = data.refreshToken || null; - if (data.scope !== undefined) payload.scope = data.scope || null; - if (data.expiresIn !== undefined && data.expiresIn !== null) { - payload.tokenExpiresAt = new Date(Date.now() + Number(data.expiresIn) * 1000); - } else if (data.tokenExpiresAt !== undefined) { - payload.tokenExpiresAt = data.tokenExpiresAt; - } - payload.lastAuthAt = new Date(); - return payload; -} - -class WechatService extends Service { - get WechatOauth() { - return this.app.model.WechatOauth; - } - - /** - * 绑定微信授权:同一 appid + openid 已存在则更新,否则新建 - * @param {object} data userId / appid / openid 必填 - */ - async bind(data) { - const { userId, appid, openid } = data; - const existing = await this.WechatOauth.findOne({ where: { appid, openid } }); - const payload = buildPayload(data); - - if (existing) { - // 换绑:允许把已存在的授权记录改到另一个用户 - if (userId && Number(existing.userId) !== Number(userId)) { - payload.userId = userId; - } - await existing.update(payload); - return existing.toJSON(); - } - - const created = await this.WechatOauth.create(Object.assign({ userId, appid, openid }, payload)); - return created.toJSON(); - } - - /** 按 appid + openid 查询授权记录,并带出关联用户 */ - async findByOpenid(appid, openid) { - const oauth = await this.WechatOauth.findOne({ - where: { appid, openid }, - include: [{ model: this.app.model.User, as: 'user', required: false }], - }); - if (!oauth) return null; - - const result = oauth.toJSON(); - if (result.user) { - // 不把用户敏感字段透出去 - delete result.user.deleted_at; - } - return result; - } - - /** 查询某个用户的全部微信授权 */ - async listByUser(userId) { - const rows = await this.WechatOauth.findAll({ - where: { userId }, - order: [[ 'id', 'DESC' ]], - }); - return rows.map(row => row.toJSON()); - } - - /** 更新小程序 session_key / 令牌 */ - async updateTokens(id, data) { - const oauth = await this.WechatOauth.findByPk(id); - if (!oauth) return null; - - await oauth.update(buildPayload(data)); - return oauth.toJSON(); - } - - /** 解绑(软删除) */ - async unbind(id) { - const affected = await this.WechatOauth.destroy({ where: { id } }); - return affected > 0; - } - - /** 总数(首页统计用) */ - async count(where = {}) { - return this.WechatOauth.count({ where }); - } -} - -module.exports = WechatService; diff --git a/backend/app/service/wechat_mp.js b/backend/app/service/wechat_mp.js deleted file mode 100644 index 00aa1bd..0000000 --- a/backend/app/service/wechat_mp.js +++ /dev/null @@ -1,272 +0,0 @@ -'use strict'; - -const { Service } = require('egg'); -const crypto = require('crypto'); -const { Op } = require('sequelize'); - -/** 小程序登录的 mock 前缀:`mock:` 直接指定 openid,方便本地联调固定账号 */ -const MOCK_PREFIX = 'mock:'; - -/** - * 微信小程序登录 / 绑定 - * - * 链路:`uni.login()` 拿 code → `jscode2session` 换 openid → - * 按 (appid, openid) 找 `wechat_mp_accounts`: - * - 已绑定平台账号 → 签发该账号的 user JWT(`firstTime: false`); - * - 未绑定 → 自动建平台账号(`wx_`,随机密码)并绑定(`firstTime: true`)。 - * - * 未配置 `WX_MP_APPID / WX_MP_SECRET` 时(本地 / 单测),走 mock: - * 传 `mock:` 固定账号,或任意 code 按 sha1 推导 openid。生产必须显式 `WX_MP_MOCK=true` 才允许 mock。 - */ -class WechatMpService extends Service { - get cfg() { - return this.app.config.wechat.mp || {}; - } - - get Account() { - return this.app.model.WechatMpAccount; - } - - /** 配置齐全(有 appid + secret)才算真机模式 */ - get enabled() { - return Boolean(this.cfg.appid && this.cfg.secret); - } - - /** mock 是否可用 */ - get mockEnabled() { - if (this.cfg.mock) return true; - return !this.enabled && this.app.config.env !== 'prod'; - } - - get appid() { - return this.cfg.appid || 'mock-appid'; - } - - get apiBase() { - return this.cfg.apiBase || 'https://api.weixin.qq.com'; - } - - /** - * code → openid - * @param {string} code `uni.login()` 返回的 code(本地可用 `mock:`) - */ - async code2Session(code) { - const jsCode = String(code || '').trim(); - if (!jsCode) this.ctx.throw(422, '缺少微信登录 code'); - - if (jsCode.startsWith(MOCK_PREFIX)) { - if (!this.mockEnabled) this.ctx.throw(400, 'mock 微信登录未开启'); - const openid = this.normalizeOpenid(jsCode.slice(MOCK_PREFIX.length)); - return { openid, unionid: null, sessionKey: null, devMode: true }; - } - - if (!this.enabled) { - if (!this.mockEnabled) { - this.ctx.throw(503, '微信小程序登录未配置(WX_MP_APPID / WX_MP_SECRET)'); - } - const digest = crypto.createHash('sha1').update(jsCode).digest('hex').slice(0, 24); - this.ctx.logger.warn('[wechat-mp] 未配置 appid/secret,使用 mock openid=%s', digest); - return { openid: `mock_${digest}`, unionid: null, sessionKey: null, devMode: true }; - } - - const res = await this.ctx.curl(`${this.apiBase}/sns/jscode2session`, { - data: { - appid: this.cfg.appid, - secret: this.cfg.secret, - js_code: jsCode, - grant_type: 'authorization_code', - }, - dataType: 'json', - timeout: 8000, - }); - const data = res.data || {}; - if (data.errcode) { - this.ctx.logger.warn('[wechat-mp] jscode2session 失败: %s %s', data.errcode, data.errmsg); - this.ctx.throw(401, `微信登录失败:${data.errmsg || data.errcode}(code 可能已过期,请重试)`); - } - if (!data.openid) { - this.ctx.logger.error('[wechat-mp] jscode2session 未返回 openid: %s', JSON.stringify(data)); - this.ctx.throw(502, '微信登录失败:未获取到 openid'); - } - return { - openid: String(data.openid), - unionid: data.unionid || null, - sessionKey: data.session_key || null, - devMode: false, - }; - } - - /** 只保留 openid 允许的字符,并限制长度(DB 是 varchar(64)) */ - normalizeOpenid(value) { - const openid = String(value || '').replace(/[^A-Za-z0-9_\-@.]/g, '').slice(0, 64); - return openid || 'mock_default'; - } - - /** - * 小程序登录 - * @param {object} params code / userInfo(可选微信昵称头像)/ client - * @return {Promise<{user:object, binding:object, firstTime:boolean}>} - */ - async login({ code, userInfo }) { - const session = await this.code2Session(code); - const appid = this.appid; - - let account = await this.Account.findOne({ where: { appid, openid: session.openid } }); - let firstTime = false; - - if (!account) { - account = await this.Account.create({ - appid, - openid: session.openid, - unionid: session.unionid, - nickname: this.pickNickname(userInfo), - avatar: this.pickAvatar(userInfo), - sessionKey: session.sessionKey, - lastLoginAt: new Date(), - loginCount: 0, - }); - firstTime = true; - } - - if (account.status === 0) { - this.ctx.throw(403, '该微信已被停用,请联系管理员'); - } - - let user = account.userId ? await this.ctx.service.user.findById(account.userId) : null; - if (!user) { - user = await this.createUserFor(account, userInfo); - firstTime = true; - } - - await account.update({ - userId: user.id, - unionid: session.unionid || account.unionid, - sessionKey: session.sessionKey, - nickname: this.pickNickname(userInfo) || account.nickname, - avatar: this.pickAvatar(userInfo) || account.avatar, - lastLoginAt: new Date(), - loginCount: Number(account.loginCount || 0) + 1, - }); - - if (Number(user.status) !== 1) { - this.ctx.throw(403, '账号已被禁用,请联系管理员'); - } - await this.ctx.service.user.touchLogin(user.id); - - this.ctx.logger.info('[wechat-mp] 登录成功 userId=%s openid=%s firstTime=%s', user.id, session.openid, firstTime); - return { user, binding: this.toPublic(account.toJSON()), firstTime }; - } - - /** - * 把微信绑定到已有账号(需 user 令牌) - * 该 openid 已绑定别的账号 → 409(先解绑) - */ - async bind(userId, { code, userInfo }) { - const session = await this.code2Session(code); - const appid = this.appid; - - const exists = await this.Account.findOne({ where: { appid, openid: session.openid } }); - if (exists && exists.userId && Number(exists.userId) !== Number(userId)) { - this.ctx.throw(409, '该微信已绑定其他账号,请先在对应账号里解绑'); - } - if (exists && exists.status === 0) this.ctx.throw(403, '该微信已被停用'); - - const payload = { - userId, - unionid: session.unionid || (exists && exists.unionid) || null, - sessionKey: session.sessionKey, - nickname: this.pickNickname(userInfo) || (exists && exists.nickname) || '', - avatar: this.pickAvatar(userInfo) || (exists && exists.avatar) || '', - lastLoginAt: new Date(), - }; - - const account = exists - ? await exists.update(payload) - : await this.Account.create(Object.assign({ appid, openid: session.openid, loginCount: 0 }, payload)); - - this.ctx.logger.info('[wechat-mp] 用户 %s 绑定微信 openid=%s', userId, session.openid); - return this.toPublic((account.toJSON ? account.toJSON() : account)); - } - - /** 当前账号的微信绑定列表 */ - async listByUser(userId) { - const rows = await this.Account.findAll({ where: { userId }, order: [[ 'id', 'DESC' ]] }); - return rows.map(row => this.toPublic(row.toJSON())); - } - - /** 解绑:解绑后该 openid 不能再登录;至少要保留一种登录方式 */ - async unbind(userId, id) { - const account = await this.Account.findByPk(id); - if (!account || Number(account.userId) !== Number(userId)) this.ctx.throw(404, '绑定不存在'); - - const user = await this.ctx.service.user.findByIdWithPassword(userId); - const others = await this.Account.count({ where: { userId, id: { [Op.ne]: account.id } } }); - if (!(user && user.passwordHash) && others === 0) { - this.ctx.throw(422, '这是唯一的登录方式,请先设置密码再解绑'); - } - - await account.update({ userId: null }); - this.ctx.logger.info('[wechat-mp] 用户 %s 解绑微信 id=%s', userId, id); - return { id: Number(account.id) }; - } - - /** 给新 openid 建一个平台账号(用户名 wx_xxx,随机密码,用户可用「找回密码」设置) */ - async createUserFor(account, userInfo) { - const nickname = this.pickNickname(userInfo) || '微信用户'; - const password = crypto.randomBytes(24).toString('hex'); - - let lastError = null; - for (let i = 0; i < 5; i++) { - const username = this.candidateUsername(account.openid, i); - try { - const user = await this.ctx.service.auth.register({ - username, - password, - nickname, - email: null, - phone: null, - }); - const avatar = this.pickAvatar(userInfo); - if (avatar) await this.ctx.service.user.update(user.id, { avatar }); - this.ctx.logger.info('[wechat-mp] 新用户注册: %s (id=%s, openid=%s)', username, user.id, account.openid); - return this.ctx.service.user.findById(user.id) || user; - } catch (err) { - if (err.status !== 409) throw err; - lastError = err; - } - } - throw lastError || new Error('创建微信账号失败'); - } - - /** `wx_` + openid 末尾 12 位;重名时加随机后缀 */ - candidateUsername(openid, attempt) { - const tail = String(openid).replace(/[^A-Za-z0-9_]/g, '').slice(-12) || 'user'; - if (attempt === 0) return `wx_${tail}`; - return `wx_${tail}_${crypto.randomBytes(3).toString('hex')}`; - } - - pickNickname(userInfo) { - const nickname = String((userInfo && userInfo.nickname) || '').trim().slice(0, 64); - return nickname || ''; - } - - pickAvatar(userInfo) { - const avatar = String((userInfo && userInfo.avatar) || '').trim().slice(0, 255); - return avatar || ''; - } - - /** 对外结构(不吐 session_key / appid 内部细节) */ - toPublic(row) { - return { - id: Number(row.id), - userId: row.userId ? Number(row.userId) : null, - nickname: row.nickname || '', - avatar: row.avatar || '', - unionid: row.unionid || null, - lastLoginAt: row.lastLoginAt || null, - loginCount: Number(row.loginCount || 0), - }; - } -} - -module.exports = WechatMpService; diff --git a/backend/database/migrations/20261029100000-drop-legacy-wechat-tables.js b/backend/database/migrations/20261029100000-drop-legacy-wechat-tables.js new file mode 100644 index 0000000..65d03f8 --- /dev/null +++ b/backend/database/migrations/20261029100000-drop-legacy-wechat-tables.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 移除自建的微信授权表(`wechat_oauth`)与小程序绑定表(`wechat_mp_accounts`) + * + * 微信侧的接入已经统一到**微信登录网关**(`wechat_gateway_bindings` + 网关自己的 openid): + * - `wechat_oauth`:自建公众号网页授权(设备扫码登录手机页静默授权)+ 运维手工维护的绑定关系,已下线; + * - `wechat_mp_accounts`:小程序 `code2Session` 一键登录,已下线(小程序改用账号密码登录)。 + * + * 两张表在升级前都是空的,直接删除;`down` 会按原结构重建(不带数据)。 + */ +module.exports = { + async up(queryInterface) { + const tables = await queryInterface.showAllTables(); + + for (const table of [ 'wechat_oauth', 'wechat_mp_accounts' ]) { + if (tables.includes(table)) await queryInterface.dropTable(table); + } + }, + + async down(queryInterface, Sequelize) { + const { BIGINT, STRING, TINYINT, DATE } = Sequelize; + const tables = await queryInterface.showAllTables(); + + if (!tables.includes('wechat_oauth')) { + await queryInterface.createTable('wechat_oauth', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, + user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '关联 users.id' }, + appid: { type: STRING(64), allowNull: false, comment: '微信 appid' }, + openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' }, + unionid: { type: STRING(64), allowNull: true, comment: '开放平台 unionid' }, + nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '授权时微信昵称' }, + avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '授权时微信头像' }, + session_key: { type: STRING(128), allowNull: true, comment: '小程序 session_key' }, + access_token: { type: STRING(512), allowNull: true, comment: '网页授权 access_token' }, + refresh_token: { type: STRING(512), allowNull: true, comment: '刷新令牌' }, + scope: { type: STRING(64), allowNull: true, comment: '授权 scope' }, + token_expires_at: { type: DATE, allowNull: true, comment: 'access_token 过期时间' }, + last_auth_at: { type: DATE, allowNull: true, comment: '最近授权时间' }, + created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + deleted_at: { type: DATE, allowNull: true }, + }, { comment: '微信授权表' }); + + await queryInterface.addIndex('wechat_oauth', [ 'appid', 'openid' ], { + name: 'uk_appid_openid', + unique: true, + }); + await queryInterface.addIndex('wechat_oauth', [ 'user_id' ], { name: 'idx_user_id' }); + await queryInterface.addIndex('wechat_oauth', [ 'unionid' ], { name: 'idx_unionid' }); + } + + if (!tables.includes('wechat_mp_accounts')) { + await queryInterface.createTable('wechat_mp_accounts', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, + user_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + references: { model: 'users', key: 'id' }, + onUpdate: 'CASCADE', + onDelete: 'SET NULL', + comment: '绑定的平台账号 users.id(解绑后为空)', + }, + appid: { type: STRING(64), allowNull: false, comment: '小程序 appid' }, + openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' }, + unionid: { type: STRING(64), allowNull: true, comment: '开放平台 unionid' }, + nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '微信昵称(有授权时)' }, + avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '微信头像(有授权时)' }, + session_key: { type: STRING(128), allowNull: true, comment: 'jscode2session 返回的 session_key' }, + last_login_at: { type: DATE, allowNull: true, comment: '最近一次微信登录时间' }, + login_count: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '微信登录次数' }, + status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0停用' }, + created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + deleted_at: { type: DATE, allowNull: true }, + }, { comment: '微信小程序授权账号表' }); + + await queryInterface.addIndex('wechat_mp_accounts', [ 'appid', 'openid' ], { + name: 'uk_wechat_mp_accounts_appid_openid', + unique: true, + }); + await queryInterface.addIndex('wechat_mp_accounts', [ 'user_id' ], { name: 'idx_wechat_mp_accounts_user' }); + await queryInterface.addIndex('wechat_mp_accounts', [ 'unionid' ], { name: 'idx_wechat_mp_accounts_unionid' }); + } + }, +}; diff --git a/backend/sql/schema.sql b/backend/sql/schema.sql index 88d00b2..0d1abaa 100644 --- a/backend/sql/schema.sql +++ b/backend/sql/schema.sql @@ -48,35 +48,6 @@ CREATE TABLE IF NOT EXISTS `users` ( DEFAULT CHARSET = utf8mb4 COMMENT = '用户表'; --- --------------------------------------------------------------- --- 微信授权表:一条记录 = 某用户在某 appid 下的一次授权 --- 一个用户可绑定多个微信(公众号 / 小程序 / 开放平台) --- --------------------------------------------------------------- -CREATE TABLE IF NOT EXISTS `wechat_oauth` ( - `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键', - `user_id` BIGINT UNSIGNED NOT NULL COMMENT '关联 users.id', - `appid` VARCHAR(64) NOT NULL COMMENT '微信 appid', - `openid` VARCHAR(64) NOT NULL COMMENT '用户在该 appid 下的 openid', - `unionid` VARCHAR(64) DEFAULT NULL COMMENT '开放平台 unionid', - `nickname` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '授权时微信昵称', - `avatar` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '授权时微信头像', - `session_key` VARCHAR(128) DEFAULT NULL COMMENT '小程序 session_key', - `access_token` VARCHAR(512) DEFAULT NULL COMMENT '网页授权 access_token', - `refresh_token` VARCHAR(512) DEFAULT NULL COMMENT '刷新令牌', - `scope` VARCHAR(64) DEFAULT NULL COMMENT '授权 scope', - `token_expires_at` DATETIME DEFAULT NULL COMMENT 'access_token 过期时间', - `last_auth_at` DATETIME DEFAULT NULL COMMENT '最近授权时间', - `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_appid_openid` (`appid`, `openid`), - KEY `idx_user_id` (`user_id`), - KEY `idx_unionid` (`unionid`) -) ENGINE = InnoDB - DEFAULT CHARSET = utf8mb4 - COMMENT = '微信授权表'; - -- --------------------------------------------------------------- -- 系统配置表:group_name + config_key 唯一定位一条配置 -- 注意:唯一性由 service 层保证(先查后写),这里只建普通索引 —— diff --git a/backend/test/app/controller/wechat-mp.test.js b/backend/test/app/controller/wechat-mp.test.js deleted file mode 100644 index 69a92f5..0000000 --- a/backend/test/app/controller/wechat-mp.test.js +++ /dev/null @@ -1,156 +0,0 @@ -'use strict'; - -const { app, mock, assert } = require('egg-mock/bootstrap'); -const createFakeRedis = require('../../utils/fake-redis'); - -const instance = (data) => Object.assign( - { - toJSON: () => data, - update: async (fields) => Object.assign(data, fields), - }, - data, -); - -describe('test/app/controller/wechat-mp.test.js', () => { - const agreement = { - id: 9, - code: 'user_agreement', - name: '用户协议', - required: true, - version: { id: 11, version: '1.0.0', title: '用户协议', content: '正文' }, - }; - const accepted = [{ code: 'user_agreement', versionId: 11 }]; - - it('未同意协议 → 428(与账号密码登录一致)', async () => { - mock(app, 'redis', createFakeRedis().client); - app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); - - const res = await app.httpRequest() - .post('/api/web/auth/wechat/login') - .send({ code: 'mock:openid-abc' }) - .expect(428); - - assert(res.body.status === 'agreement_required', JSON.stringify(res.body)); - assert(res.body.data.agreements[0].code === 'user_agreement', JSON.stringify(res.body)); - }); - - it('首次登录:按 openid 建账号 + 绑定,返回 firstTime=true', async () => { - mock(app, 'redis', createFakeRedis().client); - - let account = null; - mock(app, 'model', { - WechatMpAccount: { - async findOne() { - return account ? instance(account.data) : null; - }, - async create(data) { - account = { data: Object.assign({ id: 5, loginCount: 0, nickname: '', avatar: '' }, data) }; - return instance(account.data); - }, - }, - }); - - let registered = null; - app.mockService('auth', 'register', async (payload) => { - registered = payload; - return { id: 42, username: payload.username, nickname: payload.nickname }; - }); - app.mockService('user', 'findById', async () => ({ id: 42, username: registered.username, status: 1, nickname: '微信用户' })); - app.mockService('user', 'touchLogin', async () => null); - app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); - app.mockService('agreement', 'record', async () => [{ code: 'user_agreement', versionId: 11, version: '1.0.0' }]); - - const res = await app.httpRequest() - .post('/api/web/auth/wechat/login') - .send({ code: 'mock:openid-abc', agreements: accepted }) - .expect(200); - - assert(res.body.ok === true, JSON.stringify(res.body)); - assert(res.body.data.firstTime === true, JSON.stringify(res.body.data)); - assert(res.body.data.wechat.userId === 42, JSON.stringify(res.body.data.wechat)); - assert(registered && registered.username.startsWith('wx_'), JSON.stringify(registered)); - assert(res.body.data.agreements[0].versionId === 11, JSON.stringify(res.body.data)); - }); - - it('已绑定账号再登录:复用账号,不重复建用户', async () => { - mock(app, 'redis', createFakeRedis().client); - - const account = { - id: 5, - userId: 7, - status: 1, - loginCount: 3, - nickname: '', - avatar: '', - data: { id: 5, userId: 7, status: 1, loginCount: 3, nickname: '', avatar: '' }, - }; - mock(app, 'model', { - WechatMpAccount: { - async findOne() { - return instance(account.data); - }, - }, - }); - app.mockService('user', 'findById', async () => ({ id: 7, username: 'demo', status: 1 })); - app.mockService('user', 'touchLogin', async () => null); - app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); - app.mockService('agreement', 'record', async () => []); - - const res = await app.httpRequest() - .post('/api/web/auth/wechat/login') - .send({ code: 'mock:openid-abc', agreements: accepted }) - .expect(200); - - assert(res.body.data.firstTime === false, JSON.stringify(res.body.data)); - assert(res.body.data.user.id === 7, JSON.stringify(res.body.data.user)); - assert(res.body.data.wechat.loginCount === 4, JSON.stringify(res.body.data.wechat)); - }); - - it('缺 code → 422;账号被禁用 → 403', async () => { - mock(app, 'redis', createFakeRedis().client); - app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); - - await app.httpRequest().post('/api/web/auth/wechat/login').send({ agreements: accepted }).expect(422); - - mock(app, 'model', { - WechatMpAccount: { - async findOne() { - return instance({ id: 5, userId: 7, status: 1, loginCount: 0, nickname: '', avatar: '' }); - }, - }, - }); - app.mockService('user', 'findById', async () => ({ id: 7, username: 'demo', status: 0 })); - - const res = await app.httpRequest() - .post('/api/web/auth/wechat/login') - .send({ code: 'mock:openid-abc', agreements: accepted }) - .expect(403); - assert(res.body.message.includes('禁用'), JSON.stringify(res.body)); - }); - - it('绑定:openid 已属于别人 → 409', async () => { - mock(app, 'redis', createFakeRedis().client); - - mock(app, 'model', { - // apiAuth 会用 service.user.findById → User.findByPk - User: { - async findByPk() { - return instance({ id: 7, username: 'demo', status: 1 }); - }, - }, - WechatMpAccount: { - async findOne() { - return instance({ id: 5, userId: 99, status: 1 }); - }, - }, - }); - - const token = app.createAnonymousContext().service.jwt.signUser({ id: 7, username: 'demo' }); - const res = await app.httpRequest() - .post('/api/web/auth/wechat/bind') - .set('Authorization', `Bearer ${token}`) - .send({ code: 'mock:openid-other' }) - .expect(409); - assert(res.body.message.includes('已绑定其他账号'), JSON.stringify(res.body)); - }); -}); diff --git a/backend/test/app/controller/wechat.test.js b/backend/test/app/controller/wechat.test.js deleted file mode 100644 index 40976e2..0000000 --- a/backend/test/app/controller/wechat.test.js +++ /dev/null @@ -1,184 +0,0 @@ -'use strict'; - -const { app, mock, assert } = require('egg-mock/bootstrap'); -const createFakeRedis = require('../../utils/fake-redis'); -const { HEADER: INTERNAL } = require('../../utils/internal'); - -/** 微信绑定关系的读写属「内部接口」:请求都带上运维令牌 */ -const http = { - get: url => app.httpRequest().get(url).set(INTERNAL), - post: url => app.httpRequest().post(url).set(INTERNAL), - put: url => app.httpRequest().put(url).set(INTERNAL), - delete: url => app.httpRequest().delete(url).set(INTERNAL), -}; - -const instance = (data) => Object.assign( - { - toJSON: () => data, - update: async (fields) => Object.assign(data, fields), - }, - data, -); - -describe('test/app/controller/wechat.test.js', () => { - beforeEach(() => { - mock(app, 'redis', createFakeRedis().client); - }); - - it('POST /api/wechat/bind 首次绑定创建记录(201)', async () => { - mock(app, 'model', { - WechatOauth: { - async findOne() { - return null; - }, - async create(data) { - assert(data.userId === 1); - assert(data.appid === 'wx123'); - assert(data.openid === 'o_abc'); - assert(data.lastAuthAt instanceof Date, '应记录最近授权时间'); - return instance(Object.assign({ id: 9 }, data)); - }, - }, - }); - - const res = await http - .post('/api/wechat/bind') - .send({ userId: 1, appid: 'wx123', openid: 'o_abc', nickname: '微信昵称' }) - .expect(201); - - assert(res.body.data.id === 9); - assert(res.body.data.nickname === '微信昵称'); - }); - - it('POST /api/wechat/bind 已存在时更新(含换绑用户)', async () => { - let updated = null; - mock(app, 'model', { - WechatOauth: { - async findOne() { - return instance({ - id: 9, - userId: 1, - appid: 'wx123', - openid: 'o_abc', - update: async (fields) => { - updated = fields; - }, - }); - }, - }, - }); - - await http - .post('/api/wechat/bind') - .send({ userId: 2, appid: 'wx123', openid: 'o_abc', sessionKey: 'sk-1' }) - .expect(201); - - assert(updated.userId === 2, '应支持把授权记录换绑到另一个用户'); - assert(updated.sessionKey === 'sk-1'); - }); - - it('POST /api/wechat/bind 缺少必填参数返回 422', async () => { - await http.post('/api/wechat/bind').send({ appid: 'wx123' }).expect(422); - }); - - it('GET /api/wechat/:appid/:openid 返回授权与关联用户', async () => { - mock(app, 'model', { - User: { name: 'User' }, - WechatOauth: { - async findOne() { - return instance({ - id: 9, - appid: 'wx123', - openid: 'o_abc', - user: { id: 1, nickname: '张三', deleted_at: null }, - }); - }, - }, - }); - - const res = await http.get('/api/wechat/wx123/o_abc').expect(200); - assert(res.body.data.user.nickname === '张三'); - assert(res.body.data.user.deleted_at === undefined, '不应透出软删除字段'); - }); - - it('GET /api/wechat/:appid/:openid 不存在返回 404', async () => { - mock(app, 'model', { - User: {}, - WechatOauth: { - async findOne() { - return null; - }, - }, - }); - - await http.get('/api/wechat/wx123/o_none').expect(404); - }); - - it('GET /api/users/:id/wechats 返回该用户的授权列表', async () => { - mock(app, 'model', { - WechatOauth: { - async findAll(options) { - assert(options.where.userId === 1); - return [ instance({ id: 9, appid: 'wx123', openid: 'o_abc' }) ]; - }, - }, - }); - - const res = await http.get('/api/users/1/wechats').expect(200); - assert(res.body.data.total === 1); - }); - - it('PUT /api/wechat/:id/tokens 更新令牌', async () => { - mock(app, 'model', { - WechatOauth: { - async findByPk(id) { - assert(id === 9); - return instance({ - id: 9, - update: async fields => { - assert(fields.accessToken === 'at-1'); - assert(fields.tokenExpiresAt instanceof Date); - }, - }); - }, - }, - }); - - await http - .put('/api/wechat/9/tokens') - .send({ accessToken: 'at-1', expiresIn: 7200 }) - .expect(200); - }); - - it('PUT /api/wechat/:id/tokens 记录不存在返回 404', async () => { - mock(app, 'model', { - WechatOauth: { - async findByPk() { - return null; - }, - }, - }); - - await http.put('/api/wechat/9/tokens').send({ accessToken: 'at-1' }).expect(404); - }); - - it('DELETE /api/wechat/:id 解绑成功 / 不存在返回 404', async () => { - mock(app, 'model', { - WechatOauth: { - async destroy() { - return 1; - }, - }, - }); - await http.delete('/api/wechat/9').expect(200); - - mock(app, 'model', { - WechatOauth: { - async destroy() { - return 0; - }, - }, - }); - await http.delete('/api/wechat/9').expect(404); - }); -}); diff --git a/miniprogram/.env.example b/miniprogram/.env.example index cd98247..eca6fc9 100644 --- a/miniprogram/.env.example +++ b/miniprogram/.env.example @@ -2,7 +2,3 @@ # 本地联调:复制成 .env.development(已被根 .gitignore 忽略) # 真机/发布:必须是 https 域名,并在小程序后台「开发设置 → 服务器域名」里配好 request 合法域名 VITE_API_BASE=http://127.0.0.1:7300 - -# 仅本地联调用:H5 / 开发者工具里拿不到微信 code 时的 mock openid -# 需要后端同时允许 mock(未配置 WX_MP_APPID 时本地默认允许,生产需显式 WX_MP_MOCK=true) -# VITE_WX_MOCK_OPENID=demo-openid diff --git a/miniprogram/README.md b/miniprogram/README.md index 1280175..374fa11 100644 --- a/miniprogram/README.md +++ b/miniprogram/README.md @@ -65,7 +65,7 @@ VITE_API_BASE=http://127.0.0.1:7300 | 首页(统计) | `pages/index/index` | 是(功能介绍) | `GET /api/web/subjects`、`GET /api/web/stats` | | 扫码记录 | `pages/records/index` | 否(`pageGuards`) | `GET /api/web/records`、`GET /api/web/devices` | | 个人中心 | `pages/profile/index` | 是(欢迎卡片) | `GET /api/web/me`、`PUT /api/web/me`、`GET /api/web/subjects` | -| 登录(整页兜底) | `pages/login/index` | 是 | `GET /api/agreements/current`、`POST /api/web/auth/login`、`POST /api/web/auth/wechat/login` | +| 登录(整页兜底) | `pages/login/index` | 是 | `GET /api/agreements/current`、`POST /api/web/auth/login` | | 登录抽屉 | `components/LoginDrawer.vue` | 是 | 同上(与整页登录共用 `LoginPanel`) | 登录没有独立页面:它是一张从底部弹出的抽屉卡片([`src/components/LoginDrawer.vue`](src/components/LoginDrawer.vue)), @@ -73,13 +73,12 @@ VITE_API_BASE=http://127.0.0.1:7300 **不会一进入小程序就弹出**:只有点页面里的「登录」按钮、进入需要登录的页面、或接口返回 401 时才弹(见上面「登录时机」)。 打开时隐藏原生 tabBar,登录成功后关闭并留在当前页。 -登录面板有两个 tab([`src/components/LoginPanel.vue`](src/components/LoginPanel.vue)): +登录面板([`src/components/LoginPanel.vue`](src/components/LoginPanel.vue))只有一种登录方式: -- **微信登录(默认,优先)**:点「微信一键登录」→ `uni.login()` 拿 code → `POST /api/web/auth/wechat/login`; - 首次登录后端按 openid 自动建账号(`firstTime`),提示「已为你创建账号」; - **账号登录**:用户名 / 手机号 / 邮箱 + 密码。 +- 小程序的「微信一键登录」(`uni.login()` → `POST /api/web/auth/wechat/login`)已下线:后端移除了 + `wechat_mp_accounts` 表与整套小程序 code2Session 逻辑,微信侧接入统一走 Web 端的「微信登录网关」(扫码登录 / 绑定微信)。 -H5 / 开发者工具里 `uni.login` 拿不到 code,可设 `VITE_WX_MOCK_OPENID=` 走后端 mock(仅本地联调)。 H5 预览时接口走 Vite 的 `/api` 反代(`vite.config.ts` 的 `server.proxy`),不需要后端开 CORS。 **个人中心例外**:那里的「登录」跳整页登录 [`src/pages/login/index.vue`](src/pages/login/index.vue)(`navigateTo`), @@ -104,7 +103,7 @@ H5 预览时接口走 Vite 的 `/api` 反代(`vite.config.ts` 的 `server.prox - 401 清令牌,并按 `AUTH_POLICY.promptOnUnauthorized` 弹登录(不跳页);`400 subject_required` / `403 subject_expired` 由页面自己提示。 - 登录 / 退出后 `authVersion` 自增,页面 `watch` 它刷新或清空数据。 - 主体(租户)是设备与扫码记录的归属单位:小程序里只做切换,创建主体仍在 Web 端。 -- 微信一键登录走小程序自己的后端模块(`/api/web/auth/wechat/*`),与公众号扫码登录(`wechat_oauth`)分开;视频回放仍未接入。 +- 微信扫码登录 / 绑定微信走 Web 端的登录网关(`/api/web/auth/wechat-gateway/*`),小程序里没有扫码入口;视频回放仍未接入。 ## H5 预览(可选,方便不装开发者工具时看页面) diff --git a/miniprogram/src/api/types.ts b/miniprogram/src/api/types.ts index d8dd1db..cf36387 100644 --- a/miniprogram/src/api/types.ts +++ b/miniprogram/src/api/types.ts @@ -120,20 +120,3 @@ export interface AgreementConsentRecord { version: string; agreedAt: string; } - -/** 微信小程序绑定信息(不包含 session_key 等敏感字段) */ -export interface WechatMpBinding { - id: number; - userId: number | null; - nickname: string; - avatar: string; - unionid?: string | null; - lastLoginAt?: string | null; - loginCount: number; -} - -/** 微信小程序登录结果(`firstTime` = 刚自动建的新账号) */ -export interface WechatLoginResult extends LoginResult { - firstTime?: boolean; - wechat?: WechatMpBinding; -} diff --git a/miniprogram/src/api/web.ts b/miniprogram/src/api/web.ts index cde9d16..c438932 100644 --- a/miniprogram/src/api/web.ts +++ b/miniprogram/src/api/web.ts @@ -14,7 +14,6 @@ import type { ScanRecord, Stats, SubjectItem, - WechatLoginResult, } from '@/api/types'; /** 拼查询串(小程序环境不一定有 URLSearchParams) */ @@ -47,26 +46,6 @@ export function login( ); } -/** - * 微信小程序登录:`uni.login()` 的 code 换 openid,未绑定过的 openid 自动建账号 - * - * @param code `uni.login()` 拿到的 code(本地联调可用 `mock:`) - * @param agreements 当前同意的协议版本(小程序客户端必填) - * @param userInfo 微信昵称/头像(可选,仅用于展示) - */ -export function wechatLogin( - code: string, - agreements: AgreementAcceptance[] = [], - userInfo?: { nickname?: string; avatar?: string }, - client = 'mini_program', -): Promise { - return api.post( - '/api/web/auth/wechat/login', - { code, agreements, userInfo, client }, - { auth: false }, - ); -} - /** 当前登录用户 */ export function fetchMe(): Promise { return api.get('/api/web/me'); diff --git a/miniprogram/src/components/LoginPanel.vue b/miniprogram/src/components/LoginPanel.vue index 3e768f7..14f8200 100644 --- a/miniprogram/src/components/LoginPanel.vue +++ b/miniprogram/src/components/LoginPanel.vue @@ -2,20 +2,19 @@ /** * 登录表单面板:抽屉(`LoginDrawer`)与页面版登录(`pages/login`)共用 * - * - 两个 tab:**微信登录(默认,优先)** / 账号登录; + * - 只有账号密码登录(微信一键登录已下线:微信侧接入统一走 Web 端的扫码登录网关); * - 协议正文单独弹窗(`AgreementDialog`),面板里只留「我已阅读并同意《xx》」一行; - * - 两种登录都必须先同意当前协议版本; + * - 登录必须先同意当前协议版本; * - 每次 `active` 变成 true 都清空勾选并重拉协议(同意记录按「登录」这一动作落库); * - 登录成功只抛 `success`,关抽屉 / 返回上一页交给使用方。 */ import { computed, reactive, ref, watch } from 'vue'; import { ApiError } from '@/api/client'; -import { fetchAgreements, login, wechatLogin } from '@/api/web'; -import type { AgreementItem, WechatLoginResult } from '@/api/types'; +import { fetchAgreements, login } from '@/api/web'; +import type { AgreementItem, LoginResult } from '@/api/types'; import AgreementDialog from '@/components/AgreementDialog.vue'; import { setSession } from '@/composables/useAuth'; import { applySubjects } from '@/composables/useSubject'; -import { getWechatLoginCode } from '@/utils/wechat'; const props = withDefaults(defineProps<{ /** 面板是否处于打开状态(true 时重置勾选并加载协议) */ @@ -32,10 +31,6 @@ const emit = defineEmits<{ (e: 'cancel'): void; }>(); -type Tab = 'wechat' | 'account'; - -/** 默认落在微信登录(优先) */ -const tab = ref('wechat'); const form = reactive({ account: '', password: '' }); const busy = ref(false); const error = ref(''); @@ -57,8 +52,7 @@ const agreementsReady = computed( () => !agreementsLoading.value && !agreementsError.value && allAgreed.value, ); -const canSubmitWechat = computed(() => agreementsReady.value); -const canSubmitAccount = computed( +const canSubmit = computed( () => Boolean(form.account.trim() && form.password) && agreementsReady.value, ); @@ -108,7 +102,6 @@ watch( if (!active) return; error.value = ''; tip.value = ''; - tab.value = 'wechat'; accepted.value = {}; readerVisible.value = false; reading.value = null; @@ -118,7 +111,7 @@ watch( ); /** 登录成功后统一收尾:落地令牌 + 主体列表,抛事件给使用方 */ -function finish(data: WechatLoginResult, message: string) { +function finish(data: LoginResult, message: string) { setSession(data.token, data.user); // 登录接口直接下发主体列表,落地后页面就不用再请求一次 if (Array.isArray(data.subjects)) applySubjects(data.subjects); @@ -137,37 +130,6 @@ async function handleAgreementRequired(err: ApiError, fallback: string) { await loadAgreements(); } -async function doWechatLogin() { - if (busy.value) return; - error.value = ''; - tip.value = ''; - if (!allAgreed.value) { - error.value = '请先阅读并同意协议'; - return; - } - - busy.value = true; - try { - const code = await getWechatLoginCode(); - const payload = requiredAgreements.value.map(item => ({ - code: item.code, - versionId: item.version.id, - })); - const data = await wechatLogin(code, payload); - finish(data, data.firstTime ? '微信登录成功,已为你创建账号' : '微信登录成功'); - } catch (err) { - if (err instanceof ApiError && err.code === 'agreement_required') { - await handleAgreementRequired(err, '协议已更新,请重新阅读并同意'); - } else if (err instanceof ApiError) { - error.value = err.message; - } else { - error.value = err instanceof Error ? err.message : '微信登录失败,请稍后再试'; - } - } finally { - busy.value = false; - } -} - async function doLogin() { if (busy.value) return; error.value = ''; @@ -199,67 +161,36 @@ async function doLogin() { busy.value = false; } } - -function switchTab(next: Tab) { - if (tab.value === next) return; - tab.value = next; - error.value = ''; - tip.value = ''; -}