Skip to content

Fix/deploy and google auth#197

Merged
sumagnadas merged 3 commits intoOpenLake:mainfrom
VarshiniGunti:fix/deploy-and-google-auth
Mar 24, 2026
Merged

Fix/deploy and google auth#197
sumagnadas merged 3 commits intoOpenLake:mainfrom
VarshiniGunti:fix/deploy-and-google-auth

Conversation

@VarshiniGunti
Copy link
Copy Markdown
Contributor

@VarshiniGunti VarshiniGunti commented Mar 16, 2026

Description

This PR fixes deployment and authentication blockers that prevented testing PRs.
It removes invalid backend Vercel function config and fixes Google auth token handling so login/register works reliably in deployed environments.

Related Issue(s)

  • Fixes #
  • Related to #

Changes

  • Removed invalid worker build/routes in backend Vercel config that referenced non-existent files.
  • Updated frontend Google auth flow to send Firebase ID token to backend (/api/token/google/ and /api/register/google/).
  • Improved backend Firebase Admin initialization to support env-based credentials (FIREBASE_SERVICE_ACCOUNT / FIREBASE_SERVICE_ACCOUNT_PATH) with local fallback.
  • Added explicit backend error responses when Firebase Admin is not configured.

Screenshots of relevant screens 📸

None

Type of Change

  • Bug fix
  • Feature
  • Breaking change
  • Docs
  • Refactor

Checklist

  • Code follows project style
  • Tested locally
  • Docs updated (if needed)
  • No new warnings

Notes

  • Frontend lint passes; existing warnings are pre-existing and unrelated to these changes.
  • Backend manage.py check could not complete in local environment due to psycopg runtime dependency issue, not due to this PR.
  • For production Google auth, backend must have Firebase service account configured via env vars or service-account.json.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Strengthened authentication error handling with clearer error messages when authentication services are unavailable
    • Improved Google login/signup security and reliability with enhanced token handling
  • New Features

    • Conditional post-authentication navigation for improved user experience

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 16, 2026

Walkthrough

Introduces flexible Firebase credential loading from multiple sources with fallback support, adds configuration guards in authentication endpoints to require Firebase setup, refactors frontend authentication functions to return success/failure booleans instead of implicit navigation, and simplifies Vercel deployment configuration.

Changes

Cohort / File(s) Summary
Firebase Initialization
api/leaderboard/api/firebase.py
New _load_credentials() helper loads credentials from environment variables or fallback file; replaces unconditional loading with guarded initialization that leaves default_app as None on credential loading failure.
Backend Authentication Guards
api/leaderboard/api/views.py
Added early-return checks in loginGoogleUser and registerGoogleUser to verify Firebase configuration; returns 500 error if default_app is not configured before proceeding with token verification.
Frontend Auth Refactoring
app/src/Context/AuthContext.jsx
SignInWithGoogle and SignUpWithGoogle now return boolean (true/false) instead of implicit navigation; added upfront Firebase configuration checks; switched from accessToken to ID token for backend communication; consolidated error handling with consistent failure paths.
Frontend Navigation Updates
app/src/components/Login.jsx, app/src/components/Register.jsx
Updated to conditionally navigate based on boolean return value from auth functions; navigation to root/profile occurs only on successful authentication.
Deployment Configuration
api/vercel.json
Simplified configuration by removing multi-build setup, environment variables, and worker-specific routes; retained single build and catch-all route to leaderboard WSGI app.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant Frontend as Frontend App
    participant AuthCtx as Auth Context
    participant Firebase as Firebase SDK
    participant Backend as Backend API

    User->>Frontend: Click Sign In with Google
    activate Frontend
    Frontend->>AuthCtx: SignInWithGoogle()
    activate AuthCtx
    
    Note over AuthCtx: Check Firebase config
    alt Firebase not configured
        AuthCtx->>Frontend: return false
        Frontend->>User: Alert error
    else Firebase configured
        AuthCtx->>Firebase: Trigger Google sign-in
        activate Firebase
        Firebase->>User: Open Google dialog
        User->>Firebase: Authenticate
        Firebase->>AuthCtx: return user & ID token
        deactivate Firebase
        
        AuthCtx->>Backend: POST with ID token
        activate Backend
        alt Token valid
            Backend->>AuthCtx: Verify & return success
            AuthCtx->>Frontend: return true
        else Token invalid
            Backend->>AuthCtx: Verification failed
            AuthCtx->>Frontend: return false
            Frontend->>User: Alert error
        end
        deactivate Backend
        
        alt Success
            Frontend->>Frontend: Navigate to dashboard
        end
    end
    deactivate AuthCtx
    deactivate Frontend
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 Firebase now wears three hats, so flexible and spry,
Credentials dance from three sources—what a way to fly!
Booleans replace nav flows, guards keep backends sound,
With Vercel's leaner config, our deployment's homeward-bound! 🚀

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is vague and generic, using abbreviated shorthand (Fix/deploy and google auth) that doesn't clearly convey the specific changes made despite being somewhat related to the main objectives. Revise the title to be more specific and descriptive, such as 'Fix Firebase auth token handling and Vercel deployment config' to better reflect the actual changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description check ✅ Passed The description is well-structured, follows the template closely, clearly explains the purpose, lists key changes, addresses testing status, and includes appropriate checklist items.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Tip

