-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathgenerate-api-key.usecase.ts
More file actions
38 lines (32 loc) · 1.19 KB
/
generate-api-key.usecase.ts
File metadata and controls
38 lines (32 loc) · 1.19 KB
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
import * as crypto from 'crypto';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { EnvironmentRepository } from '@impler/dal';
import { VARIABLES } from '@shared/constants';
const API_KEY_GENERATION_MAX_RETRIES = 10;
@Injectable()
export class GenerateUniqueApiKey {
constructor(private environmentRepository: EnvironmentRepository) {}
async execute(): Promise<string> {
let apiKey = '';
let count = 0;
let isApiKeyUsed = true;
while (isApiKeyUsed) {
apiKey = this.generateApiKey();
const environment = await this.environmentRepository.findByApiKey(apiKey);
isApiKeyUsed = environment ? true : false;
count += VARIABLES.ONE;
if (count === API_KEY_GENERATION_MAX_RETRIES) {
const errorMessage = 'Clashing of the API key generation';
throw new InternalServerErrorException(new Error(errorMessage), errorMessage);
}
}
return apiKey as string;
}
/**
* Generates a cryptographically secure API key with 256-bit entropy.
* Replaces the deprecated `hat` library with Node.js native crypto.
*/
private generateApiKey(): string {
return crypto.randomBytes(32).toString('hex');
}
}