Skip to content

fix: preserve session on transient auth checks#82

Open
saurabhhhcodes wants to merge 3 commits into
kunalverma2512:mainfrom
saurabhhhcodes:fix/preserve-session-transient-auth-39
Open

fix: preserve session on transient auth checks#82
saurabhhhcodes wants to merge 3 commits into
kunalverma2512:mainfrom
saurabhhhcodes:fix/preserve-session-transient-auth-39

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented May 19, 2026

Copy link
Copy Markdown
Contributor

Fixes #39.

What changed

  • Auth bootstrapping now clears stored credentials only when profile refresh returns a real auth failure (401 or 403).
  • Temporary network/server failures preserve the stored token and cached user instead of logging the user out.
  • Verified profile data is cached after login/profile refresh so the UI can stay stable during transient outages.
  • The shared API interceptor now treats 401/403 as auth failures while leaving other failures to callers.

Validation

  • cd frontend && ./node_modules/.bin/eslint src/context/AuthContext.jsx src/services/api.js
  • git diff --check

Note: cd frontend && ./node_modules/.bin/vite build is blocked locally by the installed Rolldown native binding failing macOS code-signing/native optional dependency loading, before app code compiles.

Suggested labels for GSSoC: gssoc:approved, level:intermediate, quality:clean, type:bug.

Summary by CodeRabbit

  • New Features

    • Authentication error states are now tracked and accessible for improved error reporting
  • Bug Fixes

    • Improved session initialization to correctly distinguish between transient and permanent authentication failures
    • Enhanced logout process to properly clear cached authentication error states
    • Optimized login redirect behavior to only trigger for confirmed authentication failures, preventing unnecessary redirects during temporary issues

@github-actions

Copy link
Copy Markdown

🚀 PR Received Successfully

Hello @saurabhhhcodes,

Thank you for taking the initiative to contribute to this project.

Please ensure that your PR follows all project guidelines properly before requesting review.

⚠️ Important Instructions

  • Maintain proper code quality and structure
  • Do not make unnecessary changes/files
  • Ensure responsiveness across devices
  • Follow existing project conventions strictly
  • Attach screenshots/videos for UI-related changes
  • Resolve merge conflicts before requesting review
  • Avoid AI-generated low quality PRs or copied implementations

📌 Mandatory for GSSoC'26 Participants

Joining the community group and announcement channel is compulsory for all contributors participating through GSSoC'26.

Failure to follow contribution guidelines may lead to PR rejection.

We appreciate your effort and wish you a great open-source journey ahead. ✨

@coderabbitai

coderabbitai Bot commented May 19, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@saurabhhhcodes, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 37 minutes and 45 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fa5122b4-4571-4840-83c7-4d91119238a6

📥 Commits

Reviewing files that changed from the base of the PR and between 899d025 and 6ab632e.

📒 Files selected for processing (2)
  • frontend/src/context/AuthContext.jsx
  • frontend/src/services/api.js
📝 Walkthrough

Walkthrough

AuthContext now tracks an authError string state and applies conditional error handling across session initialization, login, logout, and user refresh. The API response interceptor selectively redirects to /login only when auth-failure status codes (401/403) occur on designated auth endpoints.

Changes

Auth Error Tracking and Selective Redirect Gating

