'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())}`; }