Merge branch 'soru/better-use-secret-store' into 'main'

fix: overgo issues with flutter_secure_store

See merge request ChristianPauly/fluffychat-flutter!213
This commit is contained in:
Christian Pauly 2020-10-08 08:23:29 +00:00
commit 4a5468151a
2 changed files with 34 additions and 2 deletions

View file

@ -175,7 +175,7 @@ class ThemeSwitcherWidgetState extends State<ThemeSwitcherWidget> {
BuildContext context; BuildContext context;
Future loadSelection(MatrixState matrix) async { Future loadSelection(MatrixState matrix) async {
String item = await matrix.store.getItem('theme') ?? 'light'; String item = await matrix.store.getItem('theme') ?? 'system';
selectedTheme = Themes.values.firstWhere( selectedTheme = Themes.values.firstWhere(
(e) => e.toString() == 'Themes.' + item, (e) => e.toString() == 'Themes.' + item,
orElse: () => Themes.system); orElse: () => Themes.system);

View file

@ -199,9 +199,30 @@ Future<void> migrate(String clientName, Database db, Store store) async {
}); });
} }
// see https://github.com/mogol/flutter_secure_storage/issues/161#issuecomment-704578453
class AsyncMutex {
Completer<void> _completer;
Future<void> lock() async {
while (_completer != null) {
await _completer.future;
}
_completer = Completer<void>();
}
void unlock() {
assert(_completer != null);
final completer = _completer;
_completer = null;
completer.complete();
}
}
class Store { class Store {
final LocalStorage storage; final LocalStorage storage;
final FlutterSecureStorage secureStorage; final FlutterSecureStorage secureStorage;
static final _mutex = AsyncMutex();
Store() Store()
: storage = LocalStorage('LocalStorage'), : storage = LocalStorage('LocalStorage'),
@ -217,9 +238,12 @@ class Store {
} }
} }
try { try {
await _mutex.lock();
return await secureStorage.read(key: key); return await secureStorage.read(key: key);
} catch (_) { } catch (_) {
return null; return null;
} finally {
_mutex.unlock();
} }
} }
@ -231,7 +255,12 @@ class Store {
if (value == null) { if (value == null) {
return await secureStorage.delete(key: key); return await secureStorage.delete(key: key);
} else { } else {
try {
await _mutex.lock();
return await secureStorage.write(key: key, value: value); return await secureStorage.write(key: key, value: value);
} finally {
_mutex.unlock();
}
} }
} }
@ -245,9 +274,12 @@ class Store {
} }
} }
try { try {
await _mutex.lock();
return await secureStorage.readAll(); return await secureStorage.readAll();
} catch (_) { } catch (_) {
return {}; return {};
} finally {
_mutex.unlock();
} }
} }
} }