Throw exception if the db could not be wiped on logout

This commit is contained in:
Roland Geider
2026-06-05 12:53:41 +02:00
parent b7674aaf41
commit 41bb7d39d7
3 changed files with 171 additions and 56 deletions

View File

@@ -853,14 +853,31 @@ class AuthNotifier extends _$AuthNotifier {
/// can never race ahead and re-attach to a DB we're about to wipe.
Future<void> _resetSession({required bool wipeLocalData}) async {
_logger.fine(wipeLocalData ? 'logging out' : 'clearing session, keeping local DB');
await (wipeLocalData ? _wipeLocalDb() : _disconnectPowerSyncIfBuilt());
// A failed wipe still logs the user out, but the data is left on disk: the
// owner marker must then survive so a later different user is detected as a
// switch and re-wipes, rather than docking onto the leftover data.
var wiped = true;
if (wipeLocalData) {
try {
await _wipeLocalDb();
} catch (e, s) {
_logger.severe('logout wipe failed, keeping owner marker', e, s);
wiped = false;
}
} else {
await _disconnectPowerSyncIfBuilt();
}
state = AsyncData(AuthState(applicationVersion: _currentOrBlank().applicationVersion));
if (wipeLocalData) {
await _storage.clearAll();
// The wipe above removed the data (built DB or on-disk file), so the
// owner marker is reset to keep the "null marker ⟺ no data" invariant.
// Kept on the credentials-only path so a returning user is recognised.
await _storage.setDbOwnerUserId(null);
// Drop the marker only when the data was actually removed, keeping the
// "null marker ⟺ no data" invariant. Kept on the credentials-only path
// so a returning user is recognised.
if (wiped) {
await _storage.setDbOwnerUserId(null);
}
} else {
await _storage.clearCredentials();
}
@@ -891,20 +908,25 @@ class AuthNotifier extends _$AuthNotifier {
/// when the instance exists we use PowerSync's own [disconnectAndClear],
/// otherwise (cold start, before any data widget has built it) we delete
/// the on-disk files directly so no data survives.
///
/// Throws if the wipe fails. Callers must abort before advancing the DB
/// owner marker, otherwise the previous user's data stay on disk
Future<void> _wipeLocalDb() async {
final db = builtPowerSyncInstance;
if (db != null) {
try {
await db.disconnectAndClear();
} catch (e, s) {
_logger.warning('local DB wipe via disconnectAndClear failed', e, s);
_logger.severe('local DB wipe via disconnectAndClear failed', e, s);
rethrow;
}
return;
}
try {
await deletePowerSyncDatabaseFile();
} catch (e, s) {
_logger.warning('local DB wipe via file delete failed', e, s);
_logger.severe('local DB wipe via file delete failed', e, s);
rethrow;
}
}

View File

@@ -3,14 +3,16 @@
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:convert' as _i4;
import 'dart:typed_data' as _i6;
import 'dart:async' as _i4;
import 'dart:convert' as _i5;
import 'dart:typed_data' as _i7;
import 'package:http/http.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i5;
import 'package:wger/providers/secure_token_storage.dart' as _i7;
import 'package:mockito/src/dummies.dart' as _i6;
import 'package:wger/models/user/account.dart' as _i3;
import 'package:wger/providers/account_repository.dart' as _i9;
import 'package:wger/providers/secure_token_storage.dart' as _i8;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
@@ -36,6 +38,10 @@ class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedRespo
: super(parent, parentInvocation);
}
class _FakeAccount_2 extends _i1.SmartFake implements _i3.Account {
_FakeAccount_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation);
}
/// A class which mocks [Client].
///
/// See the documentation for Mockito's code generation for more information.
@@ -45,37 +51,37 @@ class MockClient extends _i1.Mock implements _i2.Client {
}
@override
_i3.Future<_i2.Response> head(Uri? url, {Map<String, String>? headers}) =>
_i4.Future<_i2.Response> head(Uri? url, {Map<String, String>? headers}) =>
(super.noSuchMethod(
Invocation.method(#head, [url], {#headers: headers}),
returnValue: _i3.Future<_i2.Response>.value(
returnValue: _i4.Future<_i2.Response>.value(
_FakeResponse_0(
this,
Invocation.method(#head, [url], {#headers: headers}),
),
),
)
as _i3.Future<_i2.Response>);
as _i4.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> get(Uri? url, {Map<String, String>? headers}) =>
_i4.Future<_i2.Response> get(Uri? url, {Map<String, String>? headers}) =>
(super.noSuchMethod(
Invocation.method(#get, [url], {#headers: headers}),
returnValue: _i3.Future<_i2.Response>.value(
returnValue: _i4.Future<_i2.Response>.value(
_FakeResponse_0(
this,
Invocation.method(#get, [url], {#headers: headers}),
),
),
)
as _i3.Future<_i2.Response>);
as _i4.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> post(
_i4.Future<_i2.Response> post(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
_i5.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
@@ -83,7 +89,7 @@ class MockClient extends _i1.Mock implements _i2.Client {
[url],
{#headers: headers, #body: body, #encoding: encoding},
),
returnValue: _i3.Future<_i2.Response>.value(
returnValue: _i4.Future<_i2.Response>.value(
_FakeResponse_0(
this,
Invocation.method(
@@ -94,14 +100,14 @@ class MockClient extends _i1.Mock implements _i2.Client {
),
),
)
as _i3.Future<_i2.Response>);
as _i4.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> put(
_i4.Future<_i2.Response> put(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
_i5.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
@@ -109,7 +115,7 @@ class MockClient extends _i1.Mock implements _i2.Client {
[url],
{#headers: headers, #body: body, #encoding: encoding},
),
returnValue: _i3.Future<_i2.Response>.value(
returnValue: _i4.Future<_i2.Response>.value(
_FakeResponse_0(
this,
Invocation.method(
@@ -120,14 +126,14 @@ class MockClient extends _i1.Mock implements _i2.Client {
),
),
)
as _i3.Future<_i2.Response>);
as _i4.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> patch(
_i4.Future<_i2.Response> patch(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
_i5.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
@@ -135,7 +141,7 @@ class MockClient extends _i1.Mock implements _i2.Client {
[url],
{#headers: headers, #body: body, #encoding: encoding},
),
returnValue: _i3.Future<_i2.Response>.value(
returnValue: _i4.Future<_i2.Response>.value(
_FakeResponse_0(
this,
Invocation.method(
@@ -146,14 +152,14 @@ class MockClient extends _i1.Mock implements _i2.Client {
),
),
)
as _i3.Future<_i2.Response>);
as _i4.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> delete(
_i4.Future<_i2.Response> delete(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
_i5.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
@@ -161,7 +167,7 @@ class MockClient extends _i1.Mock implements _i2.Client {
[url],
{#headers: headers, #body: body, #encoding: encoding},
),
returnValue: _i3.Future<_i2.Response>.value(
returnValue: _i4.Future<_i2.Response>.value(
_FakeResponse_0(
this,
Invocation.method(
@@ -172,44 +178,44 @@ class MockClient extends _i1.Mock implements _i2.Client {
),
),
)
as _i3.Future<_i2.Response>);
as _i4.Future<_i2.Response>);
@override
_i3.Future<String> read(Uri? url, {Map<String, String>? headers}) =>
_i4.Future<String> read(Uri? url, {Map<String, String>? headers}) =>
(super.noSuchMethod(
Invocation.method(#read, [url], {#headers: headers}),
returnValue: _i3.Future<String>.value(
_i5.dummyValue<String>(
returnValue: _i4.Future<String>.value(
_i6.dummyValue<String>(
this,
Invocation.method(#read, [url], {#headers: headers}),
),
),
)
as _i3.Future<String>);
as _i4.Future<String>);
@override
_i3.Future<_i6.Uint8List> readBytes(
_i4.Future<_i7.Uint8List> readBytes(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(#readBytes, [url], {#headers: headers}),
returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)),
returnValue: _i4.Future<_i7.Uint8List>.value(_i7.Uint8List(0)),
)
as _i3.Future<_i6.Uint8List>);
as _i4.Future<_i7.Uint8List>);
@override
_i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) =>
_i4.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) =>
(super.noSuchMethod(
Invocation.method(#send, [request]),
returnValue: _i3.Future<_i2.StreamedResponse>.value(
returnValue: _i4.Future<_i2.StreamedResponse>.value(
_FakeStreamedResponse_1(
this,
Invocation.method(#send, [request]),
),
),
)
as _i3.Future<_i2.StreamedResponse>);
as _i4.Future<_i2.StreamedResponse>);
@override
void close() => super.noSuchMethod(
@@ -221,34 +227,71 @@ class MockClient extends _i1.Mock implements _i2.Client {
/// A class which mocks [SecureTokenStorage].
///
/// See the documentation for Mockito's code generation for more information.
class MockSecureTokenStorage extends _i1.Mock implements _i7.SecureTokenStorage {
class MockSecureTokenStorage extends _i1.Mock implements _i8.SecureTokenStorage {
MockSecureTokenStorage() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> writeRefreshToken(String? token) =>
_i4.Future<void> writeRefreshToken(String? token) =>
(super.noSuchMethod(
Invocation.method(#writeRefreshToken, [token]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i3.Future<void>);
as _i4.Future<void>);
@override
_i3.Future<String?> readRefreshToken() =>
_i4.Future<String?> readRefreshToken() =>
(super.noSuchMethod(
Invocation.method(#readRefreshToken, []),
returnValue: _i3.Future<String?>.value(),
returnValue: _i4.Future<String?>.value(),
)
as _i3.Future<String?>);
as _i4.Future<String?>);
@override
_i3.Future<void> deleteRefreshToken() =>
_i4.Future<void> deleteRefreshToken() =>
(super.noSuchMethod(
Invocation.method(#deleteRefreshToken, []),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i3.Future<void>);
as _i4.Future<void>);
}
/// A class which mocks [AccountRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockAccountRepository extends _i1.Mock implements _i9.AccountRepository {
MockAccountRepository() {
_i1.throwOnMissingStub(this);
}
@override
_i4.Future<_i3.Account> fetchAccount() =>
(super.noSuchMethod(
Invocation.method(#fetchAccount, []),
returnValue: _i4.Future<_i3.Account>.value(
_FakeAccount_2(this, Invocation.method(#fetchAccount, [])),
),
)
as _i4.Future<_i3.Account>);
@override
_i4.Future<void> requestEmailChange(String? newEmail) =>
(super.noSuchMethod(
Invocation.method(#requestEmailChange, [newEmail]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
@override
_i4.Future<void> resendVerification(String? email) =>
(super.noSuchMethod(
Invocation.method(#resendVerification, [email]),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
)
as _i4.Future<void>);
}

View File

@@ -59,6 +59,13 @@ void main() {
late MockClient mockClient;
late MockSecureTokenStorage mockSecureStorage;
// Backing dir for the on-disk PowerSync wipe path (instance never built in
// these tests). When [failDbPathLookup] is set, the path lookup throws so
// tests can exercise a failed wipe.
late Directory tmpDir;
var failDbPathLookup = false;
const pathProviderChannel = MethodChannel('plugins.flutter.io/path_provider');
const serverUrl = 'https://wger.example';
const token = 'token-12345';
const powerSyncUrl = 'https://ps.example/';
@@ -103,6 +110,25 @@ void main() {
buildSignature: 'buildSignature',
);
// Point the on-disk wipe path at a real temp dir so a wiping logout
// succeeds (no file present -> no-op). Set [failDbPathLookup] to make the
// lookup throw and exercise a failed wipe.
failDbPathLookup = false;
tmpDir = Directory.systemTemp.createTempSync('wger_ps_auth');
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(pathProviderChannel, (call) async {
if (failDbPathLookup) {
throw PlatformException(code: 'unavailable', message: 'simulated path lookup failure');
}
return call.method == 'getApplicationSupportDirectory' ? tmpDir.path : null;
});
addTearDown(() {
messenger.setMockMethodCallHandler(pathProviderChannel, null);
if (tmpDir.existsSync()) {
tmpDir.deleteSync(recursive: true);
}
});
// Wipe async prefs between tests (the platform instance is shared).
final prefs = PreferenceHelper.asyncPref;
await prefs.clear();
@@ -600,6 +626,30 @@ void main() {
expect(dbFile.existsSync(), false, reason: 'on-disk DB must be wiped on logout');
expect(await prefs.containsKey(PREFS_DB_OWNER_USER_ID), false);
});
test('a failed wipe keeps the owner marker so a different user still wipes', () async {
// If the wipe fails the data is still on disk under the old owner, so the
// marker must NOT be reset to null: otherwise a different user signing in
// later would dock onto the previous user's data instead of wiping it.
final prefs = PreferenceHelper.asyncPref;
await prefs.setString(PREFS_DB_OWNER_USER_ID, '7');
// Logout keeps the local DB by default; opt out so the wipe is attempted.
await prefs.setBool(PREFS_KEEP_DATA_ON_LOGOUT, false);
final container = makeContainer();
await container.read(authProvider.future);
await container.read(authProvider.notifier).revalidationDone;
// Make the on-disk wipe fail.
failDbPathLookup = true;
await container.read(authProvider.notifier).logout();
// Credentials are still cleared (the user logged out), but the marker
// survives because the data was not actually removed.
expect(container.read(authProvider).value?.status, AuthStatus.loggedOut);
expect(await prefs.containsKey(PREFS_USER), false);
expect(await prefs.getString(PREFS_DB_OWNER_USER_ID), '7');
});
});
group('logout: keep-data-on-logout setting', () {