37 lines
1.5 KiB
TypeScript
37 lines
1.5 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 };
|
|
}
|
|
|
|
async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise<boolean> {
|
|
const access = await this.requireBrand(request);
|
|
if (!allowedRoles.includes(access.role)) {
|
|
throw new ForbiddenException("当前账号没有系统设置权限");
|
|
}
|
|
return true;
|
|
}
|
|
}
|