feat(api): enable renaming api keys

This commit is contained in:
isra el
2024-11-29 09:18:47 +03:00
parent 44636fe1b5
commit 9b8fa3ebb0
4 changed files with 31 additions and 0 deletions

View File

@@ -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')

View File

@@ -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']

View File

@@ -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() ||

View File

@@ -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