96 lines
3.2 KiB
JavaScript
Raw Permalink 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';
/**
* 主体上下文(**必须在 apiAuth 之后**)
*
* 用法:`router.get('/api/web/cameras', apiAuth, subjectAuth, controller...)`
*
* 取值顺序:`X-Subject-Id` header > `?subjectId=` > body.subjectId
* (前端 SPA 统一走 header,见 `frontend/src/api/client.ts`)
*
* 通过后写入:
* - `ctx.state.subjectId` / `ctx.locals.subjectId`
* - `ctx.state.subject` / `ctx.locals.subject`(主体实例)
* - `ctx.state.subjectMember`(当前用户在该主体里的成员记录,含姓名 / 角色)
*
* 失败:
* - 缺参数 → 400 `{ status:'subject_required' }`(前端据此提示「请先创建/选择主体」)
* - 不是成员 / 主体不存在 → 404
* - 主体被停用 → 403 `subject_disabled`
* - 主体已过期 → 403 `subject_expired`(带 expireAt,前端据此提示续期)
*/
module.exports = () => {
return async function subjectAuth(ctx, next) {
const raw = pickSubjectId(ctx);
if (!raw) {
ctx.status = 400;
ctx.body = {
ok: false,
status: 'subject_required',
message: '缺少主体 id(请在 header 里带 X-Subject-Id)',
};
return;
}
const subjectId = Number(raw);
if (!Number.isInteger(subjectId) || subjectId <= 0) {
ctx.status = 400;
ctx.body = { ok: false, status: 'subject_required', message: '主体 id 不合法' };
return;
}
const { subject, member } = await ctx.service.subject.findForUser(subjectId, ctx.state.user.id);
if (Number(subject.status) !== 1) {
ctx.status = 403;
ctx.body = { ok: false, status: 'subject_disabled', message: '主体已被停用,请联系管理员' };
return;
}
if (ctx.service.subject.isExpired(subject)) {
ctx.status = 403;
ctx.body = {
ok: false,
status: 'subject_expired',
message: `主体「${subject.name}」使用期限已到(${formatDate(subject.expireAt)}),请联系管理员续期`,
expireAt: subject.expireAt,
};
return;
}
ctx.locals = ctx.locals || {};
ctx.locals.subjectId = subjectId;
ctx.locals.subject = subject;
ctx.locals.subjectMember = member;
ctx.state.subjectId = subjectId;
ctx.state.subject = subject;
ctx.state.subjectMember = member;
await next();
};
};
/** 从 header / query / body 里取主体 id(前端统一用 header) */
function pickSubjectId(ctx) {
const fromHeader = String(ctx.get('x-subject-id') || '').trim();
if (fromHeader) return fromHeader;
const fromQuery = ctx.query && ctx.query.subjectId;
if (fromQuery !== undefined && fromQuery !== null && String(fromQuery).trim() !== '') {
return String(fromQuery).trim();
}
const body = ctx.request && ctx.request.body;
if (body && body.subjectId !== undefined && body.subjectId !== null && String(body.subjectId).trim() !== '') {
return String(body.subjectId).trim();
}
return '';
}
/** 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())}`;
}