返回 AiToEarn
api-key.service.ts
根目录 / project / aitoearn-backend / apps / aitoearn-server / src / core / api-key / api-key.service.ts
1 import { createHash } from 'node:crypto'
2 import { Injectable } from '@nestjs/common'
3 import { AppException, ResponseCode } from '@yikart/common'
4 import { ApiKeyRepository } from '@yikart/mongodb'
5 import { customAlphabet } from 'nanoid'
6 import { config } from '../../config'
7
8 const generateId = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 48)
9
10 @Injectable()
11 export class ApiKeyService {
12 constructor(
13 private readonly apiKeyRepository: ApiKeyRepository,
14 ) {}
15
16 async create(userId: string, name: string) {
17 const rawKey = `${config.apiKey.prefix}${generateId()}`
18 const keyHash = this.hashKey(rawKey)
19
20 const apiKey = await this.apiKeyRepository.create({
21 userId,
22 name,
23 keyHash,
24 })
25
26 return {
27 id: apiKey.id,
28 name: apiKey.name,
29 key: rawKey,
30 createdAt: apiKey.createdAt,
31 }
32 }
33
34 async listByUserId(userId: string) {
35 return await this.apiKeyRepository.listByUserId(userId)
36 }
37
38 async deleteByIdAndUserId(id: string, userId: string): Promise<void> {
39 await this.apiKeyRepository.deleteByIdAndUserId(id, userId)
40 }
41
42 async validateKey(rawKey: string) {
43 const keyHash = this.hashKey(rawKey)
44 const apiKey = await this.apiKeyRepository.getByKeyHash(keyHash)
45
46 if (!apiKey) {
47 throw new AppException(ResponseCode.ApiKeyInvalid)
48 }
49
50 await this.apiKeyRepository.updateLastUsedAt(apiKey.id)
51
52 return apiKey
53 }
54
55 private hashKey(rawKey: string): string {
56 return createHash('sha1').update(rawKey).digest('hex')
57 }
58 }
59
59 lines TYPESCRIPT