Skip to content

Conversation

@AkshitGarg054
Copy link

@AkshitGarg054 AkshitGarg054 commented Jan 10, 2026

Closes # 223

📝 Description

This PR fixes an issue where users get stuck in a “Verification Pending” state when running /verify_github, even after the verification token has expired.
The fix ensures :

  • Expired verification tokens are cleaned from the database immediately
  • The Discord command correctly checks token expiry before blocking re-verification

No existing verification logic or flow has been changed — only missing safety checks were added.

🔧 Changes Made

CHANGE 1 : Force DB cleanup before creating a verification session

File : backend/app/services/auth/verification.py : Before creating a new verification session, we now explicitly clean expired tokens from Supabase using await cleanup_expired_tokens(), in create_verification_session() function.

CHANGE 2 : Make /verify_github expiry-aware

File : backend/integrations/discord/cogs.py : Token expiry is checked before showing “Verification Pending”

✅ Checklist

  • I have read the contributing guidelines.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added necessary documentation (if applicable).
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

  • Bug Fixes
    • Verification token expiration handling improved to avoid unnecessary re-verification prompts.
    • Expired tokens are now proactively cleaned up before new sessions are created.
    • All timestamps and expiry comparisons are now timezone-aware (UTC), fixing inconsistent expiry and time-remaining calculations.
    • Discord verification flow refined to better respect token state and existing pending verifications.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 10, 2026

📝 Walkthrough

Walkthrough

Auth verification now uses timezone-aware UTC datetimes and calls token cleanup before creating sessions; the Discord cog checks existing verification token expirations (normalizing to UTC) and reuses pending messages if tokens remain valid, otherwise it creates new verification sessions.

Changes

Cohort / File(s) Summary
Auth timezone & cleanup
backend/app/services/auth/verification.py
Replaced naive datetimes with UTC-aware datetime.now(timezone.utc) across session creation, verification, cleanup, and info retrieval. Added explicit cleanup_expired_tokens() call at the start of create_verification_session(). Updated expiry calculations, comparisons, timestamp fields, and time_remaining computations to use UTC-aware datetimes/ISO formatting.
Discord token expiry handling
backend/integrations/discord/cogs.py
Added datetime and timezone imports. In verify_github(), compute and normalize verification_token_expires_at to UTC (supporting string or datetime), determine expiry status, and if token is still valid retain the existing ephemeral "verification pending" message; if expired or absent, proceed to create a new verification session.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant Discord as Discord Cog
participant Auth as Auth Service
participant DB as Database

Note over Discord,Auth: New verification request flow
Discord->>Auth: request create_verification_session(user)
Auth->>DB: cleanup_expired_tokens()
DB-->>Auth: purge result
Auth->>DB: create verification session (expires_at = now UTC + N minutes)
DB-->>Auth: session record (with expires_at)
Auth-->>Discord: session details (token, expires_at)
Discord-->>User: ephemeral "verification pending" message

mermaid
sequenceDiagram
participant Discord as Discord Cog
participant Auth as Auth Service
participant DB as Database

Note over Discord,Auth: Reuse existing token flow (new logic)
Discord->>DB: fetch existing verification_token_expires_at(user)
DB-->>Discord: expires_at (string|datetime)
Discord->>Discord: normalize expires_at to UTC, compare to now UTC
alt token not expired
    Discord->>User: keep existing ephemeral "verification pending" message
else token expired or missing
    Discord->>Auth: request create_verification_session(user)
    Auth->>DB: cleanup_expired_tokens()
    Auth->>DB: create new session
    DB-->>Auth: session record
    Auth-->>Discord: session details
    Discord-->>User: new ephemeral message

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through clocks both old and new,

Cleaned the tokens, set them true,
Discord peeks if time's run dry,
Reuses notes or spawns one nigh,
Tiny hops, UTC in view ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: fixing an issue where GitHub verification gets stuck in a pending state when tokens expire.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 276366d and b088977.

📒 Files selected for processing (1)
  • backend/app/services/auth/verification.py
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-28T14:44:34.399Z
Learnt from: smokeyScraper
Repo: AOSSIE-Org/Devr.AI PR: 85
File: backend/app/services/auth/management.py:83-83
Timestamp: 2025-06-28T14:44:34.399Z
Learning: In the backend/app/services/auth/management.py file, the team prefers to use datetime.now() (local timezone/IST) during development and testing for easier debugging, with plans to change to UTC timezone-aware datetime (datetime.now(timezone.utc)) during deployment.

Applied to files:

  • backend/app/services/auth/verification.py
🧬 Code graph analysis (1)
backend/app/services/auth/verification.py (2)
backend/integrations/discord/cogs.py (1)
  • cleanup_expired_tokens (39-46)
frontend/src/lib/supabaseClient.ts (1)
  • supabase (12-12)
🔇 Additional comments (5)
backend/app/services/auth/verification.py (5)

2-2: LGTM!

The addition of timezone import is correct for enabling UTC-aware datetime operations throughout the module.


15-31: LGTM!

The UTC-aware timestamp comparison is correct and consistent with how expiry_time is set in create_verification_session.


33-62: Core fix implemented correctly.

The addition of await cleanup_expired_tokens() at line 39 before creating a new session ensures that expired verification tokens are cleared from the database, allowing users to re-initiate verification. This directly addresses the "stuck in pending state" issue described in the PR objectives.


