import { Controller, Body, ForbiddenException, Get, Param, Patch, Post, Req, UnauthorizedException, } from "@nestjs/common"; import type { FastifyRequest } from "fastify"; import { readIdentity } from "../../auth.js"; import { AdminAccessService } from "../../admin-access.service.js"; import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js"; import { TenantService } from "./tenant.service.js"; @Controller("admin/brands") export class TenantController { constructor( private readonly access: AdminAccessService, private readonly tenants: TenantService, ) {} @Get("members") async listMembers(@Req() request: FastifyRequest): Promise { await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); const current = this.adminIdentity(request); return this.tenants.listMembers(current.brandId); } @Post("members") async createMember( @Req() request: FastifyRequest, @Body() body: CreateBrandMemberDto, ): Promise { await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); const actor = this.adminIdentity(request); return this.tenants.createMember(actor.brandId, body); } @Patch("members/:id") async updateMember( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateBrandMemberDto, ): Promise { await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); const actor = this.adminIdentity(request); return this.tenants.updateMember(actor.brandId, actor.subject, id, body); } @Get() async list(@Req() request: FastifyRequest): Promise { const identity = this.adminIdentity(request); return this.tenants.listMemberships(identity.subject); } @Post(":brandId/switch") async switchBrand( @Req() request: FastifyRequest, @Param("brandId") brandId: string, ): Promise<{ token: string; role: string; brand: unknown }> { const identity = this.adminIdentity(request); return this.tenants.switchBrand(identity, brandId); } 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; } }