From efb0b9f495ba8d56b594f55c871d07f1e0a890d0 Mon Sep 17 00:00:00 2001 From: sabaimran Date: Mon, 16 Dec 2024 16:47:54 -0800 Subject: [PATCH] Gracefully handle error when user login code is expired --- .../web/app/components/loginPrompt/loginPrompt.tsx | 2 ++ src/khoj/database/adapters/__init__.py | 8 ++++---- src/khoj/routers/auth.py | 7 ++++++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/interface/web/app/components/loginPrompt/loginPrompt.tsx b/src/interface/web/app/components/loginPrompt/loginPrompt.tsx index 6af02f9b..3d1a3752 100644 --- a/src/interface/web/app/components/loginPrompt/loginPrompt.tsx +++ b/src/interface/web/app/components/loginPrompt/loginPrompt.tsx @@ -261,6 +261,8 @@ function EmailSignInContext({ } else if (res.status === 429) { setOTPError("Too many failed attempts. Please try again tomorrow."); setNumFailures(ALLOWED_OTP_ATTEMPTS); + } else if (res.status === 403) { + setOTPError("OTP expired. Please request a new one."); } else { throw new Error("Failed to verify OTP"); } diff --git a/src/khoj/database/adapters/__init__.py b/src/khoj/database/adapters/__init__.py index 28f1d2d9..80f99fb5 100644 --- a/src/khoj/database/adapters/__init__.py +++ b/src/khoj/database/adapters/__init__.py @@ -269,19 +269,19 @@ async def astart_trial_subscription(user: KhojUser) -> Subscription: return subscription -async def aget_user_validated_by_email_verification_code(code: str, email: str) -> KhojUser: +async def aget_user_validated_by_email_verification_code(code: str, email: str) -> tuple[Optional[KhojUser], bool]: user = await KhojUser.objects.filter(email_verification_code=code, email=email).afirst() if not user: - return None + return None, False if user.email_verification_code_expiry < datetime.now(tz=timezone.utc): - return None + return None, True user.email_verification_code = None user.verified_email = True await user.asave() - return user + return user, False async def create_user_by_google_token(token: dict) -> KhojUser: diff --git a/src/khoj/routers/auth.py b/src/khoj/routers/auth.py index f1c2f66c..432eecef 100644 --- a/src/khoj/routers/auth.py +++ b/src/khoj/routers/auth.py @@ -111,8 +111,13 @@ async def sign_in_with_magic_link( EmailVerificationApiRateLimiter(requests=10, window=60 * 60 * 24, slug="magic_link_verification") ), ): - user = await aget_user_validated_by_email_verification_code(code, email) + user, code_is_expired = await aget_user_validated_by_email_verification_code(code, email) + if user: + if code_is_expired: + request.session["user"] = {} + return Response(status_code=403) + id_info = { "email": user.email, }