Layer / File(s) Summary
Auth Context Error State and Handler Integration
frontend/src/context/AuthContext.jsx
AuthContext adds authError state variable and updates getMe() effect to distinguish confirmed auth failures (401/403—clear user and error) from transient failures (set error message, preserve user). Login clears authError on state updates, logout clears authError after clearing user, and refreshUser sets/clears authError based on success vs. auth failure vs. other failure types. Context value now exports authError for consumer access.
API Interceptor Selective Redirect Logic
frontend/src/services/api.js
Axios client defines AUTH_FAILURE_STATUSES set (401, 403) and AUTH_ONLY_PATHS list for session/profile endpoints. Response interceptor checks both status code and request URL before redirecting to /login; other failures propagate error without redirect. Configuration retains withCredentials: true for cookie handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A rabbit's ode to steady sessions:
No more lost trust on network hiccups,
Auth errors named, transient skipped,
Only true logout signs the slip—
Error messages bloom in context's cup,
Sessions survive the API's stumbles, hooray!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description covers what changed and validation steps, but deviates from the template structure with minimal use of required sections like Type of Change, Testing, and Checklist. Align description with the template by explicitly filling Type of Change checkboxes, providing detailed Testing section with verification status, and completing the Checklist items.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main objective: preventing unnecessary session loss during transient auth checks, which is the core change.
Linked Issues check ✅ Passed The PR directly addresses all coding requirements from issue #39: differentiates auth errors (401/403) from transient failures, preserves session during non-auth failures, and caches verified profile data for UI stability.
Out of Scope Changes check ✅ Passed All changes focus on auth error handling in AuthContext and API interceptor logic; no out-of-scope modifications detected beyond the stated objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@saurabhhhcodes

Copy link
Copy Markdown
Contributor Author

Quick follow-up: this PR is still clean and mergeable from my side. If there is no further feedback needed here, please review and merge when convenient; I can respond quickly if you want any changes.

…transient-auth-39

# Conflicts:
#	frontend/src/context/AuthContext.jsx
#	frontend/src/services/api.js
@vercel

vercel Bot commented May 31, 2026

Copy link
Copy Markdown

@saurabhhhcodes is attempting to deploy a commit to the Kunal Verma's projects Team on Vercel.

A member of the Team first needs to authorize it.

@saurabhhhcodes

Copy link
Copy Markdown
Contributor Author

Refreshed this PR against current main and resolved the auth-context/api conflicts.

Resolution notes:

  • kept the new HttpOnly cookie-based auth flow from main
  • preserved this PR’s behavior so transient session refresh/API failures do not clear the current user or globally redirect
  • kept login/logout/refreshUser clearing authError only on successful or confirmed auth-loss paths

Validation:

  • npm install --ignore-scripts in frontend
  • npx eslint src/context/AuthContext.jsx src/services/api.js --quiet
  • npm run build
  • git diff --check -- frontend/src/context/AuthContext.jsx frontend/src/services/api.js

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@frontend/src/context/AuthContext.jsx`:
- Around line 31-45: The initAuth bootstrap treats any non-401/403 getMe()
failure as signed-out by leaving user null and clearing loading; change it to
preserve the last known authenticated state (or introduce an explicit
"authUnknown" flag) instead of setting user to null on transient errors: in
initAuth, on catch for non-401/403 errors do not overwrite setUser (leave
existing user value) and set a separate state like setAuthError(...) or
setAuthUnknown(true) so that callers relying on !loading && !isAuthenticated
don't treat temporary failures as sign-out; keep handling for 401/403 to clear
user via setUser(null) and still call setLoading(false) when finished.

In `@frontend/src/services/api.js`:
- Around line 25-29: The current substring check using requestUrl.includes(path)
causes false positives; instead parse the requestUrl into a URL object (e.g. new
URL(requestUrl, window.location.origin)), normalize its pathname (remove
trailing slash if needed) and then check AUTH_ONLY_PATHS.some(path =>
normalizedPathname === path) so only exact pathname matches trigger the
redirect; update the logic around AUTH_FAILURE_STATUSES, AUTH_ONLY_PATHS and the
isAuthPath computation to use the URL pathname and handle relative URLs safely.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6637730e-6898-48b9-82a3-68e43f19d848

📥 Commits

Reviewing files that changed from the base of the PR and between 9390870 and 899d025.

📒 Files selected for processing (2)
  • frontend/src/context/AuthContext.jsx
  • frontend/src/services/api.js

Comment thread frontend/src/context/AuthContext.jsx
Comment thread frontend/src/services/api.js
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.

Prevent Unnecessary User Logout During Temporary Network/API Failures

1 participant