All files / src/modules/leads lead.guard.ts

31.57% Statements 6/19
21.42% Branches 3/14
50% Functions 1/2
30.76% Lines 4/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2111x 11x     11x 22x                              
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
 
@Injectable()
export class LeadOwnerGuard implements CanActivate {
  constructor(private readonly prisma: PrismaService) {}
 
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const user = req.user as { id: number; role: string; agencyId?: number };
    const id = parseInt(req.params.id, 10);
    Iif (!id || !user) return false;
    // @ts-ignore
    const lead = await this.prisma.client.lead.findUnique({ where: { id } });
    Iif (!lead) return false;
    Iif (lead.agentId === user.id) return true;
    Iif (user.role === 'AGENCY_OWNER' && lead.agencyId && user.agencyId && lead.agencyId === user.agencyId) return true;
    return false;
  }
}