import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common"; import type { FastifyRequest } from "fastify"; 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>(); private readonly brandAccess = new WeakMap>(); constructor(private readonly prisma: PrismaService) {} requireToken(request: FastifyRequest): Promise { 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 { const token = readAdminToken(request); if (!token) throw new UnauthorizedException("缺少管理员登录态"); let identity; try { identity = readIdentity(token); } catch { throw new UnauthorizedException("管理员登录态无效或已过期"); } 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, platformTemplateRole: true, }, }); if (!user || identity.tokenVersion !== user.tokenVersion) throw new UnauthorizedException("管理员登录态已失效,请重新登录"); if (!user.isEnabled) throw new ForbiddenException("管理员账号已停用"); return { subject: identity.subject, brandId: identity.brandId, mustChangePassword: user.mustChangePassword, tokenVersion: user.tokenVersion, platformTemplateRole: user.platformTemplateRole, }; } requireBrand(request: FastifyRequest): Promise { 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 { const access = await this.requireToken(request); if (access.mustChangePassword) throw new ForbiddenException("请先完成初始密码修改后再访问管理后台"); const membership = await this.prisma.brandMembership.findUnique({ where: { adminUserId_brandId: { adminUserId: access.subject, brandId: access.brandId } }, }); if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限"); return { subject: access.subject, brandId: access.brandId, role: membership.role }; } async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise { const access = await this.requireBrand(request); if (!allowedRoles.includes(access.role)) { throw new ForbiddenException("当前账号没有系统设置权限"); } return true; } async requireTemplateAdmin(request: FastifyRequest): Promise<{ subject: string }> { const access = await this.requireToken(request); if (access.mustChangePassword) throw new ForbiddenException("请先完成初始密码修改后再访问管理后台"); if (access.platformTemplateRole !== "template_admin") throw new ForbiddenException("当前账号没有模板管理权限"); return { subject: access.subject }; } }