'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;