Files
persionalBrand/apps/api/src/admin-access.service.ts
T

29 lines
1.2 KiB
TypeScript

import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "./prisma.service.js";
import { readIdentity } from "./auth.js";
@Injectable()
export class AdminAccessService {
constructor(private readonly prisma: PrismaService) {}
async requireBrand(
request: FastifyRequest,
): Promise<{ subject: string; brandId: string; role: string }> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const membership = await this.prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
});
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
return { subject: identity.subject, brandId: identity.brandId, role: membership.role };
}
}