Migrating from UI to YAML configuration.

Use the @coderabbitai configuration command in a PR comment to get a dump of all your UI settings in YAML format. You can then edit this YAML file and upload it to the root of your repository to configure CodeRabbit programmatically.

@github-actions
Copy link
Copy Markdown

@check-spelling-bot Report

🔴 Please review

See the 📂 files view, the 📜action log, or 📝 job summary for details.

Unrecognized words (26)
amaydixit
arpit
atcoder
atcoderuser
ctz
efcajlnqvdqjeoud
FCalcutta
fns
FOSSOVERFLOW
grindset
gtcvau
Hacktoberfest
heatmap
ical
idx
iframe
kenkoooo
lccal
linecap
linejoin
lstrip
Maxed
noopener
spsiphnqk
startswith
ulk
These words are not needed and should be removed CRA leetcoderankingccps signup

Some files were automatically ignored 🙈

These sample patterns would exclude them:

^\Q.cspell.json\E$

You should consider adding them to:

.github/actions/spelling/excludes.txt

File matching is via Perl regular expressions.

To check these files, more of their words need to be in the dictionary than not. You can use patterns.txt to exclude portions, add items to the dictionary (e.g. by adding them to allow.txt), or fix typos.

To accept these unrecognized words as correct, update file exclusions, and remove the previously acknowledged and now absent words, you could run the following commands

... in a clone of the git@github.com:VarshiniGunti/Leaderboard-Pro.git repository
on the fix/deploy-and-google-auth branch (ℹ️ how do I use this?):

curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/main/apply.pl' |
perl - 'https://github.com/OpenLake/Leaderboard-Pro/actions/runs/23126784020/attempts/1' &&
git commit -m 'Update check-spelling metadata'
Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary

This includes both expected items (592) from .github/actions/spelling/expect.txt and unrecognized words (26)

Dictionary Entries Covers Uniquely
cspell:django/dict/django.txt 393 63 18
cspell:software-terms/dict/softwareTerms.txt 1288 106 15
cspell:python/src/common/extra.txt 741 20 13
cspell:npm/dict/npm.txt 302 46 10
cspell:html/dict/html.txt 2060 46 7

Consider adding them (in .github/workflows/spelling.yml) in jobs:/spelling::

      with:
        extra_dictionaries: |
          cspell:django/dict/django.txt
          cspell:software-terms/dict/softwareTerms.txt
          cspell:python/src/common/extra.txt
          cspell:npm/dict/npm.txt
          cspell:html/dict/html.txt

To stop checking additional dictionaries, add (in .github/workflows/spelling.yml):

check_extra_dictionaries: ""
Warnings ⚠️ (1)

See the 📂 files view, the 📜action log, or 📝 job summary for details.

⚠️ Warnings Count
⚠️ noisy-file 1

See ⚠️ Event descriptions for more information.

If you see a bunch of garbage

If it relates to a ...

well-formed pattern

See if there's a pattern that would match it.

If not, try writing one and adding it to the patterns.txt file.

Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

Note that patterns can't match multiline strings.

binary-ish string

Please add a file path to the excludes.txt file instead of just accepting the garbage.

File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

Copy link
Copy Markdown
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.

🧹 Nitpick comments (4)
app/src/Context/AuthContext.jsx (2)

219-225: Dead code: response["status"] === 400 check is never true.

signInWithPopup returns a UserCredential object on success or throws an exception on failure. It never returns an object with a status property. The condition !(response["status"] === 400) will always be true for successful responses, making this check ineffective.

Consider simplifying to just check for the response and user:

♻️ Proposed simplification
       response = await signInWithPopup(auth, googleProvider);
