From d94f0d73516f51c28dfd81201ab2165d3740b92a Mon Sep 17 00:00:00 2001 From: Sorunome Date: Wed, 3 Feb 2021 14:50:03 +0100 Subject: [PATCH] fix: SecureStorage sometimes reading wrong / bad values --- lib/utils/famedlysdk_store.dart | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/utils/famedlysdk_store.dart b/lib/utils/famedlysdk_store.dart index e59c621e..53d771e1 100644 --- a/lib/utils/famedlysdk_store.dart +++ b/lib/utils/famedlysdk_store.dart @@ -40,9 +40,30 @@ Future getDatabase(Client client) async { Database _db; bool _generateDatabaseLock = false; +// see https://github.com/mogol/flutter_secure_storage/issues/161#issuecomment-704578453 +class AsyncMutex { + Completer _completer; + + Future lock() async { + while (_completer != null) { + await _completer.future; + } + + _completer = Completer(); + } + + void unlock() { + assert(_completer != null); + final completer = _completer; + _completer = null; + completer.complete(); + } +} + class Store { LocalStorage storage; final FlutterSecureStorage secureStorage; + static final _mutex = AsyncMutex(); Store() : secureStorage = PlatformInfos.isMobile ? FlutterSecureStorage() : null; @@ -69,6 +90,7 @@ class Store { } } try { + await _mutex.lock(); return await secureStorage.read(key: key); } catch (_) { return null; @@ -89,6 +111,7 @@ class Store { await _setupLocalStorage(); return await storage.setItem(key, value); } + await _mutex.lock(); return await secureStorage.write(key: key, value: value); } @@ -101,6 +124,7 @@ class Store { await _setupLocalStorage(); return await storage.deleteItem(key); } + await _mutex.lock(); return await secureStorage.delete(key: key); } }