67 lines
2.2 KiB
JavaScript
67 lines
2.2 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
|
||
/**
|
||
* 成员绑定(手机扫码侧)
|
||
*
|
||
* 流程与扫码登录一个套路:
|
||
* 1. 电脑端 `POST /api/web/subjects/:id/members/:memberId/bind-code` 生成 6 位码 → 画二维码
|
||
* 2. 手机扫码打开前端 `/wechat?bind=<码>`
|
||
* 3. 手机侧轮询 `GET /api/subject/member-bind?code=`(公开)拿状态
|
||
* 4. 已登录的账号点「确认绑定」→ `POST /api/subject/member-bind/confirm`(要 user JWT)
|
||
* → 该账号被写进 `subject_members.user_id`,从此可以进入这个主体
|
||
*/
|
||
class MemberBindController extends Controller {
|
||
/** GET /api/subject/member-bind?code=ABC123 —— 绑定码状态(公开) */
|
||
async status() {
|
||
const { ctx } = this;
|
||
const code = String(ctx.query.code || '').trim();
|
||
|
||
if (!code) {
|
||
ctx.status = 422;
|
||
ctx.body = { ok: false, status: 'bad_format', message: '缺少绑定码' };
|
||
return;
|
||
}
|
||
if (!/^[0-9A-Z]{4,12}$/i.test(code)) {
|
||
ctx.status = 422;
|
||
ctx.body = { ok: false, status: 'bad_format', message: '绑定码格式不对' };
|
||
return;
|
||
}
|
||
|
||
const result = await ctx.service.subject.bindStatus(code);
|
||
ctx.status = result.status === 'expired' ? 410 : 200;
|
||
ctx.body = { ok: true, data: result };
|
||
}
|
||
|
||
/** POST /api/subject/member-bind/confirm —— body { code },把当前登录账号绑到该成员 */
|
||
async confirm() {
|
||
const { ctx } = this;
|
||
const body = ctx.request.body || {};
|
||
const code = String(body.code || ctx.query.code || '').trim();
|
||
|
||
if (!code) ctx.throw(422, '缺少绑定码');
|
||
|
||
const user = ctx.state.user;
|
||
const result = await ctx.service.subject.confirmBind(code, user.id);
|
||
if (!result.ok) {
|
||
const mapping = {
|
||
bad_param: 422,
|
||
expired: 410,
|
||
used: 410,
|
||
bound: 409,
|
||
joined: 409,
|
||
};
|
||
ctx.status = mapping[result.reason] || 400;
|
||
ctx.body = { ok: false, status: result.reason, message: result.message };
|
||
return;
|
||
}
|
||
|
||
ctx.logger.info('[subject] %s 扫码确认成为主体 %s 的成员「%s」',
|
||
user.username || user.id, result.subjectId, result.memberName);
|
||
ctx.body = { ok: true, data: result };
|
||
}
|
||
}
|
||
|
||
module.exports = MemberBindController;
|