Surface involuntary logouts and revalidate the session on app resume

This makes it obvious why users are redirected to the auth screen, since the
snackbar could be easily missed.

See #1265
This commit is contained in:
Roland Geider
2026-07-30 15:47:04 +02:00
parent de40db09f7
commit 914e9ac575
5 changed files with 184 additions and 21 deletions

View File

@@ -22,6 +22,7 @@ import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/widgets.dart' show AppLifecycleListener;
import 'package:flutter_riverpod/flutter_riverpod.dart' show Provider;
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
@@ -644,6 +645,22 @@ class AuthNotifier extends _$AuthNotifier {
}
});
ref.onDispose(sub.cancel);
// A warm resume must also revalidate: the process can stay alive in the
// background for days, so the tokens may have expired without any cold
// start noticing. The app is offline-first, so without this a dead
// session would only surface once some server-backed action happens to
// run. Gated on needsRefresh so quick app switches stay request-free.
final lifecycleListener = AppLifecycleListener(
onResume: () {
final credential = state.asData?.value.credential;
if (credential?.needsRefresh(refreshLeeway) ?? false) {
_logger.fine('revalidation: app resumed with stale access token');
revalidationDone = _revalidate();
}
},
);
ref.onDispose(lifecycleListener.dispose);
}
/// Revalidates the restored session against the server. Fire-and-forget: it
@@ -887,12 +904,15 @@ class AuthNotifier extends _$AuthNotifier {
/// Called from refresh-token failures, repeated 401s on the HTTP
/// client, and revalidation rejections. The UI logout button must use
/// [logout] instead, which performs a full wipe.
Future<void> clearSessionOnly() => _resetSession(wipeLocalData: false);
Future<void> clearSessionOnly() => _resetSession(wipeLocalData: false, sessionExpired: true);
/// Shared body for [logout] and [clearSessionOnly]. PowerSync is touched
/// before the state mutation so a reader observing the post-reset state
/// can never race ahead and re-attach to a DB we're about to wipe.
Future<void> _resetSession({required bool wipeLocalData}) async {
///
/// [sessionExpired] marks the reset as involuntary in the published state,
/// so the login screen can tell the user why they were logged out.
Future<void> _resetSession({required bool wipeLocalData, bool sessionExpired = false}) async {
_logger.fine(wipeLocalData ? 'logging out' : 'clearing session, keeping local DB');
// A failed wipe still logs the user out, but the data is left on disk: the
@@ -910,7 +930,12 @@ class AuthNotifier extends _$AuthNotifier {
await _disconnectPowerSyncIfBuilt();
}
state = AsyncData(AuthState(applicationVersion: _currentOrBlank().applicationVersion));
state = AsyncData(
AuthState(
applicationVersion: _currentOrBlank().applicationVersion,
sessionExpired: sessionExpired,
),
);
if (wipeLocalData) {
await _storage.clearAll();
// Drop the marker only when the data was actually removed, keeping the

View File

@@ -67,6 +67,12 @@ sealed class AuthState with _$AuthState {
String? serverVersion,
PackageInfo? applicationVersion,
@Default(false) bool serverConfigWarning,
/// True when the previous session ended involuntarily (expired or
/// revoked tokens). The login screen shows a hint so the user knows
/// why they have to log in again. Reset by the next login, which
/// builds a fresh state.
@Default(false) bool sessionExpired,
}) = _AuthState;
const AuthState._();

View File

@@ -14,7 +14,11 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$AuthState {
AuthStatus get status; AuthCredential? get credential; String? get serverUrl; String? get serverVersion; PackageInfo? get applicationVersion; bool get serverConfigWarning;
AuthStatus get status; AuthCredential? get credential; String? get serverUrl; String? get serverVersion; PackageInfo? get applicationVersion; bool get serverConfigWarning;/// True when the previous session ended involuntarily (expired or
/// revoked tokens). The login screen shows a hint so the user knows
/// why they have to log in again. Reset by the next login, which
/// builds a fresh state.
bool get sessionExpired;
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -25,16 +29,16 @@ $AuthStateCopyWith<AuthState> get copyWith => _$AuthStateCopyWithImpl<AuthState>
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning));
return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning)&&(identical(other.sessionExpired, sessionExpired) || other.sessionExpired == sessionExpired));
}
@override
int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning);
int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning,sessionExpired);
@override
String toString() {
return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning)';
return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning, sessionExpired: $sessionExpired)';
}
@@ -45,7 +49,7 @@ abstract mixin class $AuthStateCopyWith<$Res> {
factory $AuthStateCopyWith(AuthState value, $Res Function(AuthState) _then) = _$AuthStateCopyWithImpl;
@useResult
$Res call({
AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning
AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired
});
@@ -62,7 +66,7 @@ class _$AuthStateCopyWithImpl<$Res>
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,Object? sessionExpired = null,}) {
return _then(_self.copyWith(
status: null == status ? _self.status : status // ignore: cast_nullable_to_non_nullable
as AuthStatus,credential: freezed == credential ? _self.credential : credential // ignore: cast_nullable_to_non_nullable
@@ -70,6 +74,7 @@ as AuthCredential?,serverUrl: freezed == serverUrl ? _self.serverUrl : serverUrl
as String?,serverVersion: freezed == serverVersion ? _self.serverVersion : serverVersion // ignore: cast_nullable_to_non_nullable
as String?,applicationVersion: freezed == applicationVersion ? _self.applicationVersion : applicationVersion // ignore: cast_nullable_to_non_nullable
as PackageInfo?,serverConfigWarning: null == serverConfigWarning ? _self.serverConfigWarning : serverConfigWarning // ignore: cast_nullable_to_non_nullable
as bool,sessionExpired: null == sessionExpired ? _self.sessionExpired : sessionExpired // ignore: cast_nullable_to_non_nullable
as bool,
));
}
@@ -164,10 +169,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _AuthState() when $default != null:
return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning);case _:
return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning,_that.sessionExpired);case _:
return orElse();
}
@@ -185,10 +190,10 @@ return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersio
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired) $default,) {final _that = this;
switch (_that) {
case _AuthState():
return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning);}
return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning,_that.sessionExpired);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -202,10 +207,10 @@ return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersio
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired)? $default,) {final _that = this;
switch (_that) {
case _AuthState() when $default != null:
return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning);case _:
return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersion,_that.applicationVersion,_that.serverConfigWarning,_that.sessionExpired);case _:
return null;
}
@@ -217,7 +222,7 @@ return $default(_that.status,_that.credential,_that.serverUrl,_that.serverVersio
class _AuthState extends AuthState {
const _AuthState({this.status = AuthStatus.loggedOut, this.credential, this.serverUrl, this.serverVersion, this.applicationVersion, this.serverConfigWarning = false}): super._();
const _AuthState({this.status = AuthStatus.loggedOut, this.credential, this.serverUrl, this.serverVersion, this.applicationVersion, this.serverConfigWarning = false, this.sessionExpired = false}): super._();
@override@JsonKey() final AuthStatus status;
@@ -226,6 +231,11 @@ class _AuthState extends AuthState {
@override final String? serverVersion;
@override final PackageInfo? applicationVersion;
@override@JsonKey() final bool serverConfigWarning;
/// True when the previous session ended involuntarily (expired or
/// revoked tokens). The login screen shows a hint so the user knows
/// why they have to log in again. Reset by the next login, which
/// builds a fresh state.
@override@JsonKey() final bool sessionExpired;
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@@ -237,16 +247,16 @@ _$AuthStateCopyWith<_AuthState> get copyWith => __$AuthStateCopyWithImpl<_AuthSt
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AuthState&&(identical(other.status, status) || other.status == status)&&(identical(other.credential, credential) || other.credential == credential)&&(identical(other.serverUrl, serverUrl) || other.serverUrl == serverUrl)&&(identical(other.serverVersion, serverVersion) || other.serverVersion == serverVersion)&&(identical(other.applicationVersion, applicationVersion) || other.applicationVersion == applicationVersion)&&(identical(other.serverConfigWarning, serverConfigWarning) || other.serverConfigWarning == serverConfigWarning)&&(identical(other.sessionExpired, sessionExpired) || other.sessionExpired == sessionExpired));
}
@override
int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning);
int get hashCode => Object.hash(runtimeType,status,credential,serverUrl,serverVersion,applicationVersion,serverConfigWarning,sessionExpired);
@override
String toString() {
return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning)';
return 'AuthState(status: $status, credential: $credential, serverUrl: $serverUrl, serverVersion: $serverVersion, applicationVersion: $applicationVersion, serverConfigWarning: $serverConfigWarning, sessionExpired: $sessionExpired)';
}
@@ -257,7 +267,7 @@ abstract mixin class _$AuthStateCopyWith<$Res> implements $AuthStateCopyWith<$Re
factory _$AuthStateCopyWith(_AuthState value, $Res Function(_AuthState) _then) = __$AuthStateCopyWithImpl;
@override @useResult
$Res call({
AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning
AuthStatus status, AuthCredential? credential, String? serverUrl, String? serverVersion, PackageInfo? applicationVersion, bool serverConfigWarning, bool sessionExpired
});
@@ -274,7 +284,7 @@ class __$AuthStateCopyWithImpl<$Res>
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? status = null,Object? credential = freezed,Object? serverUrl = freezed,Object? serverVersion = freezed,Object? applicationVersion = freezed,Object? serverConfigWarning = null,Object? sessionExpired = null,}) {
return _then(_AuthState(
status: null == status ? _self.status : status // ignore: cast_nullable_to_non_nullable
as AuthStatus,credential: freezed == credential ? _self.credential : credential // ignore: cast_nullable_to_non_nullable
@@ -282,6 +292,7 @@ as AuthCredential?,serverUrl: freezed == serverUrl ? _self.serverUrl : serverUrl
as String?,serverVersion: freezed == serverVersion ? _self.serverVersion : serverVersion // ignore: cast_nullable_to_non_nullable
as String?,applicationVersion: freezed == applicationVersion ? _self.applicationVersion : applicationVersion // ignore: cast_nullable_to_non_nullable
as PackageInfo?,serverConfigWarning: null == serverConfigWarning ? _self.serverConfigWarning : serverConfigWarning // ignore: cast_nullable_to_non_nullable
as bool,sessionExpired: null == sessionExpired ? _self.sessionExpired : sessionExpired // ignore: cast_nullable_to_non_nullable
as bool,
));
}

