packServer/backend/app/middleware/subject_active.js
liufumingren 7b11f7052d feat(subject): 主体到期暂停设备上报,新增续期订单与支付回调
- 主体状态缓存(Redis 优先、进程内兜底):设备心跳与上报判断不再查库,续期/停用后主动失效
- 上报写接口按缓存校验期限:过期 403 subject_expired、停用 subject_disabled、主体缺失 subject_missing
- 心跳与 /api/scanner/me 返回 subject 状态,桌面端据此暂停推送并在续期后自动补传积压
- 新增续期订单(subject_orders)与接口,支付回调 POST /api/pay/notify 幂等、支持 HMAC 签名,
  另提供内部令牌模拟支付用于联调
- 顺带提交工作区中已完成的「登录协议」后端改动(agreement):与本次改动共用 router.js / config.default.js

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-20 18:55:57 +08:00

58 lines
2.1 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';
/**
* 设备上报时的主体可用性检查(**必须在 scannerAuth 之后**)
*
* 用法:`router.post('/api/scan/records', scannerAuth, subjectActive(), controller...)`
*
* - 设备没有归属主体(历史数据 `subject_id` 为空)→ 放行,保持老设备可用;
* - 主体已停用 → 403 `subject_disabled`;
* - 主体已过期 → 403 `subject_expired`(带 expireAt,设备据此暂停上报并等待续期)。
*
* 状态来自 `service.subjectState` 缓存,**不查数据库**;续期后由写库方主动失效缓存。
* 心跳 / `me` 这两个接口不挂本中间件 —— 它们就是设备用来探测「是否已续期」的通道。
*/
module.exports = () => {
return async function subjectActive(ctx, next) {
const scanner = ctx.state.scanner;
const subjectId = scanner && Number(scanner.subjectId);
// 老数据(设备没挂主体)保持原行为,不做限制
if (!subjectId) return next();
const state = await ctx.service.subjectState.get(subjectId);
if (!state) {
ctx.status = 403;
ctx.body = { ok: false, status: 'subject_missing', message: '设备所属主体不存在,请联系管理员' };
return;
}
if (state.disabled) {
ctx.status = 403;
ctx.body = { ok: false, status: 'subject_disabled', message: '主体已被停用,请联系管理员' };
return;
}
if (state.expired) {
ctx.status = 403;
ctx.body = {
ok: false,
status: 'subject_expired',
message: `主体「${state.name}」使用期限已到(${formatDate(state.expireAt)}),请联系管理员续期`,
expireAt: state.expireAt,
remainingSeconds: 0,
};
return;
}
await next();
};
};
/** yyyy-MM-dd HH:mm(服务器本地时间,仅用于提示文案) */
function formatDate(value) {
if (!value) return '';
const date = new Date(value);
const pad = num => String(num).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}