| 34 | @Controller('api-keys') |
| 35 | @UseGuards(AuthGuard, RolesGuard) |
| 36 | export class ApiKeysController { |
| 37 | constructor(private readonly apiKeysService: ApiKeysService) {} |
| 38 | |
| 39 | @Get() |
| 40 | @ApiOkResponse({ type: ApiKeyResponseDto, isArray: true }) |
| 41 | async list( |
| 42 | @CurrentAuth() auth: AuthContext, |
| 43 | @Query(new ZodValidationPipe(ListApiKeysQuerySchema)) query: ListApiKeysQueryDto, |
| 44 | ) { |
| 45 | const keys = await this.apiKeysService.list(auth, query); |
| 46 | return keys.map((key) => ApiKeyResponseDto.create(key)); |
| 47 | } |
| 48 | |
| 49 | @Post() |
| 50 | @Roles('ADMIN') |
| 51 | @ApiCreatedResponse({ type: CreateApiKeyResponseDto }) |
| 52 | async create( |
| 53 | @CurrentAuth() auth: AuthContext, |
| 54 | @Body(new ZodValidationPipe(CreateApiKeySchema)) dto: CreateApiKeyDto, |
| 55 | ) { |
| 56 | const { apiKey, plainKey } = await this.apiKeysService.create(auth, dto); |
| 57 | // Return the response DTO plus the plain key (one-time only) |
| 58 | return { |
| 59 | ...ApiKeyResponseDto.create(apiKey), |
| 60 | plainKey, |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | @Get(':id') |
| 65 | @ApiOkResponse({ type: ApiKeyResponseDto }) |
| 66 | async get(@CurrentAuth() auth: AuthContext, @Param('id') id: string) { |
| 67 | const apiKey = await this.apiKeysService.get(auth, id); |
| 68 | return ApiKeyResponseDto.create(apiKey); |
| 69 | } |
| 70 | |
| 71 | @Patch(':id') |
| 72 | @Roles('ADMIN') |
| 73 | @ApiOkResponse({ type: ApiKeyResponseDto }) |
| 74 | async update( |
| 75 | @CurrentAuth() auth: AuthContext, |
| 76 | @Param('id') id: string, |
| 77 | @Body(new ZodValidationPipe(UpdateApiKeySchema)) dto: UpdateApiKeyDto, |
| 78 | ) { |
| 79 | const apiKey = await this.apiKeysService.update(auth, id, dto); |
| 80 | return ApiKeyResponseDto.create(apiKey); |
| 81 | } |
| 82 | |
| 83 | @Post(':id/revoke') |
| 84 | @Roles('ADMIN') |
| 85 | @ApiOkResponse({ type: ApiKeyResponseDto }) |
| 86 | async revoke(@CurrentAuth() auth: AuthContext, @Param('id') id: string) { |
| 87 | const apiKey = await this.apiKeysService.update(auth, id, { isActive: false }); |
| 88 | return ApiKeyResponseDto.create(apiKey); |
| 89 | } |
| 90 | |
| 91 | @Delete(':id') |
| 92 | @Roles('ADMIN') |
| 93 | @ApiOkResponse({ type: DeleteApiKeyResponseDto }) |