Skip to content

feat: enhance NextAuth configuration and user session management with additional fields and cookie domain validation - #3607

Merged
Baalmart merged 3 commits into
stagingfrom
SSO-configuration
Jun 10, 2026
Merged

feat: enhance NextAuth configuration and user session management with additional fields and cookie domain validation#3607
Baalmart merged 3 commits into
stagingfrom
SSO-configuration

Conversation

@OchiengPaul442

@OchiengPaul442 OchiengPaul442 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done

Screenshots (optional)

Summary by CodeRabbit

  • New Features

    • Enhanced user profile data now captures organization, privilege, country, phone number, and username information during authentication.
  • Bug Fixes

    • Improved logout behavior with more reliable page navigation.
    • Refined authentication cookie handling across environments for better session management.

… additional fields and cookie domain validation
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 14 minutes and 27 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 89e2cd9a-0eaa-4e1c-a945-d28247bcd554

📥 Commits

Reviewing files that changed from the base of the PR and between 0b7c97e and d3fb9c4.

📒 Files selected for processing (3)
  • src/platform/src/shared/hooks/useLogout.ts
  • src/vertex/app/api/auth/[...nextauth]/options.ts
  • src/vertex/middleware.ts
📝 Walkthrough

Walkthrough

This PR extends NextAuth authentication across two applications (platform and vertex) by introducing environment-based cookie domain configuration, augmenting session/JWT/user types with profile identity fields, enriching credential providers to populate those fields from OAuth tokens and login data, and switching post-logout navigation from Next.js router to full-page redirects.

Changes

Platform App Authentication Enhancement

Layer / File(s) Summary
Environment and Type Definitions
src/platform/.env.example, src/platform/src/next-auth.d.ts
NextAuth environment example includes NEXTAUTH_COOKIE_DOMAIN setting; SessionUser, User, and JWT types gain optional profile fields (userName, organization, privilege, country, phoneNumber) and expiration tracking (exp).
Cookie Domain Validation and Middleware Configuration
src/platform/src/shared/lib/auth.ts, src/platform/middleware.ts
getCookieDomain() validates NEXTAUTH_COOKIE_DOMAIN against NEXTAUTH_URL host with fallback warnings; session cookie naming switches from analytics-prefixed to standard next-auth.session-token; configuration wired through shared cookieOptions.
Credentials Provider Enhancement
src/platform/src/shared/lib/auth.ts
OAuth token flow decodes JWT payload to extract userName, organization, privilege, country, phoneNumber, and expiration; email/password flow populates same SSO identity fields from loginData; credential failures throw structured error objects containing message/status/data/success.
JWT and Session Callback Enrichment
src/platform/src/shared/lib/auth.ts
JWT callback stores userName, organization, privilege, country, phoneNumber, image, and exp from user object; session callback mirrors these fields onto session.user with safe fallbacks and conditional image assignment.
Logout Navigation Redirect Pattern
src/platform/src/shared/hooks/useLogout.ts
Logout removes Next.js router and switches to window.location.href for full-page redirects to callbackUrl or fallback path; applied in both success and error paths; router dependency removed from useCallback.

Vertex App Authentication Enhancement

Layer / File(s) Summary
Environment and Type Definitions
src/vertex/.env.example, src/vertex/types/next-auth.d.ts
Environment example includes NEXTAUTH_COOKIE_DOMAIN setting; Session.user, User, and JWT types augmented with optional _id, image, expiresAt, and exp fields.
Session Cookie Configuration
src/vertex/middleware.ts, src/vertex/app/api/auth/[...nextauth]/options.ts
Session cookie naming removes -v2 suffix: production uses __Secure-next-auth.session-token, non-production uses next-auth.session-token.
Credentials Provider and Session Enrichment
src/vertex/app/api/auth/[...nextauth]/options.ts
OAuth and password authorize paths populate image field from profile/decoded claims/fallback; JWT callback stores _id and image on token; session callback maps token fields to session.user with fallbacks.
Logout Navigation Redirect Pattern
src/vertex/core/hooks/useLogout.ts
Logout removes router-based navigation and uses window.location.href for full-page redirects; applied in both success and error paths; router dependency removed from useCallback; usePathname imported separately.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • airqo-platform/AirQo-frontend#3587: Modifies the sessionToken cookie naming in src/vertex/middleware.ts and src/vertex/app/api/auth/[...nextauth]/options.ts, directly overlapping with this PR's cookie rotation changes.

Suggested reviewers

  • Baalmart
  • Codebmk

Poem

🔐 Cookies are unified across the land,
With profile fields by NextAuth's hand,
OAuth tokens decoded with care,
Sessions enriched everywhere,
Full-page redirects make the logout fair ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately captures the main changes: enhanced NextAuth configuration with additional session fields and cookie domain validation across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch SSO-configuration

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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.

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure analytics_platform changes available for preview here

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
src/platform/src/shared/lib/auth.ts (1)