View File

@@ -288,6 +288,14 @@ class _AuthCardState extends ConsumerState<AuthCard> {
),
);
// Involuntary logout (expired/revoked tokens): tell the user why they
// are looking at the login form. The transient snackbar shown at the
// moment of the logout is easy to miss, this hint persists until the
// next login.
final sessionExpired = ref.watch(
authProvider.select((s) => s.value?.sessionExpired ?? false),
);
Widget errorMessage = const SizedBox.shrink();
if (_httpError != null) {
errorMessage = FormHttpErrorsWidget(_httpError!);
@@ -322,6 +330,15 @@ class _AuthCardState extends ConsumerState<AuthCard> {
child: AutofillGroup(
child: Column(
children: [
if (sessionExpired && _authMode == AuthMode.login)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Text(
i18n.sessionExpired,
textAlign: TextAlign.center,
style: TextStyle(color: Theme.of(context).colorScheme.primary),
),
),
errorMessage,
if (_useUsernameAndPassword) UsernameField(controller: _usernameController),
if (_authMode == AuthMode.register) EmailField(controller: _emailController),

View File

@@ -22,6 +22,7 @@ import 'dart:io';
import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show AppLifecycleState;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
@@ -1307,6 +1308,109 @@ void main() {
).called(1);
});
});
group('involuntary logout surfacing', () {
String makeJwt(Map<String, dynamic> payload) {
String enc(Map<String, dynamic> m) =>
base64Url.encode(utf8.encode(jsonEncode(m))).replaceAll('=', '');
return '${enc({'alg': 'HS256', 'typ': 'JWT'})}.${enc(payload)}.signature';
}
/// Replaces the legacy seed from setUp with a restored headless-JWT
/// session whose access token expires at [expiresAt].
Future<void> seedJwtSession({required DateTime expiresAt}) async {
final prefs = PreferenceHelper.asyncPref;
await prefs.remove(PREFS_USER);
await prefs.setString(
PREFS_ACCESS_TOKEN,
makeJwt({'sub': '42', 'exp': expiresAt.millisecondsSinceEpoch ~/ 1000}),
);
await prefs.setInt(PREFS_ACCESS_EXPIRES_AT, expiresAt.millisecondsSinceEpoch);
await prefs.setString(PREFS_TOKEN_TYPE, AuthTokenType.headlessJwt.name);
await prefs.setString(PREFS_SERVER_URL, serverUrl);
}
setUp(() async {
await PreferenceHelper.asyncPref.setBool(PREFS_HAS_EVER_SYNCED, true);
});
test('revalidation rejection sets sessionExpired for the login screen', () async {
when(
mockClient.head(tProbe, headers: anyNamed('headers')),
).thenAnswer((_) async => Response('Unauthorized', 401));
final container = makeContainer();
await container.read(authProvider.future);
await container.read(authProvider.notifier).revalidationDone;
final state = container.read(authProvider).value;
expect(state?.status, AuthStatus.loggedOut);
expect(state?.sessionExpired, true);
});
test('user-driven logout does not set sessionExpired', () async {
final container = makeContainer();
await container.read(authProvider.future);
await container.read(authProvider.notifier).revalidationDone;
await container.read(authProvider.notifier).logout();
final state = container.read(authProvider).value;
expect(state?.status, AuthStatus.loggedOut);
expect(state?.sessionExpired, false);
});
test(
'app resume with a stale token revalidates; a rejected refresh ends the session',
() async {
// The access token expires inside the pre-emptive refresh leeway, so
// the startup revalidation and the resume hook both treat it as stale.
final expiry = DateTime.now().add(const Duration(seconds: 10));
await seedJwtSession(expiresAt: expiry);
when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'stored-refresh');
// Startup revalidation refreshes successfully; the minted token is
// again short-lived so the resume hook sees it as stale too.
final freshJwt = makeJwt({'sub': '42', 'exp': expiry.millisecondsSinceEpoch ~/ 1000});
when(
mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
).thenAnswer(
(_) async => Response(
jsonEncode({
'status': 200,
'data': {'access_token': freshJwt, 'refresh_token': 'rotated'},
}),
200,
),
);
final container = makeContainer();
await container.read(authProvider.future);
await container.read(authProvider.notifier).revalidationDone;
expect(container.read(authProvider).value?.status, AuthStatus.loggedIn);
// The server now rejects the refresh token (expired server-side).
when(
mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
).thenAnswer((_) async => Response('{"status": 400}', 400));
// Background -> foreground transition must trigger the resume hook.
// The intermediate states mirror what the engine dispatches; jumping
// straight to resumed would violate AppLifecycleListener's asserts.
final binding = TestWidgetsFlutterBinding.instance;
binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await container.read(authProvider.notifier).revalidationDone;
final state = container.read(authProvider).value;
expect(state?.status, AuthStatus.loggedOut);
expect(state?.sessionExpired, true);
},
);
});
}
/// Connectivity stub backed by a caller-controlled stream so reconnect events