Repository navigation
feat!: Introduce shared AuthSuccess for all authentication strategies. - #3904
marcelomendoncasoares merged 11 commits into
Conversation
… side sessions and JWT tokens.
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughReplaces sessionKey with token across auth flows and introduces AuthStrategy. AuthSuccess now carries authStrategy, token, optional refreshToken, authUserId, and scopeNames. Token generation and session creation return AuthSuccess. Client SessionManager stores token. Tests and exports updated accordingly; TokenPair replaced in JWT paths. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client
participant Server as Auth Server
participant JWT as JWT Service
participant Store as SessionManager (Client)
rect rgba(200,220,255,0.25)
note over Client,Server: Authentication (Session-based)
Client->>Server: Create session (credentials)
Server-->>Client: AuthSuccess{authStrategy=session, token=sessionKey, authUserId, scopeNames}
Client->>Store: setLoggedIn(AuthSuccess)
Store-->>Store: Save token to secure storage
end
rect rgba(200,255,220,0.25)
note over Client,JWT: Authentication (JWT-based)
Client->>Server: Request tokens (credentials)
Server->>JWT: createTokens(...)
JWT-->>Server: AuthSuccess{authStrategy=jwt, token=accessJWT, refreshToken?}
Server-->>Client: AuthSuccess
Client->>Store: setLoggedIn(AuthSuccess)
Store-->>Store: Save token to secure storage
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
✨ Finishing Touches🧪 Generate 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
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 (3)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1)
82-99: Missing refreshToken persistence in Flutter SessionManagerI searched the entire
serverpod_auth_core_flutterpackage for anyrefreshTokenreferences (viarg -n '\brefreshToken\b') and found none. The currentSessionManageronly stores:
tokenauthUserIdscopeNamesTo properly support JWT flows with refresh tokens, please:
• In
lib/src/session_manager.dart→setLoggedIn(AuthSuccess authSuccess), also persist the refresh token:await _secureStorage.set( SessionManagerStorageKeys.refreshTokenKey.key, authSuccess.refreshToken, );(You’ll need to add a corresponding key in
SessionManagerStorageKeys.)• In
_init()/ your “current auth” getter, read the storedrefreshTokenand use it for silent renewal when the access token expires.• In
clearSession(), remove the persistedrefreshTokenalongside the other keys.If you’re intentionally relying solely on short-lived JWTs (no refresh flow), please confirm that this omission is expected.
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (1)
124-149: Breaking Change: Update.sessionKeyto.tokenin Call SitesPlease update any places still accessing the old
sessionKeyproperty on theAuthSuccessreturned bycreateSession, and document this in your PR’s “Breaking changes” section.• tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:329
Change:- loginSessionKey = registrationResult.sessionKey; + loginSessionKey = registrationResult.token;No other occurrences of
.sessionKeyonAuthSuccesswere found.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (1)
69-73: Typo: “paylaod” → “payload”Small spelling fix in public docs.
Apply this diff:
- /// These are added on the top level of the paylaod, so be sure not to conflict with the [registered claims](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1), + /// These are added on the top level of the payload, so be sure not to conflict with the [registered claims](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1),
🧹 Nitpick comments (27)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml (1)
1-1: Fix grammar in the top-level doc string.“supported the” → “supported by the”.
Apply this diff:
-### Authentication strategies supported the Serverpod authentication core module +### Authentication strategies supported by the Serverpod authentication core modulemodules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml (2)
3-4: Widen wording: not all successes are “sessions”.JWT-based flows aren’t sessions. Suggest a neutral phrasing.
Apply this diff:
- ### The authentication strategy used for this session. + ### The authentication strategy used for this authentication (e.g., JWT or session).
9-10: Document invariants between strategy and tokens.
- If authStrategy == session, refreshToken should be null.
- If authStrategy == jwt, token is the access token; refreshToken may be present depending on flow.
Would you like me to add these notes to the model comments and scan/create unit tests that assert these invariants in the business layer?
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1)
45-51: Consider migrating the storage key from “sessionKey” to a neutral “authToken” with backward compatibility.You’re now storing JWTs and session keys under a key named sessionKey; that’s confusing and makes future migrations harder. Suggest introducing a new key while continuing to read/write the legacy key for one release.
Apply these changes:
@@ Future<void> _init() async { - final sessionKey = await _secureStorage.get( - SessionManagerStorageKeys.sessionKey.key, - ); + // Prefer the new 'authToken' key, but support the legacy 'sessionKey' for backward compatibility. + var sessionKey = await _secureStorage.get( + SessionManagerStorageKeys.authToken.key, + ); + sessionKey ??= await _secureStorage.get( + SessionManagerStorageKeys.sessionKey.key, + ); @@ Future<void> setLoggedIn(AuthSuccess authSuccess) async { await _secureStorage.set( - SessionManagerStorageKeys.sessionKey.key, - authSuccess.token, + SessionManagerStorageKeys.authToken.key, + authSuccess.token, ); + // Also write legacy key during transition period. + await _secureStorage.set( + SessionManagerStorageKeys.sessionKey.key, + authSuccess.token, + ); @@ Future<void> setLoggedOut() async { - await _secureStorage.set(SessionManagerStorageKeys.sessionKey.key, null); + await _secureStorage.set(SessionManagerStorageKeys.authToken.key, null); + await _secureStorage.set(SessionManagerStorageKeys.sessionKey.key, null); @@ enum SessionManagerStorageKeys { - sessionKey('serverpod_auth_session.sessionKey'), + // New neutral key name for both JWT and session tokens. + authToken('serverpod_auth_session.token'), + // Legacy key kept for backward compatibility. + sessionKey('serverpod_auth_session.sessionKey'),Follow-up: We should also update any docs/comments that reference “session key” to reflect that the value may be a JWT or a session key.
Also applies to: 84-87, 107-107, 136-144
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_admin_test.dart (1)
114-128: Avoid non-null assertion with a clearer test flow and rename for accuracy.Rename tokenPair → authSuccess, assert refreshToken presence before parsing. This improves readability and diagnostics on failures.
Apply this diff:
- final tokenPair = await AuthenticationTokens.createTokens( + final authSuccess = await AuthenticationTokens.createTokens( session, authUserId: authUserId, scopes: {}, ); refreshTokenIdsInOrderOfCreation.add( UuidValue.fromByteList( - base64Decode(tokenPair.refreshToken!.split(':')[1]), + () { + final refreshToken = authSuccess.refreshToken; + expect(refreshToken, isNotNull, + reason: + 'createTokens() should produce a refreshToken in admin test setup'); + return base64Decode(refreshToken!.split(':')[1]); + }(), ), );modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart (1)
49-50: Optional: renamesessionKeyvariables tosessionTokenfor clarity.Now that the value originates from
AuthSuccess.token, naming itsessionToken(or simplytoken) reduces cognitive overhead in tests.Do you want me to generate a follow-up patch to rename and update references in this file?
Also applies to: 122-123, 160-161, 221-222
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart (3)
35-45: Assert non-null before dereferencing authInfo to improve test failure diagnostics
authenticationHandlercan return null. Immediately dereferencing with!can obscure the root cause when authentication unexpectedly fails. Add an explicit non-null expectation before using the value (consistent with team testing preferences).Apply this diff:
final authInfoABeforeRevocation = await AuthSessions.authenticationHandler( session, sessionKey, ); + // Ensure we fail with a clear error if authentication unexpectedly returns null + expect(authInfoABeforeRevocation, isNotNull); + final channelName = MessageCentralServerpodChannels.revokedAuthentication( authInfoABeforeRevocation!.userIdentifier, );
129-135: Avoid hand-parsing the token; prefer a stable parse helper or APIManually splitting on ':' and base64-decoding couples the test to the current token format. If
buildSessionKey(...)ever changes its serialization, this will silently break.
- Prefer using a library/helper to parse the token (e.g., a
tryParseSessionKey-like helper) to retrieveauthSessionId, if accessible from tests.- If such helper isn’t publicly available, consider adding a small, test-only helper in the module to extract the
authSessionIdin a format-stable way.If accessible, this is what the intent would look like:
final (:authSessionId, :secret) = tryParseSessionKey(session, destroyedSessionKey)!; await AuthSessions.destroySession( session, authSessionId: authSessionId, );Please verify whether
tryParseSessionKey(or an equivalent) is available to tests or can be exposed via a test-only export.
181-195: Naming consistency: consider renaming variables and descriptions from “session key” to “token”You’ve correctly switched to
.token, but the variables (sessionKey1,sessionKey2, etc.) and test descriptions still refer to “session key”. For clarity with the new unified AuthSuccess.token concept, consider renaming to “token” in variable names and test descriptions. This is cosmetic but helps future maintainers.tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart (4)
113-115: Update test descriptions to say “token” instead of “session key”The behavioral assertions now validate a token; update the user-facing test descriptions for clarity.
Example edits:
- “...then it succeeds returning a valid session key.” → “...then it succeeds returning a valid token.”
Also applies to: 153-155, 289-291, 363-366
445-451: Avoid!onauthInfofor clearer failuresSimilar to other tests, assert that
authInfois not null before using it. This yields more actionable failures when auth unexpectedly fails.Apply this diff:
final authInfo = await AuthSessions.authenticationHandler( sessionBuilder.build(), authSuccess.token, ); - return (sessionKey: authSuccess.token, authUserId: authInfo!.authUserId); + expect(authInfo, isNotNull); + return (sessionKey: authSuccess.token, authUserId: authInfo!.authUserId);
487-489: Docstring still mentions “session key”; update to “token”The helper returns a token now; adjust the docstring accordingly.
Apply this diff:
- /// Returns the new session key after successful password change. + /// Returns the new token after a successful password change.
413-451: Optional: rename the returned record field fromsessionKeytotokenfor consistencyThe extension returns
({String sessionKey, UuidValue authUserId})but now populates it withauthSuccess.token. Consider renaming to reduce confusion across tests.Apply this diff within the helper:
- Future<({String sessionKey, UuidValue authUserId})> _registerEmailAccount( + Future<({String token, UuidValue authUserId})> _registerEmailAccount( ... - return (sessionKey: authSuccess.token, authUserId: authInfo!.authUserId); + return (token: authSuccess.token, authUserId: authInfo!.authUserId);You’ll need to adjust call sites in this file accordingly, e.g.:
// Before loginSessionKey = registrationResult.sessionKey; // After loginSessionKey = registrationResult.token;modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (1)
120-122: Minor wording: remove double space and clarify sentenceSmall polish to the doc comment.
Apply this diff:
- /// Send the return value to the client to use that to authenticate in future calls. + /// Send the return value to the client to authenticate future calls.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/jwt.dart (1)
11-19: Export AuthStrategy alongside AuthSuccess in jwt.dartConsumers handling
AuthSuccess.authStrategywill commonly need theAuthStrategyenum. Exporting it here lets them pull both types from the JWT barrel without importingprotocol.dartseparately.Apply this patch in
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/jwt.dart:export '../generated/protocol.dart' show AuthenticationTokenInfo, + AuthStrategy, AuthSuccess, RefreshTokenExpiredException, RefreshTokenInvalidSecretException, RefreshTokenMalformedException, RefreshTokenNotFoundException, TokenPair;modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (2)
59-63: Docstring still says “Creates a new token pair” but method now returns AuthSuccessAdjust the wording to reflect the AuthSuccess return type and the unified token concept.
Apply this diff:
- /// Creates a new token pair for the given auth user. + /// Creates new JWT credentials (AuthSuccess) for the given auth user. /// - /// This is akin to creating a new session, and should be used after a successful login or registration. + /// This is akin to creating a new session, used after a successful login or registration.
110-192: API consistency: consider returning AuthSuccess from refresh rotation as well
rotateRefreshTokenstill returnsTokenPair, whereascreateTokensnow returnsAuthSuccess. Mixed return types complicate clients. Consider:
- Adding a new
rotateTokens(...) -> Future<AuthSuccess>and deprecatingrotateRefreshToken(keeping it for back-compat), or- Changing
rotateRefreshTokento returnAuthSuccess(breaking change, document accordingly).Example of an additive API to preserve back-compat:
@useResult static Future<AuthSuccess> rotateTokens( final Session session, { required final String refreshToken, final Transaction? transaction, }) async { final pair = await rotateRefreshToken( session, refreshToken: refreshToken, transaction: transaction, ); // Note: No authUserId/scopeNames here without DB fetch; consider loading the row by id if needed. return AuthSuccess( authStrategy: AuthStrategy.jwt, token: pair.accessToken, refreshToken: pair.refreshToken, // Optionally populate these with a lookup if required for parity: // authUserId: ..., // scopeNames: ..., ); }modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart (3)
174-177: Add an explicit null-check before using refreshToken! to improve failure diagnostics.In case createTokens returns an AuthSuccess without a refresh token (misconfiguration, future behavior changes), the test will throw with a less helpful null-assertion error. Add an expect to make failures clearer.
Apply this diff:
- final newTokenPair = await AuthenticationTokens.rotateRefreshToken( + expect(authSuccess.refreshToken, isNotNull); + final newTokenPair = await AuthenticationTokens.rotateRefreshToken( session, refreshToken: authSuccess.refreshToken!, );Consider applying the same pattern to other refreshToken! usages in this file.
51-56: Update stale test descriptions: replace “TokenPair” with neutral wording.These tests no longer deal with a TokenPair object directly; they use AuthSuccess and then rotate tokens. Updating the description reduces confusion.
Apply this diff:
- withServerpod( - 'Given a valid `TokenPair` for a refresh token with scopes and extra claims,', + withServerpod( + 'Given valid authentication tokens (access + refresh) with scopes and extra claims,',And:
- withServerpod( - 'Given a valid `TokenPair` for a refresh token with scopes and extra claims,', + withServerpod( + 'Given valid authentication tokens (access + refresh) with scopes and extra claims,',Also applies to: 138-147
28-34: Grammar nit: “an non-JWT” → “a non-JWT”.Tiny clarity fix for the test description.
Apply this diff:
- 'when calling the authentication handler with an non-JWT String, then it returns `null`.', + 'when calling the authentication handler with a non-JWT String, then it returns `null`.',modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart (4)
38-39: Avoid asserting exact JSON string ordering for scopeNames; decode and compare as a set.Scope serialization order can be brittle across runtimes. Decode JSON and compare as a set to prevent flaky tests.
Apply this diff:
- expect( - storage.values, - { - SessionManagerStorageKeys.sessionKey.key: _authSuccess.token, - SessionManagerStorageKeys.authUserId.key: - _authSuccess.authUserId.toString(), - SessionManagerStorageKeys.scopeNames.key: '["test1","test2"]' - }, - ); + expect( + storage.values.length, + SessionManagerStorageKeys.values.length, + ); + expect( + storage.values[SessionManagerStorageKeys.sessionKey.key], + _authSuccess.token, + ); + expect( + storage.values[SessionManagerStorageKeys.authUserId.key], + _authSuccess.authUserId.toString(), + ); + final scopesRaw = + storage.values[SessionManagerStorageKeys.scopeNames.key]; + final scopes = (jsonDecode(scopesRaw!) as List).toSet(); + expect(scopes, {'test1', 'test2'});Also add this import at the top of the file:
import 'dart:convert';Also applies to: 48-53
68-69: Same JSON-ordering concern in the “then all keys are present” test.Mirror the safer assertions here too.
Apply this diff:
- expect( - storage.values, - { - SessionManagerStorageKeys.sessionKey.key: _authSuccess.token, - SessionManagerStorageKeys.authUserId.key: - _authSuccess.authUserId.toString(), - SessionManagerStorageKeys.scopeNames.key: '["test1","test2"]' - }, - ); + expect( + storage.values.length, + SessionManagerStorageKeys.values.length, + ); + expect( + storage.values[SessionManagerStorageKeys.sessionKey.key], + _authSuccess.token, + ); + expect( + storage.values[SessionManagerStorageKeys.authUserId.key], + _authSuccess.authUserId.toString(), + ); + final scopesRaw = + storage.values[SessionManagerStorageKeys.scopeNames.key]; + final scopes = (jsonDecode(scopesRaw!) as List).toSet(); + expect(scopes, {'test1', 'test2'});Also applies to: 80-85
121-129: Split expectations across secure vs default storage; decode scopes as above.Preserve the intent but avoid brittle string equality for JSON.
Apply this diff:
- expect( - secureStorage.values, - { - SessionManagerStorageKeys.sessionKey.key: _authSuccess.token, - }, - ); + expect( + secureStorage.values[SessionManagerStorageKeys.sessionKey.key], + _authSuccess.token, + ); - expect( - defaultStorage.values, - { - SessionManagerStorageKeys.authUserId.key: - _authSuccess.authUserId.toString(), - SessionManagerStorageKeys.scopeNames.key: '["test1","test2"]' - }, - ); + expect( + defaultStorage.values[SessionManagerStorageKeys.authUserId.key], + _authSuccess.authUserId.toString(), + ); + final scopesRaw = + defaultStorage.values[SessionManagerStorageKeys.scopeNames.key]; + final scopes = (jsonDecode(scopesRaw!) as List).toSet(); + expect(scopes, {'test1', 'test2'});Also applies to: 130-137
47-53: Optional: Consider aligning naming from “sessionKey” to “token”.The storage key remains SessionManagerStorageKeys.sessionKey. If the public API has moved to token, consider a follow-up deprecation path and migration doc for renaming the storage key to reduce cognitive overhead. Not a blocker.
If you’d like, I can propose a migration plan and a staged deprecation PR for this rename.
Also applies to: 79-85, 131-137
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart (3)
137-139: Add an explicit null-check before using refreshToken!Same rationale as other tests: prefer a clear assertion before using the null-assertion operator.
Apply this diff:
- () => AuthenticationTokens.rotateRefreshToken( - session, - refreshToken: authSuccess.refreshToken!, - ), + () => AuthenticationTokens.rotateRefreshToken( + session, + refreshToken: authSuccess.refreshToken!, + ),And insert above the withClock call:
+ expect(authSuccess.refreshToken, isNotNull);Please replicate this pattern for other refreshToken! usages in this file.
93-100: Update test descriptions to remove “TokenPair” where not accurate anymore.These tests now use AuthSuccess for initial issuance. Consider neutral phrasing.
Apply these diffs:
- test('when requesting a new token pair, then one is returned.', () async { + test('when requesting new authentication tokens, then one is returned.', () async {- withServerpod('Given an initial `TokenPair` and its refreshed successor,', ( + withServerpod('Given initial authentication tokens and their refreshed successor,', (Also applies to: 255-263
174-175: Naming nit: Consider renaming newTokenPair to rotatedTokens.It’s still a TokenPair, but the semantic intent is “rotated” rather than “new”. Readability only.
- final newTokenPair = await AuthenticationTokens.rotateRefreshToken( + final rotatedTokens = await AuthenticationTokens.rotateRefreshToken( session, refreshToken: authSuccess.refreshToken!, );And adjust subsequent references in the test accordingly.
Also applies to: 188-193
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (6)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_client/lib/src/protocol/common/models/auth_strategy.dartis excluded by!**/lib/src/protocol/**modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_client/lib/src/protocol/common/models/auth_success.dartis excluded by!**/lib/src/protocol/**modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_client/lib/src/protocol/protocol.dartis excluded by!**/lib/src/protocol/**modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/generated/common/models/auth_strategy.dartis excluded by!**/generated/**modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/generated/common/models/auth_success.dartis excluded by!**/generated/**modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/generated/protocol.dartis excluded by!**/generated/**
📒 Files selected for processing (13)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart(1 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart(8 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml(1 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml(1 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart(2 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/jwt.dart(1 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart(2 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart(10 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_admin_test.dart(1 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart(13 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart(4 hunks)modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart(3 hunks)tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart(6 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-18T14:49:11.263Z
Learnt from: tp
PR: serverpod/serverpod#3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., `late AuthenticationInfo? authenticationInfo;`) rather than non-nullable ones to avoid using `!` operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when `session.authenticated` returns null.
Applied to files:
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_admin_test.dartmodules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dartmodules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.darttests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dartmodules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dartmodules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dartmodules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart
📚 Learning: 2025-07-15T13:10:16.490Z
Learnt from: tp
PR: serverpod/serverpod#3787
File: modules/new_serverpod_auth/serverpod_auth_apple_account/serverpod_auth_apple_account_server/lib/src/business/apple_accounts.dart:65-67
Timestamp: 2025-07-15T13:10:16.490Z
Learning: In Serverpod Apple authentication, tp prefers adding a `lastRefreshed` field to the database model to track when refresh tokens were last validated, enabling periodic refresh token validation strategy for Apple Sign-In accounts.
Applied to files:
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (35)
- GitHub Check: Bootstrap tests (3.24.0, ubuntu-latest, tests/bootstrap_project)
- GitHub Check: Module integration tests in modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server with Flutter 3.32.1
- GitHub Check: Bootstrap tests (3.32.1, ubuntu-latest, tests/bootstrap_project)
- GitHub Check: Bootstrap tests (3.24.0, windows-latest, tests/bootstrap_project)
- GitHub Check: CLI e2e tests (3.32.1, ubuntu-latest, tests/serverpod_cli_e2e_test)
- GitHub Check: Bootstrap tests (3.32.1, windows-latest, tests/bootstrap_project)
- GitHub Check: Migration e2e tests (3.32.1)
- GitHub Check: CLI e2e tests (3.24.0, ubuntu-latest, tests/serverpod_cli_e2e_test)
- GitHub Check: Serverpod concurrent integration tests (server) (3.32.1)
- GitHub Check: Migration e2e tests (3.24.0)
- GitHub Check: Serverpod integration tests (server) (3.32.1)
- GitHub Check: Serverpod integration tests (server) (3.24.0)
- GitHub Check: Serverpod concurrent integration tests (server) (3.24.0)
- GitHub Check: Module integration tests in tests/serverpod_test_nonvector/serverpod_test_nonvector_server with Flutter 3.24.0
- GitHub Check: Module integration tests in tests/serverpod_test_nonvector/serverpod_test_nonvector_server with Flutter 3.32.1
- GitHub Check: Module integration tests in modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server with Flutter 3.24.0
- GitHub Check: dart analyze downgrade (3.32.1, ubuntu-latest)
- GitHub Check: Flutter unit tests (3.32.1, windows-latest, packages/serverpod_flutter)
- GitHub Check: dart analyze downgrade (3.24.0, windows-latest)
- GitHub Check: Unit tests IO (3.24.0, ubuntu-latest)
- GitHub Check: dart analyze downgrade (3.32.1, windows-latest)
- GitHub Check: Unit tests IO (3.32.1, windows-latest)
- GitHub Check: dart analyze downgrade (3.24.0, ubuntu-latest)
- GitHub Check: Serverpod E2E IO tests (3.24.0)
- GitHub Check: Unit tests IO (3.24.0, windows-latest)
- GitHub Check: Unit tests IO (3.32.1, ubuntu-latest)
- GitHub Check: Serverpod E2E web tests (3.24.0)
- GitHub Check: Serverpod E2E web tests (3.32.1)
- GitHub Check: Unit tests Web (3.32.1, windows-latest)
- GitHub Check: Serverpod E2E IO tests (3.32.1)
- GitHub Check: dart analyze latest (3.32.1, windows-latest)
- GitHub Check: serverpod generate (3.32.1)
- GitHub Check: serverpod generate (3.24.0)
- GitHub Check: dart analyze (3.24.0, windows-latest)
- GitHub Check: dart analyze latest (3.32.1, ubuntu-latest)
🔇 Additional comments (17)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml (2)
2-11: Enum definition looks solid and forward-compatible.byName serialization with a stable, lowercase value set is a good choice. Defaulting to unknown is a safe baseline for extensibility.
3-4: No runtime emission of AuthStrategy.unknown
We’ve confirmed that outside of the generated enum fallback, there are no references to AuthStrategy.unknown in your business logic or serialization flows. All manual assignments in authentication and session code use onlyjwtorsession. Theunknowncase remains solely a safe-generated default for malformed or unexpected values and will not appear in successful authentication responses.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml (1)
2-19: Overall model shape LGTM.Replacing
sessionKeywith a sharedtokenplusauthStrategycleanly unifies the response across auth flows.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1)
84-87: LGTM: PersistingauthSuccess.tokento secure storage is correct.This aligns the Flutter client with the unified
AuthSuccesscontract.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart (4)
62-62: LGTM: Using.tokenfromAuthSessions.createSessionis correct.
135-135: LGTM: Using.tokenfromAuthSessions.createSessionis correct.
174-174: LGTM: Using.tokenfromAuthSessions.createSessionis correct.
235-235: LGTM: Using.tokenfromAuthSessions.createSessionis correct.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart (1)
23-30: Migration to AuthSuccess.token looks correctUsing
.tokenfromAuthSessions.createSession(...)aligns with the new AuthSuccess contract. No issues spotted.tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart (1)
121-126: Token-based assertions: LGTMAll usages migrated to
authSuccess.tokenand validated throughAuthSessions.authenticationHandler(...). Looks consistent across registration, login, and password reset paths.Also applies to: 161-166, 298-303, 372-377
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (2)
118-118: Typo fix in docs: “decommissioned”The correction reads well. Thanks for tightening the docs.
188-196: Returning AuthSuccess with authStrategy=AuthStrategy.session and token=buildSessionKey(): LGTMThe new return shape is coherent with the unified AuthSuccess model and keeps session semantics intact. Scope forwarding and user-blocked check are preserved.
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (2)
94-103: AuthSuccess payload construction: LGTM
authStrategy: AuthStrategy.jwttokenderived from the inserted refresh tokenrefreshTokenstring includedauthUserIdandscopeNamespopulatedThis aligns with the unified token model.
62-75: Verification complete:createTokens→AuthSuccessis safeAll call sites of
AuthenticationTokens.createTokensnow bind to anAuthSuccessand use its.token/.refreshToken, not the old.accessToken. The only remainingTokenPairusages are inrotateRefreshToken, which still returnsTokenPairas intended. No downstream code expects aTokenPairfromcreateTokens.modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart (1)
60-61: Solid migration to AuthSuccess; usages look consistent.createTokens now returns AuthSuccess and the tests correctly read token and (later) refreshToken from it. Access-token validations via authenticationHandler(authSuccess.token) are coherent across tests.
Also applies to: 73-79, 90-91, 103-104, 116-118, 130-131, 206-207
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart (1)
223-229: AuthSuccess usage in the client SessionManager tests looks correct.Passing AuthSuccess to setLoggedIn and validating authInfo/authUserId/scopeNames aligns with the new shared type. The test helper _authSuccess is well-formed.
Also applies to: 317-320
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart (1)
49-57: AuthSuccess adoption for createTokens is correct; field access via token is consistent.Decoding and verifying scopes/claims from authSuccess.token is aligned with the new API.
Also applies to: 65-73
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Just one small variable name detail on a test!
This PR introduces a shared
AuthSuccessclass for all authentication strategies in the new authentication package. This change aims to standardize the response structure for successful authentication across different login mechanisms, making it easier for clients and backend services to consume and handle authentication results consistently.This work is done in preparation for adding a shared configuration to switch authentication strategy on the Server for all providers.
Relates to: #3856
Pre-launch Checklist
///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.If you need help, consider asking for advice on the discussion board.
Breaking changes
Two breaking changes:
sessionKeyfield totoken.AuthenticationTokens.createTokensnow returns anAuthSuccessobject instead of aTokenPair.Summary by CodeRabbit
New Features
Refactor
Tests