237-247: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't stringify raw backend error payloads into the NextAuth error message.

error?.data is being copied straight into Error.message. In this flow that message is very likely to get logged or propagated through auth error handling, which can leak backend response bodies and user identifiers into logs, monitoring, or redirect/query surfaces. Throw a sanitized code/message instead and keep the raw payload server-side only if it's redacted.

As per coding guidelines, "Keep NextAuth session tokens out of logs and sanitize error payloads."

Suggested direction
         } catch (error: any) {
-          // Enhanced error handling to include status and full response data
-          const errorData = {
-            message: error?.message || 'Login failed',
-            status: error?.status || 500,
-            data: error?.data || null,
-            success: false,
-          };
-
-          // Throw a structured error that includes all the details
-          throw new Error(JSON.stringify(errorData));
+          const status =
+            typeof error?.status === 'number' ? error.status : 500;
+          const message =
+            status === 401 ? 'Invalid credentials' : 'Login failed';
+
+          throw new Error(message);
         }
🤖 Prompt for 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.

In `@src/platform/src/shared/lib/auth.ts` around lines 237 - 247, The catch block
in src/shared/lib/auth.ts currently serializes backend payloads into
Error.message (the errorData object) which can leak sensitive info; instead,
change the catch handling in the login/auth flow so you throw a sanitized Error
containing only a non-sensitive code and brief message (e.g.,
"AUTH_LOGIN_FAILED" / "Login failed") and do NOT include error?.data in the
Error.message; keep the full backend payload private by assigning it to a
non-serializing property (e.g., error.raw or a local server-side log) and redact
any tokens/identifiers before logging, and ensure this change is applied where
errorData is created/thrown in the catch block so NextAuth receives only the
safe code/message.

Source: Coding guidelines

🤖 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 `@src/platform/src/shared/hooks/useLogout.ts`:
- Around line 119-127: The catch block in useLogout currently treats a failed
signOut() as success by clearing local state and forcing navigation, which can
leave the NextAuth cookie intact; update the catch so you do NOT reset local
auth state or immediately redirect when signOut({ redirect: false }) throws.
Instead, on error attempt a fallback server-side sign-out (e.g. POST to your
server sign-out route or call a server-side endpoint) and await its result; only
perform window.location.href navigation after the server-side sign-out succeeds,
and if that also fails, leave logging-out state (dispatch(setLoggingOut(false))
or set an error state) and do not navigate so the client doesn’t silently
recreate a session. Ensure the changes are made around the signOut call in
useLogout and reference signOut and setLoggingOut when modifying the control
flow.

In `@src/vertex/app/api/auth/`[...nextauth]/options.ts:
- Line 337: The session callback currently assigns session.user._id from
token.id but the JWT callback stores the Mongo-style identifier on token._id;
update the session construction to read session.user._id from token._id (not
token.id) so the persisted `_id` contract is preserved—locate the session
callback in options.ts where session.user._id is assigned and change the source
to token._id.

---

Outside diff comments:
In `@src/platform/src/shared/lib/auth.ts`:
- Around line 237-247: The catch block in src/shared/lib/auth.ts currently
serializes backend payloads into Error.message (the errorData object) which can
leak sensitive info; instead, change the catch handling in the login/auth flow
so you throw a sanitized Error containing only a non-sensitive code and brief
message (e.g., "AUTH_LOGIN_FAILED" / "Login failed") and do NOT include
error?.data in the Error.message; keep the full backend payload private by
assigning it to a non-serializing property (e.g., error.raw or a local
server-side log) and redact any tokens/identifiers before logging, and ensure
this change is applied where errorData is created/thrown in the catch block so
NextAuth receives only the safe code/message.
🪄 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: 08dc9ffe-6686-42eb-90ac-10c4564f597e

📥 Commits

Reviewing files that changed from the base of the PR and between 97fcf0d and 0b7c97e.

📒 Files selected for processing (10)
  • src/platform/.env.example
  • src/platform/middleware.ts
  • src/platform/src/next-auth.d.ts
  • src/platform/src/shared/hooks/useLogout.ts
  • src/platform/src/shared/lib/auth.ts
  • src/vertex/.env.example
  • src/vertex/app/api/auth/[...nextauth]/options.ts
  • src/vertex/core/hooks/useLogout.ts
  • src/vertex/middleware.ts
  • src/vertex/types/next-auth.d.ts

Comment thread src/platform/src/shared/hooks/useLogout.ts
Comment thread src/vertex/app/api/auth/[...nextauth]/options.ts Outdated
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure docs changes available for preview here

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure analytics_platform changes available for preview here

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure analytics_platform changes available for preview here

@Baalmart
Baalmart merged commit 45ef3a1 into staging Jun 10, 2026
26 of 28 checks passed
@Baalmart
Baalmart deleted the SSO-configuration branch June 10, 2026 03:52
@Baalmart Baalmart mentioned this pull request Jun 10, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants