| 1 | import type { TokenPayload } from '@yikart/aitoearn-auth' |
| 2 | import { createHash } from 'node:crypto' |
| 3 | import { Module, UnauthorizedException } from '@nestjs/common' |
| 4 | import { ScheduleModule } from '@nestjs/schedule' |
| 5 | import { AitoearnAuthModule } from '@yikart/aitoearn-auth' |
| 6 | import { AitoearnQueueModule } from '@yikart/aitoearn-queue' |
| 7 | import { AssetsModule } from '@yikart/assets' |
| 8 | import { ConfigEditorModule } from '@yikart/config-editor' |
| 9 | import { ApiKeyRepository, MongodbModule, UserRepository, UserStatus } from '@yikart/mongodb' |
| 10 | import { RedlockModule } from '@yikart/redlock' |
| 11 | import { AppConfig, config } from './config' |
| 12 | import { AgentModule } from './core/agent/agent.module' |
| 13 | import { AiAvailabilityModule } from './core/ai-availability' |
| 14 | import { AiModule } from './core/ai/ai.module' |
| 15 | import { DraftGenerationModule } from './core/draft-generation' |
| 16 | import { InternalModule } from './core/internal' |
| 17 | |
| 18 | @Module({ |
| 19 | imports: [ |
| 20 | AiAvailabilityModule.forRoot(), |
| 21 | ScheduleModule.forRoot(), |
| 22 | ConfigEditorModule.forRoot({ |
| 23 | schema: AppConfig, |
| 24 | config, |
| 25 | routePrefix: 'ai/config', |
| 26 | }), |
| 27 | MongodbModule.forRoot(config.mongodb), |
| 28 | AitoearnQueueModule.forRoot({ |
| 29 | redis: config.redis, |
| 30 | prefix: '{bull}', |
| 31 | }), |
| 32 | RedlockModule.forRoot(config.redlock), |
| 33 | AitoearnAuthModule.forRootAsync({ |
| 34 | inject: [UserRepository, ApiKeyRepository], |
| 35 | useFactory: (userRepository: UserRepository, apiKeyRepository: ApiKeyRepository) => { |
| 36 | const getOpenUser = async (userId: string) => { |
| 37 | const user = await userRepository.getById(userId) |
| 38 | if (!user || user.isDelete || user.status !== UserStatus.OPEN) { |
| 39 | throw new UnauthorizedException() |
| 40 | } |
| 41 | return user |
| 42 | } |
| 43 | return { |
| 44 | ...config.auth, |
| 45 | getTokenInfo: (payload: TokenPayload) => getOpenUser(payload.id), |
| 46 | getTokenInfoByApiKey: async (apiKey: string) => { |
| 47 | const keyHash = createHash('sha1').update(apiKey).digest('hex') |
| 48 | const record = await apiKeyRepository.getByKeyHash(keyHash) |
| 49 | if (!record) { |
| 50 | throw new UnauthorizedException() |
| 51 | } |
| 52 | await apiKeyRepository.updateLastUsedAt(record.id) |
| 53 | return getOpenUser(record.userId) |
| 54 | }, |
| 55 | } |
| 56 | }, |
| 57 | }), |
| 58 | AssetsModule.forRoot(config.assets), |
| 59 | AiModule, |
| 60 | AgentModule, |
| 61 | InternalModule, |
| 62 | DraftGenerationModule, |
| 63 | ], |
| 64 | controllers: [], |
| 65 | providers: [], |
| 66 | }) |
| 67 | export class AppModule { } |
| 68 |