Skip to content

fix: make Google auth flow reliable and success-gated#193

Open
VarshiniGunti wants to merge 3 commits intoOpenLake:mainfrom
VarshiniGunti:fix/google-auth-login-flow
Open

fix: make Google auth flow reliable and success-gated#193
VarshiniGunti wants to merge 3 commits intoOpenLake:mainfrom
VarshiniGunti:fix/google-auth-login-flow

Conversation

@VarshiniGunti
Copy link
Copy Markdown
Contributor

@VarshiniGunti VarshiniGunti commented Feb 25, 2026

Issue Description
Google authentication is failing inconsistently in the frontend flow. In failure scenarios (invalid Firebase setup, missing Google access token, or non-JSON backend response), the app may still proceed in UI flow, leading to confusing behavior and failed login state.

Expected behavior

  • Google login/register should proceed only when auth succeeds.
  • Navigation should happen only after successful backend token exchange.
  • Failures should show clear feedback and keep user on current auth page.
  • Missing Firebase config should fail gracefully, not break flow.

Actual behavior

  • Auth helpers did not consistently guard config/token/parsing failures.
  • Login/Register handlers could navigate even when Google auth failed.
  • Backend response parsing could throw when response was not JSON.

Proposed fix

  • Add safe JSON parsing in auth flow.
  • Guard Firebase auth initialization before popup flow.
  • Safely extract Google token from Firebase credential.
  • Make Google auth helpers return explicit success/failure.
  • Navigate only when success is true.

PR Summary
This PR hardens Google auth flow so it is success-gated and failure-safe.

What changed

  • AuthContext:
    • Added safe localStorage JSON parsing.
    • Added safe response JSON parser.
    • Added Firebase config/auth guard before popup.
    • Added robust Google token extraction.
    • Updated SignInWithGoogle / SignUpWithGoogle to return boolean success.
  • Login / Register:
    • Navigate only when Google auth helper returns success.

Result

  • No false-success redirects.
  • Better error handling for misconfiguration/backend failures.
  • More reliable Google login/register UX.

Summary by CodeRabbit

  • Bug Fixes
    • Improved Google sign-in and sign-up error handling with user-friendly alerts instead of silent failures
    • Fixed authentication flow to navigate to dashboard only on successful login or to profile on successful registration
    • Enhanced token extraction reliability and validation for Google OAuth authentication

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Feb 25, 2026

Warning

Rate limit exceeded

@VarshiniGunti has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 16 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dc2f1aef-00cb-400b-8d65-0827a01d21eb

📥 Commits

Reviewing files that changed from the base of the PR and between da02c49 and 9a418d6.

📒 Files selected for processing (1)
  • app/src/Context/AuthContext.jsx

Walkthrough

Authentication error handling is improved across three components. AuthContext now provides robust Google OAuth token extraction with fallback logic, user-facing alerts for errors, and boolean return values to indicate success or failure. Login and Register components conditionally navigate based on authentication outcomes rather than unconditionally.

Changes

Cohort / File(s) Summary
OAuth Error Handling & Token Management
app/src/Context/AuthContext.jsx
Firebase config errors now show user alerts; Google OAuth token extraction uses GoogleAuthProvider.credentialFromResult with fallback to response.user.accessToken; backend calls send computed accessToken; functions return boolean values; error handling logs to console and shows alerts; cancellations explicitly return false.
Conditional Navigation
app/src/components/Login.jsx, app/src/components/Register.jsx
Navigation to home/profile routes now depends on authentication success flags instead of executing unconditionally; sign-in/registration results are checked before routing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 With tokens secured and errors made clear,
Our OAuth flows now have no fear,
Navigation waits for success to align,
No more blind hops—just a cleaner design!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: making Google auth flow reliable and success-gated, which aligns with the changeset's core objective.
Description check ✅ Passed The description is comprehensive, covering issue context, expected/actual behavior, proposed fixes, and implementation details. However, the Type of Change checkboxes and some template sections are not filled out.

✏️ 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

You can make CodeRabbit's review stricter and more nitpicky using the `assertive` profile, if that's what you prefer.