138-155: LGTM!

The cleanup function correctly uses UTC-aware timestamps for both the expiry comparison and the updated_at field update, maintaining consistency.


157-177: LGTM!

UTC-aware timestamps are used consistently for expiry checks and time remaining calculations, which correctly compares against the UTC-aware expiry_time stored in the session.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @backend/integrations/discord/cogs.py:
- Around line 133-162: Update the code that sets verification_token_expires_at
to use an aware UTC timestamp: replace datetime.now() with
datetime.now(timezone.utc) when computing the expiry (the assignment in the
verification token creation code where verification_token_expires_at is set).
Keep storing the ISO string as-is so cogs.py can parse it; no changes needed to
the expiry check in the Discord cog.
🧹 Nitpick comments (1)
backend/app/services/auth/verification.py (1)

39-39: Consider performance impact of cleanup on every verification creation.

Calling cleanup_expired_tokens() before every verification session creation ensures immediate removal of expired tokens (fixing the stuck pending issue), but it executes a database query on each /verify_github invocation. Since a periodic cleanup task already runs every 5 minutes (in discord/cogs.py), this could be redundant in most cases.

The current approach prioritizes correctness over performance, which may be acceptable depending on verification request volume. However, if you experience high traffic, consider:

  • Adding a simple in-memory timestamp check to skip cleanup if it ran recently (e.g., within last 30 seconds)
  • Relying solely on the periodic task and accepting a small window where expired tokens exist
Details ♻️ Optional: Add rate-limiting for cleanup calls
+_last_cleanup_time = None
+CLEANUP_COOLDOWN_SECONDS = 30
+
 async def create_verification_session(discord_id: str) -> Optional[str]:
     """
     Create a verification session with expiry and return session ID.
     """
     supabase = get_supabase_client()
 
+    global _last_cleanup_time
+    now = datetime.now()
+    if _last_cleanup_time is None or (now - _last_cleanup_time).total_seconds() > CLEANUP_COOLDOWN_SECONDS:
+        await cleanup_expired_tokens()
+        _last_cleanup_time = now
-    await cleanup_expired_tokens()
     _cleanup_expired_sessions()
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa66519 and 276366d.

📒 Files selected for processing (2)
  • backend/app/services/auth/verification.py
  • backend/integrations/discord/cogs.py
🧰 Additional context used
🧬 Code graph analysis (1)
backend/app/services/auth/verification.py (1)
backend/integrations/discord/cogs.py (1)
  • cleanup_expired_tokens (39-46)
🔇 Additional comments (1)
backend/integrations/discord/cogs.py (1)

6-6: LGTM: Necessary imports for timezone-aware datetime handling.

The datetime and timezone imports are correctly added to support the expiry-aware verification logic below.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/app/services/auth/verification.py (1)

114-123: Inconsistent timezone usage: updated_at is missing timezone.utc.

Line 122 uses datetime.now().isoformat() while line 119 uses datetime.now(timezone.utc).isoformat(). This inconsistency within the same update_data dict will cause verified_at to be stored as UTC-aware but updated_at as local/naive time, leading to potential timestamp comparison issues in the database.

🐛 Proposed fix
         update_data = {
             "github_id": github_id,
             "github_username": github_username,
             "email": user_to_verify.get('email') or email,
             "is_verified": True,
             "verified_at": datetime.now(timezone.utc).isoformat(),
             "verification_token": None,
             "verification_token_expires_at": None,
-            "updated_at": datetime.now().isoformat()
+            "updated_at": datetime.now(timezone.utc).isoformat()
         }
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 276366d and b088977.

📒 Files selected for processing (1)
  • backend/app/services/auth/verification.py
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-28T14:44:34.399Z
Learnt from: smokeyScraper
Repo: AOSSIE-Org/Devr.AI PR: 85
File: backend/app/services/auth/management.py:83-83
Timestamp: 2025-06-28T14:44:34.399Z
Learning: In the backend/app/services/auth/management.py file, the team prefers to use datetime.now() (local timezone/IST) during development and testing for easier debugging, with plans to change to UTC timezone-aware datetime (datetime.now(timezone.utc)) during deployment.

Applied to files:

  • backend/app/services/auth/verification.py
🧬 Code graph analysis (1)
backend/app/services/auth/verification.py (2)
backend/integrations/discord/cogs.py (1)
  • cleanup_expired_tokens (39-46)
frontend/src/lib/supabaseClient.ts (1)
  • supabase (12-12)
🔇 Additional comments (5)
backend/app/services/auth/verification.py (5)

2-2: LGTM!

The addition of timezone import is correct for enabling UTC-aware datetime operations throughout the module.


15-31: LGTM!

The UTC-aware timestamp comparison is correct and consistent with how expiry_time is set in create_verification_session.


33-62: Core fix implemented correctly.

The addition of await cleanup_expired_tokens() at line 39 before creating a new session ensures that expired verification tokens are cleared from the database, allowing users to re-initiate verification. This directly addresses the "stuck in pending state" issue described in the PR objectives.


138-155: LGTM!

The cleanup function correctly uses UTC-aware timestamps for both the expiry comparison and the updated_at field update, maintaining consistency.


157-177: LGTM!

UTC-aware timestamps are used consistently for expiry checks and time remaining calculations, which correctly compares against the UTC-aware expiry_time stored in the session.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant