Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/gotrue/lib/gotrue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ export 'src/helper.dart' show decodeJwt, validateExp;
export 'src/types/auth_exception.dart';
export 'src/types/auth_response.dart' hide ToSnakeCase;
export 'src/types/auth_state.dart';
export 'src/types/error_code.dart';
export 'src/types/gotrue_async_storage.dart';
export 'src/types/jwt.dart';
export 'src/gotrue_admin_passkey_api.dart';
export 'src/types/mfa.dart';
export 'src/types/passkey.dart';
export 'src/types/sign_out_reason.dart';
export 'src/types/types.dart';
export 'src/types/session.dart';
export 'src/types/user.dart';
Expand Down
60 changes: 50 additions & 10 deletions packages/gotrue/lib/src/gotrue_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -962,7 +962,13 @@ class GoTrueClient {
/// [scope] determines which sessions should be logged out.
///
/// If using [SignOutScope.others] scope, no [AuthChangeEvent.signedOut] event is fired!
Future<void> signOut({SignOutScope scope = SignOutScope.local}) async {
Future<void> signOut({SignOutScope scope = SignOutScope.local}) =>
_signOut(scope: scope, reason: SignOutReason.userInitiated);

Future<void> _signOut({
required SignOutScope scope,
required SignOutReason reason,
}) async {
_log.info('Signing out user with scope: ${scope.name}');
final accessToken = currentSession?.accessToken;

Expand All @@ -971,7 +977,10 @@ class GoTrueClient {
await _asyncStorage?.removeItem(
key: '${Constants.defaultStorageKey}-code-verifier',
);
notifyAllSubscribers(AuthChangeEvent.signedOut);
notifyAllSubscribers(
AuthChangeEvent.signedOut,
signOutReason: reason,
);
}

if (accessToken != null) {
Expand Down Expand Up @@ -1129,8 +1138,16 @@ class GoTrueClient {
final session = Session.fromJson(json.decode(jsonStr));
if (session == null) {
// sign out to delete the local storage from supabase_flutter
await signOut();
throw notifyException(AuthException('Initial session is missing data.'));
await _signOut(
scope: SignOutScope.local,
reason: SignOutReason.sessionMissing,
);
throw notifyException(
AuthException(
'Initial session is missing data.',
code: ErrorCode.sessionMissing.code,
),
);
}

_currentSession = session;
Expand All @@ -1143,9 +1160,15 @@ class GoTrueClient {
final session = Session.fromJson(json.decode(jsonStr));
if (session == null) {
_log.warning("Can't recover session from string, session is null");
await signOut();
await _signOut(
scope: SignOutScope.local,
reason: SignOutReason.sessionMissing,
);
throw notifyException(
AuthException('Current session is missing data.'),
AuthException(
'Current session is missing data.',
code: ErrorCode.sessionMissing.code,
),
);
}

Expand All @@ -1165,8 +1188,16 @@ class GoTrueClient {
if (_autoRefreshToken && refreshToken != null) {
return await _callRefreshToken(refreshToken);
}
await signOut();
throw notifyException(AuthException('Session expired.'));
await _signOut(
scope: SignOutScope.local,
reason: SignOutReason.sessionExpired,
);
throw notifyException(
AuthException(
'Session expired.',
code: ErrorCode.sessionExpired.code,
),
);
}
final shouldEmitEvent = _currentSession == null ||
_currentSession!.user.id != session.user.id;
Expand Down Expand Up @@ -1495,7 +1526,10 @@ class GoTrueClient {
// user who just signed in.
if (!_isDisposed && _sessionVersion == versionBeforeRefresh) {
_removeSession();
notifyAllSubscribers(AuthChangeEvent.signedOut);
notifyAllSubscribers(
AuthChangeEvent.signedOut,
signOutReason: SignOutReason.sessionExpired,
);
}
} else if (!_isDisposed) {
notifyException(error, stack);
Expand Down Expand Up @@ -1525,6 +1559,7 @@ class GoTrueClient {
AuthChangeEvent event, {
Session? session,
bool broadcast = true,
SignOutReason? signOutReason,
}) {
session ??= currentSession;
if (broadcast && event != AuthChangeEvent.initialSession) {
Expand All @@ -1533,7 +1568,12 @@ class GoTrueClient {
'session': session?.toJson(),
});
}
final state = AuthState(event, session, fromBroadcast: !broadcast);
final state = AuthState(
event,
session,
fromBroadcast: !broadcast,
signOutReason: signOutReason,
);
_log.finest('onAuthStateChange: $state');
_onAuthStateChangeController.add(state);
_onAuthStateChangeControllerSync.add(state);
Expand Down
19 changes: 17 additions & 2 deletions packages/gotrue/lib/src/types/auth_state.dart
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
import 'package:gotrue/src/constants.dart';
import 'package:gotrue/src/types/session.dart';
import 'package:gotrue/src/types/sign_out_reason.dart';

class AuthState {
final AuthChangeEvent event;
final Session? session;

/// Why the user was signed out, when [event] is
/// [AuthChangeEvent.signedOut].
///
/// Lets listeners tell an explicit sign out apart from an involuntary one
/// (such as an expired session). It is `null` for every other event and for
/// `signedOut` events received from another tab via `web.BroadcastChannel`.
final SignOutReason? signOutReason;

/// Whether this state was broadcasted via `web.BroadcastChannel` on web from
/// another tab or window.
final bool fromBroadcast;

const AuthState(this.event, this.session, {this.fromBroadcast = false});
const AuthState(
this.event,
this.session, {
this.fromBroadcast = false,
this.signOutReason,
});

@override
String toString() {
return 'AuthState(event: ${event.name}, session: $session, fromBroadcast: $fromBroadcast)';
return 'AuthState(event: ${event.name}, session: $session, '
'fromBroadcast: $fromBroadcast, signOutReason: $signOutReason)';
}
}
2 changes: 2 additions & 0 deletions packages/gotrue/lib/src/types/error_code.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ enum ErrorCode {
noAuthorization('no_authorization'),
userNotFound('user_not_found'),
sessionNotFound('session_not_found'),
sessionExpired('session_expired'),
sessionMissing('session_missing'),
flowStateNotFound('flow_state_not_found'),
flowStateExpired('flow_state_expired'),
signupDisabled('signup_disabled'),
Expand Down
17 changes: 17 additions & 0 deletions packages/gotrue/lib/src/types/sign_out_reason.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/// The reason why an [AuthChangeEvent.signedOut] event was emitted.
///
/// Available on [AuthState.signOutReason] and lets listeners distinguish an
/// explicit sign out from an involuntary one, such as an expired session,
/// without inspecting error messages.
enum SignOutReason {
/// The user explicitly signed out by calling [GoTrueClient.signOut].
userInitiated,

/// The session could no longer be refreshed because its refresh token was
/// rejected (invalid or expired), so the session was removed.
sessionExpired,

/// A stored session could not be recovered because it was missing required
/// data, so the session was removed.
sessionMissing,
}
1 change: 0 additions & 1 deletion packages/gotrue/test/client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import 'dart:convert';

import 'package:dotenv/dotenv.dart';
import 'package:gotrue/gotrue.dart';
import 'package:gotrue/src/types/error_code.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:jwt_decode/jwt_decode.dart';
Expand Down
71 changes: 65 additions & 6 deletions packages/gotrue/test/src/token_refresh_race_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -302,15 +302,13 @@ void main() {

test('signOut event is emitted when refresh fails and session is unchanged',
() async {
final events = <AuthChangeEvent>[];
client.onAuthStateChange.listen((state) {
events.add(state.event);
});
final states = <AuthState>[];
client.onAuthStateChange.listen(states.add);

// Set an initial session.
final freshAt = _freshAccessToken();
await client.setSession('initial-token', accessToken: freshAt);
events.clear();
states.clear();

// Now make a refresh that will fail with a non-retryable error.
mockClient.tokenStatusOverride = 400;
Expand All @@ -321,7 +319,68 @@ void main() {

// Without any concurrent session changes, the failure should sign out.
expect(client.currentSession, isNull);
expect(events, contains(AuthChangeEvent.signedOut));
final signedOut = states.firstWhere(
(state) => state.event == AuthChangeEvent.signedOut,
);
expect(signedOut.signOutReason, SignOutReason.sessionExpired);
});

test('explicit signOut reports a userInitiated reason', () async {
final states = <AuthState>[];
client.onAuthStateChange.listen(states.add);

final freshAt = _freshAccessToken();
await client.setSession('initial-token', accessToken: freshAt);
states.clear();

await client.signOut();

final signedOut = states.firstWhere(
(state) => state.event == AuthChangeEvent.signedOut,
);
expect(signedOut.signOutReason, SignOutReason.userInitiated);
});

test('recoverSession with an expired session reports sessionExpired',
() async {
final states = <AuthState>[];
// recoverSession also surfaces the failure as a stream error, which we
// ignore here since we only assert on the emitted signedOut state.
client.onAuthStateChange.listen(states.add, onError: (_) {});

// Build an expired session string. With autoRefreshToken disabled it
// cannot be refreshed, so recovery signs the user out.
final expiredAt = _makeRawJwt({
'exp': DateTime.now().millisecondsSinceEpoch ~/ 1000 - 3600,
'iat': DateTime.now().millisecondsSinceEpoch ~/ 1000 - 7200,
'sub': 'mock-user-id',
});
final expiredSession = jsonEncode({
'access_token': expiredAt,
'token_type': 'bearer',
'expires_in': -3600,
'refresh_token': 'expired-refresh-token',
'user': _mockUserJson,
});

await expectLater(
client.recoverSession(expiredSession),
throwsA(
isA<AuthException>().having(
(error) => error.code,
'code',
ErrorCode.sessionExpired.code,
),
),
);

// Let the asynchronous state event flush before asserting.
await Future<void>.delayed(Duration.zero);

final signedOut = states.firstWhere(
(state) => state.event == AuthChangeEvent.signedOut,
);
expect(signedOut.signOutReason, SignOutReason.sessionExpired);
});
});
}
Loading