From 9b8fa3ebb0e24727442ebbfefd6596a471894e85 Mon Sep 17 00:00:00 2001 From: isra el Date: Fri, 29 Nov 2024 09:18:47 +0300 Subject: [PATCH] feat(api): enable renaming api keys --- api/src/auth/auth.controller.ts | 11 +++++++++++ api/src/auth/auth.service.ts | 9 +++++++++ api/src/auth/guards/can-modify-api-key.guard.ts | 8 ++++++++ api/src/auth/schemas/api-key.schema.ts | 3 +++ 4 files changed, 31 insertions(+) diff --git a/api/src/auth/auth.controller.ts b/api/src/auth/auth.controller.ts index 6239f86..3997e06 100644 --- a/api/src/auth/auth.controller.ts +++ b/api/src/auth/auth.controller.ts @@ -6,6 +6,7 @@ import { HttpCode, HttpStatus, Param, + Patch, Post, Request, UseGuards, @@ -95,6 +96,16 @@ export class AuthController { return { message: 'API Key Revoked' } } + @UseGuards(AuthGuard, CanModifyApiKey) + @ApiOperation({ summary: 'Rename Api Key' }) + @ApiBearerAuth() + @HttpCode(HttpStatus.OK) + @Patch('/api-keys/:id/rename') + async renameApiKey(@Param() params, @Body() input: { name: string }) { + await this.authService.renameApiKey(params.id, input.name) + return { message: 'API Key Renamed' } + } + @ApiOperation({ summary: 'Request Password Reset' }) @HttpCode(HttpStatus.OK) @Post('/request-password-reset') diff --git a/api/src/auth/auth.service.ts b/api/src/auth/auth.service.ts index 907a207..6a4756b 100644 --- a/api/src/auth/auth.service.ts +++ b/api/src/auth/auth.service.ts @@ -253,6 +253,15 @@ export class AuthService { await apiKey.save() } + async renameApiKey(apiKeyId: string, name: string) { + const apiKey = await this.apiKeyModel.findById(apiKeyId) + if (!apiKey) { + throw new HttpException({ error: 'Api key not found' }, HttpStatus.NOT_FOUND) + } + apiKey.name = name + await apiKey.save() + } + async trackAccessLog({ request }) { const { apiKey, user, method, url, ip, headers } = request const userAgent = headers['user-agent'] diff --git a/api/src/auth/guards/can-modify-api-key.guard.ts b/api/src/auth/guards/can-modify-api-key.guard.ts index bef09ca..02a29c5 100644 --- a/api/src/auth/guards/can-modify-api-key.guard.ts +++ b/api/src/auth/guards/can-modify-api-key.guard.ts @@ -25,6 +25,14 @@ export class CanModifyApiKey implements CanActivate { } const apiKey = await this.authService.findApiKeyById(apiKeyId) + + if (apiKey?.revokedAt) { + throw new HttpException( + { error: 'Unauthorized' }, + HttpStatus.UNAUTHORIZED, + ) + } + if ( !!userId && (apiKey?.user == userId.toString() || diff --git a/api/src/auth/schemas/api-key.schema.ts b/api/src/auth/schemas/api-key.schema.ts index aa2a35a..99a50ec 100644 --- a/api/src/auth/schemas/api-key.schema.ts +++ b/api/src/auth/schemas/api-key.schema.ts @@ -11,6 +11,9 @@ export class ApiKey { @Prop({ type: String }) apiKey: string // save first few chars only [ abc123****** ] + @Prop({ type: String, default: 'API Key' }) + name: string + @Prop({ type: String }) hashedApiKey: string