import { CanActivate, ExecutionContext, ForbiddenException, Injectable, } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import type { PartnerPermissionKey } from '@dukang/shared-types'; import { PARTNER_PERMISSIONS_KEY } from '../decorators/partner-permission.decorator'; import { PrismaService } from '../prisma/prisma.module'; import { AuthUser, JwtAuthGuard } from './jwt-auth.guard'; @Injectable() export class PartnerPermissionGuard implements CanActivate { constructor( private readonly jwtAuthGuard: JwtAuthGuard, private readonly prisma: PrismaService, private readonly reflector: Reflector, ) {} async canActivate(context: ExecutionContext): Promise { await this.jwtAuthGuard.canActivate(context); const req = context.switchToHttp().getRequest(); const user = req.user as AuthUser; if (user.actorType !== 'PARTNER') { throw new ForbiddenException('仅合伙人可操作'); } const account = await this.prisma.partnerAccount.findUniqueOrThrow({ where: { id: user.actorId }, }); if (account.isPrimary === 1) return true; const required = this.reflector.getAllAndOverride( PARTNER_PERMISSIONS_KEY, [context.getHandler(), context.getClass()], ); if (!required?.length) return true; const perms = Array.isArray(account.permissions) ? (account.permissions as string[]) : []; if (required.some((p) => perms.includes(p))) return true; throw new ForbiddenException('当前子账号无此操作权限'); } }