feat: 增加多品牌切换并继续拆分控制器
This commit is contained in:
1 parent
f4a93bba23
commit
045472035b
7 files changed
+126
-3
No files matched your search
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity, signIdentity } from "../../auth.js";
|
||||
|
||||
@Controller("admin/brands")
|
||||
export class TenantController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.adminIdentity(request);
|
||||
return this.prisma.brandMembership.findMany({
|
||||
where: { adminUserId: identity.subject, isEnabled: true },
|
||||
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
@Post(":brandId/switch")
|
||||
async switchBrand(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("brandId") brandId: string,
|
||||
): Promise<{ token: string; brand: unknown }> {
|
||||
const identity = this.adminIdentity(request);
|
||||
const membership = await this.prisma.brandMembership.findFirst({
|
||||
where: { adminUserId: identity.subject, brandId, isEnabled: true },
|
||||
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||
});
|
||||
if (!membership) throw new ForbiddenException("没有该品牌的管理权限");
|
||||
return {
|
||||
token: signIdentity({ subject: identity.subject, brandId, role: "admin" }),
|
||||
brand: membership.brand,
|
||||
};
|
||||
}
|
||||
|
||||
private adminIdentity(request: FastifyRequest) {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
return identity;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user