Change the reviews.profile setting to assertive to make CodeRabbit's nitpick more issues in your PRs.

@VarshiniGunti VarshiniGunti force-pushed the fix/google-auth-login-flow branch from 79affb1 to a013b18 Compare February 25, 2026 15:55
@github-actions

This comment has been minimized.

Copilot AI review requested due to automatic review settings March 16, 2026 03:23
@github-actions

This comment has been minimized.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the Google authentication flow to be success-gated, ensuring navigation only occurs after a successful auth exchange with the backend. Previously, SignInWithGoogle and SignUpWithGoogle could allow navigation even on failure.

Changes:

  • SignInWithGoogle and SignUpWithGoogle in AuthContext.jsx now return boolean (true/false) instead of the Firebase response, with guards for missing Firebase config, missing access tokens, and safe JSON parsing.
  • Login.jsx and Register.jsx now conditionally navigate only when the Google auth helper returns true.
  • Removed navigate() calls from inside the auth helpers, delegating navigation responsibility to the calling components.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 6 comments.

File Description
app/src/Context/AuthContext.jsx Refactored SignInWithGoogle/SignUpWithGoogle to return boolean success, added token extraction guard, removed internal navigation
app/src/components/Login.jsx Gates navigation on SignInWithGoogle returning true; minor whitespace fix
app/src/components/Register.jsx Gates navigation on SignUpWithGoogle returning true

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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.

Actionable comments posted: 2

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

253-256: Consider using console.error for error logging.

Using console.error instead of console.log for caught exceptions improves debuggability by marking them as errors in browser dev tools.

♻️ Suggested change
     } catch (error) {
-      console.log(error);
+      console.error("Google sign-in error:", error);
       alert("Please try logging in again");
       return false;
     }

Same applies to line 302 in SignUpWithGoogle.

🤖 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 253 - 256, Replace the generic
console.log calls in the catch blocks with console.error to properly surface
exceptions; specifically update the catch in the sign-in flow (the catch block
shown around the return false in AuthContext.jsx) and the catch in
SignUpWithGoogle so they call console.error(error) instead of
console.log(error), leaving the existing alert and return behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/src/Context/AuthContext.jsx`:
- Around line 268-281: The code is sending the OAuth access token to the backend
(credential?.accessToken / accessToken) instead of the Firebase ID token; update
the registration flow in the same function that creates credential and calls
fetch (symbols: GoogleAuthProvider.credentialFromResult, credential,
accessToken, regresponse) to obtain the ID token (either credential.idToken or
await response.user.getIdToken()) and send that idToken in the POST body to
/api/register/google/ (replace token: accessToken with token: idToken) so the
backend receives the Firebase ID token.
- Around line 221-234: The code is sending the Google OAuth access token
(credential?.accessToken) to the backend, but Firebase Admin expects a Firebase
ID token; replace use of credential?.accessToken (and any variable named
accessToken) with the Firebase ID token obtained from the signed-in user (await
response.user.getIdToken()) and send that ID token in the POST body to
BACKEND+"/api/token/google/"; apply the same change in both places referenced
(the block using GoogleAuthProvider.credentialFromResult(response) and the
SignUpWithGoogle block) so the backend's verify_id_token() receives a Firebase
ID token.

---

Nitpick comments:
In `@app/src/Context/AuthContext.jsx`:
- Around line 253-256: Replace the generic console.log calls in the catch blocks
with console.error to properly surface exceptions; specifically update the catch
in the sign-in flow (the catch block shown around the return false in
AuthContext.jsx) and the catch in SignUpWithGoogle so they call
console.error(error) instead of console.log(error), leaving the existing alert
and return behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ff036621-6798-4016-9714-691f61b98b50

📥 Commits

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

📒 Files selected for processing (3)
  • app/src/Context/AuthContext.jsx
  • app/src/components/Login.jsx
  • app/src/components/Register.jsx

@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

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/google-auth-login-flow 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/23126866054/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:fullstack/dict/fullstack.txt 419 42 8

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:fullstack/dict/fullstack.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).

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