'use strict'; const { Controller } = require('egg'); /** * 运维/内部:微信授权(绑定关系)的读写 * * 挂在 `middleware.internalAuth()` 后面(见 app/middleware/internal_auth.js)。 * * 用户侧的扫码确认在 `app/controller/client/wechat.js`,公开的发码/查码在 `app/controller/auth/wechat.js`。 */ class InternalWechatController extends Controller { /** GET /api/users/:id/wechats —— 某用户的全部微信授权 */ async indexByUser() { const { ctx } = this; const userId = Number(ctx.params.id); if (!Number.isInteger(userId) || userId <= 0) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const list = await ctx.service.wechat.listByUser(userId); ctx.body = { ok: true, data: { list, total: list.length } }; } /** GET /api/wechat/:appid/:openid —— 按 appid + openid 反查授权与用户 */ async show() { const { ctx } = this; const { appid, openid } = ctx.params; const data = await ctx.service.wechat.findByOpenid(appid, openid); if (!data) { ctx.status = 404; ctx.body = { ok: false, message: '授权记录不存在' }; return; } ctx.body = { ok: true, data }; } /** POST /api/wechat/bind —— 绑定(已存在则更新) */ async bind() { const { ctx } = this; const { userId, appid, openid } = ctx.request.body || {}; if (!userId || !appid || !openid) { ctx.status = 422; ctx.body = { ok: false, message: 'userId、appid、openid 均为必填' }; return; } const data = await ctx.service.wechat.bind(ctx.request.body); ctx.status = 201; ctx.body = { ok: true, data }; } /** PUT /api/wechat/:id/tokens —— 更新 session_key / 令牌 */ async updateTokens() { const { ctx } = this; const id = Number(ctx.params.id); if (!Number.isInteger(id) || id <= 0) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const data = await ctx.service.wechat.updateTokens(id, ctx.request.body || {}); if (!data) { ctx.status = 404; ctx.body = { ok: false, message: '授权记录不存在' }; return; } ctx.body = { ok: true, data }; } /** DELETE /api/wechat/:id —— 解绑 */ async unbind() { const { ctx } = this; const id = Number(ctx.params.id); if (!Number.isInteger(id) || id <= 0) { ctx.status = 400; ctx.body = { ok: false, message: 'id 必须是正整数' }; return; } const removed = await ctx.service.wechat.unbind(id); if (!removed) { ctx.status = 404; ctx.body = { ok: false, message: '授权记录不存在' }; return; } ctx.body = { ok: true, data: { id } }; } } module.exports = InternalWechatController;