All files / libs/tenants/companies/core/src/lib/companyApiKey companyApiKey.service.ts

90.9% Statements 100/110
63.63% Branches 7/11
100% Functions 4/4
90.9% Lines 100/110

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 1111x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x           3x 1x  
import { ConflictException, HttpException, HttpStatus, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { pick } from 'lodash-es';
import { IsNull, Repository } from 'typeorm';
 
import { CompanyApiKey, type Company } from '@amalia/core/models';
import { generateRandomString } from '@amalia/ext/string';
import { toError } from '@amalia/ext/typescript';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
 
import { type CompanyApiKeyDto } from './companyApiKey.dto';
import { ApiKeyCreatedEvent } from './events/ApiKeyCreatedEvent';
import { ApiKeyDeletedEvent } from './events/ApiKeyDeletedEvent';
 
@Injectable()
export class CompanyApiKeyService {
  private readonly logger = new Logger(CompanyApiKeyService.name);
 
  public constructor(
    private readonly eventBus: EventBus,
 
    @InjectRepository(CompanyApiKey)
    private readonly companyApiKeyRepository: Repository<CompanyApiKey>,
  ) {}
 
  public list(companyId: string) {
    return this.companyApiKeyRepository.find({
      where: {
        companyId,
        deactivatedAt: IsNull(),
      },
      select: ['createdAt', 'creatorId', 'description', 'id', 'token'],
    });
  }
 
  public async create(company: Company, authenticatedContext: AuthenticatedContext, createTokenDto: CompanyApiKeyDto) {
    const token = generateRandomString(64);
 
    try {
      const createdToken = await this.companyApiKeyRepository.save({
        companyId: company.id,
        description: createTokenDto.description,
        creatorId: authenticatedContext.user.id,
        token,
      });
 
      await this.eventBus.publish(
        new ApiKeyCreatedEvent({
          authenticatedContext,
          object: RecordObject.API_SETTINGS,
          type: RecordType.CREATE,
          values: {
            target: {
              id: createdToken.id,
              name: createdToken.description,
            },
          },
        }),
      );
 
      return createdToken;
    } catch (err) {
      const error = toError(err);
      this.logger.error({ message: 'Error on create Api Key', error, company: pick(company, ['id', 'name']) });

      throw new HttpException('Error during Api Key creation, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
 
  public async delete(company: Company, authenticatedContext: AuthenticatedContext, apiKeyId: string) {
    const { id: companyId } = company;
    const apiKey = await this.companyApiKeyRepository.findOneBy({
      companyId,
      id: apiKeyId,
    });
 
    if (!apiKey) {
      throw new NotFoundException('Api key not found');
    }
 
    if (apiKey.deactivatedAt) {
      throw new ConflictException('Api key already deactivated');
    }
 
    try {
      await this.companyApiKeyRepository.update({ companyId, id: apiKeyId }, { deactivatedAt: new Date() });
 
      await this.eventBus.publish(
        new ApiKeyDeletedEvent({
          authenticatedContext,
          object: RecordObject.API_SETTINGS,
          type: RecordType.DELETE,
          values: {
            target: {
              id: apiKey.id,
              name: apiKey.description,
            },
          },
        }),
      );
    } catch (err) {
      const error = toError(err);
      this.logger.error({ message: 'Error on delete Api Key', error, company: pick(company, ['id', 'name']) });

      throw new HttpException('Error during Api Key deletion, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}