Skip to content

fix(auth): avoid persisting populated relationship fields in OAuth session write#75

Open
JannikZed wants to merge 2 commits into
WilsonLe:mainfrom
JannikZed:fix/oauth-session-relationship-persistence
Open

fix(auth): avoid persisting populated relationship fields in OAuth session write#75
JannikZed wants to merge 2 commits into
WilsonLe:mainfrom
JannikZed:fix/oauth-session-relationship-persistence

Conversation

@JannikZed
Copy link
Copy Markdown
Contributor

Summary

This PR fixes a regression in OAuth callback session persistence where the plugin writes the full user object via db.updateOne when adding a Payload session.

In projects with populated relationship fields (e.g. roles) on the user during login hooks, this can persist relationship objects instead of IDs and trigger Mongo cast errors like:

  • Cast to [ObjectId] failed ... at path "roles.0"

Root Cause

addPayloadSessionToUser currently passes a user-shaped object into session persistence, which can include populated relationship data from login hooks.

Fix

Update addPayloadSessionToUser to persist only session-related fields:

  • sessions
  • updatedAt

while still mutating the in-memory user with session info for downstream token signing.

Tests

Added regression coverage in test/callback-endpoint.spec.ts:

  • does not persist populated relationship fields when creating Payload sessions

This test simulates a populated roles array injected in beforeLogin and asserts that db.updateOne payload does not include roles.

Verification

Ran targeted test suite:

  • pnpm test -- callback-endpoint.spec.ts
  • Result: all tests passing (15/15)

@JannikZed JannikZed marked this pull request as ready for review May 18, 2026 08:37
@JannikZed
Copy link
Copy Markdown
Contributor Author

@WilsonLe found this bug with the new session logic.

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