Browse Source

feat(api): enable renaming api keys

legacy-ui
isra el 1 year ago
parent
commit
9b8fa3ebb0
  1. 11
      api/src/auth/auth.controller.ts
  2. 9
      api/src/auth/auth.service.ts
  3. 8
      api/src/auth/guards/can-modify-api-key.guard.ts
  4. 3
      api/src/auth/schemas/api-key.schema.ts

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

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

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

3
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

Loading…
Cancel
Save