From 388d7151f765ffb235fff71b1e6551337ea9a83e Mon Sep 17 00:00:00 2001 From: vmkhitaryanscn <120190555+vmkhitaryanscn@users.noreply.github.com> Date: Thu, 7 Nov 2024 19:19:02 +0400 Subject: [PATCH] Feat: delete passkey by id (#26) --- src/api/passkeys/controller.ts | 41 ++++++++++++++++++- .../UserCredential/UserCredential.crud.ts | 14 +++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/api/passkeys/controller.ts b/src/api/passkeys/controller.ts index 5d53df2..76d951d 100644 --- a/src/api/passkeys/controller.ts +++ b/src/api/passkeys/controller.ts @@ -19,7 +19,11 @@ import { LoginBodySchema } from '../auth/validation.schema'; import { Env, ONE_MINUTE, ONE_MONTH, rpID, rpName } from '~/core/constants'; import { origin } from '~/core/constants'; import { ErrorMessages } from '~/core/dictionary/error.messages'; -import { BadRequestError, UnauthorizedError } from '~/core/errors'; +import { + BadRequestError, + NotFoundError, + UnauthorizedError, +} from '~/core/errors'; import { logger } from '~/core/logger'; import { authMiddleware } from '~/core/middleware/auth'; import { jwtService, modelToPlain } from '~/core/utils'; @@ -379,4 +383,39 @@ route.get( res.status(200).json(userPassKeysResult); }, ); + +route.delete( + '/:passkeyId', + authMiddleware, + async (req: Request, res: Response, next: NextFunction) => { + const user = req.user; + + if (!isAuthenticated(user)) { + return next(new UnauthorizedError(ErrorMessages.unauthorized)); + } + + const passkeyId = req.params.passkeyId; + + try { + const deleteResult = await UserCredentialCrudService.deleteOneByParams({ + id: passkeyId, + userId: user.id, + }); + + if (deleteResult === 0) { + throw new NotFoundError('Passkey not found'); + } + + return res.status(200).json({ + type: 'PASSKEY_DELETED', + statusCode: 200, + message: 'Passkey deleted successfully', + isSuccess: true, + }); + } catch (error: unknown) { + return next(error); + } + }, +); + export default route; diff --git a/src/shared/UserCredential/UserCredential.crud.ts b/src/shared/UserCredential/UserCredential.crud.ts index 6cc04e7..2626f35 100644 --- a/src/shared/UserCredential/UserCredential.crud.ts +++ b/src/shared/UserCredential/UserCredential.crud.ts @@ -16,6 +16,11 @@ interface UpdateCredentialCounterPayload { counter: number; } +export interface DeleteByParams { + id: string; + userId: string; +} + export class UserCredentialCrudService { static async getCredentialByUserId(userId: string) { return UserCredential.findAll({ where: { userId } }); @@ -42,4 +47,13 @@ export class UserCredentialCrudService { { where: { credId: payload.credId } }, ); } + + static deleteOneByParams(params: DeleteByParams) { + return UserCredential.destroy({ + where: { + id: params.id, + userId: params.userId, + }, + }); + } }