liufumingren 517fafeef9 refactor(web): 登录会话与协议同意逻辑抽到 service/login
账号密码登录、微信小程序登录共用同一套:客户端归一、协议校验(428)、
落库同意记录、签发令牌 + 主体列表。auth 控制器只保留参数校验与业务编排。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 00:47:06 +08:00

90 lines
2.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 CLIENTS = [ 'mini_program', 'web', 'h5' ];
/**
* 登录会话(账号密码登录 / 微信小程序登录共用)
*
* - `issue(user)`:签发 user JWT + 带上可进入的主体列表
* - `requireAgreements(input)`:校验协议是否为当前版本,不通过直接写 428
* - `recordAgreements(user, accepted, client)`:把同意记录落库
*/
class LoginService extends Service {
/** 客户端标识归一(非法返回空串) */
normalizeClient(value) {
const client = String(value || '').trim().toLowerCase();
return CLIENTS.includes(client) ? client : '';
}
/** 当前配置下,这个客户端是否必须先同意协议 */
shouldEnforceAgreement(client) {
const mode = String(this.app.config.agreement.enforce || 'mini_program').toLowerCase();
if ([ 'off', 'false', '0', 'no' ].includes(mode)) return false;
if (mode === 'all') return true;
return client === 'mini_program';
}
/**
* 校验协议同意情况
* @return {Promise<Array|null>} 通过 → 可落库的 `[{ agreementId, code, versionId, version }]`;
* 不通过 → 写 428 并返回 null
*/
async requireAgreements(input) {
const { ctx } = this;
const required = await ctx.service.agreement.requiredVersions();
const check = ctx.service.agreement.verifyAcceptance(required, input);
if (check.ok) return check.accepted;
ctx.status = 428;
ctx.body = {
ok: false,
status: 'agreement_required',
message: '请阅读并同意用户协议后再登录',
data: { agreements: required },
};
return null;
}
/** 落库同意记录(失败不阻断登录,只记错误日志) */
async recordAgreements(user, accepted, client) {
const { ctx } = this;
try {
return await ctx.service.agreement.record(user.id, accepted, {
source: client || 'unknown',
ip: ctx.ip,
userAgent: String(ctx.get('user-agent') || ''),
});
} catch (err) {
ctx.logger.error('[login] 记录协议同意失败, userId=%s: %s', user.id, err.message);
return [];
}
}
/**
* 签发令牌 + 返回脱敏用户
*
* `subjects` 带上当前账号可进入的主体列表(前端登录后直接拿它渲染切换器,不用再请求一次)
*/
async issue(user) {
const { ctx } = this;
let subjects = [];
try {
subjects = await ctx.service.subject.listForUser(user.id);
} catch (err) {
ctx.logger.warn('[login] 登录时读取主体列表失败: %s', err.message);
}
return {
token: ctx.service.jwt.signUser(user),
tokenType: 'Bearer',
expiresIn: this.app.config.jwt.userExpiresIn,
user,
subjects,
};
}
}
module.exports = LoginService;