forked from humanprotocol/human-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapikey.repository.ts
48 lines (39 loc) · 1.39 KB
/
apikey.repository.ts
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 { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiKeyEntity } from './apikey.entity';
@Injectable()
export class ApiKeyRepository {
private readonly logger = new Logger(ApiKeyRepository.name);
constructor(
@InjectRepository(ApiKeyEntity)
private readonly apiKeyRepository: Repository<ApiKeyEntity>,
) {}
async createOrUpdateAPIKey(userId: number, hashedAPIKey: string, salt: string): Promise<ApiKeyEntity> {
let apiKeyEntity = await this.findAPIKeyByUserId(userId);
if (!apiKeyEntity) {
apiKeyEntity = this.apiKeyRepository.create({ user: { id: userId } });
}
apiKeyEntity.hashedAPIKey = hashedAPIKey;
apiKeyEntity.salt = salt;
return this.apiKeyRepository.save(apiKeyEntity);
}
public async findAPIKeyByUserId(userId: number): Promise<ApiKeyEntity | null> {
return this.apiKeyRepository.findOne({
where: { user: { id: userId } },
relations: ['user'],
});
}
async findAPIKeyByHash(hashedAPIKey: string): Promise<ApiKeyEntity | null> {
return this.apiKeyRepository.findOne({
where: { hashedAPIKey },
relations: ['user'],
});
}
async findAPIKeyById(apiKeyId: number): Promise<ApiKeyEntity | null> {
return this.apiKeyRepository.findOne({
where: { id: apiKeyId },
relations: ['user'],
});
}
}