-      if (response && !(response["status"] === 400)) {
+      if (response?.user) {
         const idToken = await response.user.getIdToken();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/Context/AuthContext.jsx` around lines 219 - 225, Remove the dead
status check on the signInWithPopup result: signInWithPopup(auth,
googleProvider) returns a UserCredential or throws, so delete the invalid
response["status"] === 400 logic and instead verify the returned object and its
user property (e.g., check that response and response.user exist) before calling
response.user.getIdToken(); update the conditional around signInWithPopup to
handle success by checking response && response.user and rely on try/catch to
handle failures.

264-270: Same dead code issue as SignInWithGoogle.

The response["status"] === 400 check is ineffective here as well.

♻️ Proposed simplification
       response = await signInWithPopup(auth, googleProvider);
-      if (response && !(response["status"] === 400)) {
+      if (response?.user) {
         const idToken = await response.user.getIdToken();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/Context/AuthContext.jsx` around lines 264 - 270, Remove the
ineffective response["status"] === 400 check in the Google sign-in flow and
instead validate the actual sign-in result and user object returned by
signInWithPopup; specifically, in the code using signInWithPopup(auth,
googleProvider) check that response and response.user exist (and that
response.user.getIdToken() returns a token), and handle failures via the
existing try/catch path rather than testing a non-existent HTTP status on the
response object (references: signInWithPopup, googleProvider,
response.user.getIdToken).
api/leaderboard/api/firebase.py (1)

31-35: Add logging when Firebase initialization fails.

The broad except Exception catch prevents startup crashes, which is appropriate for optional Firebase support. However, silently swallowing all exceptions makes debugging difficult when credentials are misconfigured.

🔧 Proposed fix to add diagnostic logging
+import logging
+
+logger = logging.getLogger(__name__)
+
 try:
     cred = _load_credentials()
     default_app = firebase_admin.initialize_app(cred) if cred else None
+    if default_app is None:
+        logger.warning("Firebase Admin SDK not initialized: no credentials found")
-except Exception:
+except Exception as e:
+    logger.exception("Firebase Admin SDK initialization failed: %s", e)
     default_app = None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/leaderboard/api/firebase.py` around lines 31 - 35, The try/except around
_load_credentials() and firebase_admin.initialize_app currently swallows all
exceptions; update the except block to catch Exception as e and log a clear
diagnostic using the existing logger (or create one) that includes the exception
details and context (e.g., "Failed to initialize Firebase app with credentials")
and still assign default_app = None; reference _load_credentials,
firebase_admin.initialize_app, and default_app so you modify that exact
initialization block.
api/vercel.json (1)

2-14: Celery worker deployment removed — ensure workers run elsewhere.

The simplified configuration removes any Celery worker build/route entries. However, api/leaderboard/settings.py (lines 250-281) still defines CELERY_BEAT_SCHEDULE with 5 periodic tasks (codechef, github, leetcode, openlake, codeforces updates). These tasks will be scheduled but never executed unless Celery workers are deployed on separate infrastructure outside Vercel.

If Celery is intentionally disabled for now, consider commenting out or removing the CELERY_BEAT_SCHEDULE configuration to avoid confusion. If workers are expected to run elsewhere, document the required deployment setup.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/vercel.json` around lines 2 - 14, The Vercel config removes Celery worker
deployment but the app still defines CELERY_BEAT_SCHEDULE in
leaderboard/settings.py with periodic tasks (codechef_update, github_update,
leetcode_update, openlake_update, codeforces_update); update the repo to either
remove or comment out the CELERY_BEAT_SCHEDULE block if Celery is intentionally
disabled, or add a short README note and deployment docs indicating that Celery
workers must run on separate infrastructure and how to deploy/start them
(including broker/worker service and beat), so the scheduled tasks are either
disabled or clearly documented to run elsewhere.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@api/leaderboard/api/firebase.py`:
- Around line 31-35: The try/except around _load_credentials() and
firebase_admin.initialize_app currently swallows all exceptions; update the
except block to catch Exception as e and log a clear diagnostic using the
existing logger (or create one) that includes the exception details and context
(e.g., "Failed to initialize Firebase app with credentials") and still assign
default_app = None; reference _load_credentials, firebase_admin.initialize_app,
and default_app so you modify that exact initialization block.

In `@api/vercel.json`:
- Around line 2-14: The Vercel config removes Celery worker deployment but the
app still defines CELERY_BEAT_SCHEDULE in leaderboard/settings.py with periodic
tasks (codechef_update, github_update, leetcode_update, openlake_update,
codeforces_update); update the repo to either remove or comment out the
CELERY_BEAT_SCHEDULE block if Celery is intentionally disabled, or add a short
README note and deployment docs indicating that Celery workers must run on
separate infrastructure and how to deploy/start them (including broker/worker
service and beat), so the scheduled tasks are either disabled or clearly
documented to run elsewhere.

In `@app/src/Context/AuthContext.jsx`:
- Around line 219-225: Remove the dead status check on the signInWithPopup
result: signInWithPopup(auth, googleProvider) returns a UserCredential or
throws, so delete the invalid response["status"] === 400 logic and instead
verify the returned object and its user property (e.g., check that response and
response.user exist) before calling response.user.getIdToken(); update the
conditional around signInWithPopup to handle success by checking response &&
response.user and rely on try/catch to handle failures.
- Around line 264-270: Remove the ineffective response["status"] === 400 check
in the Google sign-in flow and instead validate the actual sign-in result and
user object returned by signInWithPopup; specifically, in the code using
signInWithPopup(auth, googleProvider) check that response and response.user
exist (and that response.user.getIdToken() returns a token), and handle failures
via the existing try/catch path rather than testing a non-existent HTTP status
on the response object (references: signInWithPopup, googleProvider,
response.user.getIdToken).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 78af3d2c-4046-4bdf-9414-e3be06343cd9

📥 Commits

Reviewing files that changed from the base of the PR and between b2f1a42 and e39339b.

📒 Files selected for processing (6)
  • api/leaderboard/api/firebase.py
  • api/leaderboard/api/views.py
  • api/vercel.json
  • app/src/Context/AuthContext.jsx
  • app/src/components/Login.jsx
  • app/src/components/Register.jsx

@sumagnadas
Copy link
Copy Markdown
Collaborator

LGTM.

@sumagnadas sumagnadas merged commit 81842aa into OpenLake:main Mar 24, 2026
1 of 2 checks passed
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.

2 participants