All files / src/platform/licensing licensing.guard.ts

0% Statements 0/20
0% Branches 0/16
0% Functions 0/2
0% Lines 0/18

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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                                                                               
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ModuleLicensingService } from './licensing.service';
import { MODULE_KEY } from './licensing.decorator';
 
@Injectable()
export class ModuleLicenseGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly licensingService: ModuleLicensingService,
  ) {}
 
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredModule = this.reflector.getAllAndOverride<string>(
      MODULE_KEY,
      [context.getHandler(), context.getClass()],
    );
 
    if (!requiredModule) {
      return true;
    }
 
    const request = context.switchToHttp().getRequest();
    const tenantId = request.user?.tenantId || request.headers['x-tenant-id'];
 
    if (!tenantId) {
      throw new ForbiddenException('Tenant context missing');
    }
 
    const isLicensed = await this.licensingService.isModuleLicensed(
      tenantId,
      requiredModule,
    );
    if (!isLicensed) {
      throw new ForbiddenException(
        `Module '${requiredModule}' is not licensed or active for this tenant.`,
      );
    }
 
    return true;
  }
}