refactor: 缓存后台请求级权限校验
This commit is contained in:
1 parent
00aeaa3cb1
commit
4cd3749806
3 files changed
+119
-17
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
||||
"generatedAt": "2026-10-23T04:56:52.289Z",
|
||||
"generatedAt": "2026-10-23T04:57:00.699Z",
|
||||
"templates": {
|
||||
"acheng-campus-food": {
|
||||
"real-manifest-interaction": {
|
||||
@@ -256,5 +256,5 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"sourceTreeHash": "503e7b49d4b7c34c3405cd3d89e58e624a30e4c4831997480ebd7d4359c34052"
|
||||
"sourceTreeHash": "1ffdc0a1b62271bbb621546a212aa7a05f1d0b797963a6332ce14bc5c35fe1ab"
|
||||
}
|
||||
@@ -4,16 +4,36 @@ import { PrismaService } from "./prisma.service.js";
|
||||
import { readAdminToken } from "./admin-access.identity.js";
|
||||
import { readIdentity } from "./auth.js";
|
||||
|
||||
type TokenAccess = {
|
||||
subject: string;
|
||||
brandId: string;
|
||||
mustChangePassword: boolean;
|
||||
tokenVersion: number;
|
||||
platformTemplateRole: string;
|
||||
};
|
||||
|
||||
type BrandAccess = { subject: string; brandId: string; role: string };
|
||||
|
||||
@Injectable()
|
||||
export class AdminAccessService {
|
||||
/**
|
||||
* 同一 HTTP 请求内 Guard 和 Controller 都会调用访问校验。
|
||||
* 用 WeakMap 按请求缓存结果,既避免重复查询,也不会把权限状态跨请求缓存。
|
||||
*/
|
||||
private readonly tokenAccess = new WeakMap<FastifyRequest, Promise<TokenAccess>>();
|
||||
private readonly brandAccess = new WeakMap<FastifyRequest, Promise<BrandAccess>>();
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async requireToken(request: FastifyRequest): Promise<{
|
||||
subject: string;
|
||||
brandId: string;
|
||||
mustChangePassword: boolean;
|
||||
tokenVersion: number;
|
||||
}> {
|
||||
requireToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||
const cached = this.tokenAccess.get(request);
|
||||
if (cached) return cached;
|
||||
const pending = this.resolveToken(request);
|
||||
this.tokenAccess.set(request, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async resolveToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||
const token = readAdminToken(request);
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
@@ -25,7 +45,12 @@ export class AdminAccessService {
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
|
||||
select: {
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
tokenVersion: true,
|
||||
platformTemplateRole: true,
|
||||
},
|
||||
});
|
||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||
@@ -35,12 +60,19 @@ export class AdminAccessService {
|
||||
brandId: identity.brandId,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
tokenVersion: user.tokenVersion,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
};
|
||||
}
|
||||
|
||||
async requireBrand(
|
||||
request: FastifyRequest,
|
||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
||||
requireBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||
const cached = this.brandAccess.get(request);
|
||||
if (cached) return cached;
|
||||
const pending = this.resolveBrand(request);
|
||||
this.brandAccess.set(request, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async resolveBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
@@ -63,11 +95,7 @@ export class AdminAccessService {
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
||||
where: { id: access.subject },
|
||||
select: { platformTemplateRole: true },
|
||||
});
|
||||
if (user.platformTemplateRole !== "template_admin")
|
||||
if (access.platformTemplateRole !== "template_admin")
|
||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||
return { subject: access.subject };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminAccessService } from "../src/admin-access.service.js";
|
||||
import { signIdentity } from "../src/auth.js";
|
||||
|
||||
process.env.SESSION_SECRET = "admin-access-service-test-secret-1234567890";
|
||||
|
||||
type RequestFixture = {
|
||||
headers: { authorization: string };
|
||||
};
|
||||
|
||||
function requestFixture(subject = "admin-1", brandId = "brand-1"): RequestFixture {
|
||||
return {
|
||||
headers: {
|
||||
authorization: `Bearer ${signIdentity({ subject, brandId, role: "admin" })}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function accessFixture() {
|
||||
const calls = { adminUser: 0, membership: 0 };
|
||||
const prisma = {
|
||||
adminUser: {
|
||||
findUnique: async () => {
|
||||
calls.adminUser += 1;
|
||||
return {
|
||||
isEnabled: true,
|
||||
mustChangePassword: false,
|
||||
tokenVersion: 0,
|
||||
platformTemplateRole: "none",
|
||||
};
|
||||
},
|
||||
},
|
||||
brandMembership: {
|
||||
findUnique: async () => {
|
||||
calls.membership += 1;
|
||||
return { role: "owner", isEnabled: true };
|
||||
},
|
||||
},
|
||||
};
|
||||
return { calls, prisma };
|
||||
}
|
||||
|
||||
test("同一请求内 Guard 与 Controller 复用访问校验结果", async () => {
|
||||
const { calls, prisma } = accessFixture();
|
||||
const service = new AdminAccessService(prisma as never);
|
||||
const request = requestFixture();
|
||||
|
||||
const [guardResult, controllerResult] = await Promise.all([
|
||||
service.requireBrand(request as never),
|
||||
service.requireBrand(request as never),
|
||||
]);
|
||||
assert.deepEqual(guardResult, controllerResult);
|
||||
await service.requireRole(request as never, ["owner"]);
|
||||
await assert.rejects(
|
||||
service.requireTemplateAdmin(request as never),
|
||||
(error: unknown) => error instanceof ForbiddenException,
|
||||
);
|
||||
|
||||
assert.equal(calls.adminUser, 1);
|
||||
assert.equal(calls.membership, 1);
|
||||
});
|
||||
|
||||
test("不同请求之间不共享访问校验缓存", async () => {
|
||||
const { calls, prisma } = accessFixture();
|
||||
const service = new AdminAccessService(prisma as never);
|
||||
|
||||
await service.requireBrand(requestFixture("admin-1") as never);
|
||||
await service.requireBrand(requestFixture("admin-2") as never);
|
||||
|
||||
assert.equal(calls.adminUser, 2);
|
||||
assert.equal(calls.membership, 2);
|
||||
});
|
||||
Reference in new issue
Block a user