Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mobile] Store session tokens in secure storage (#14262)

Rakhul31a12bfbb701
diff --git a/mobile/apps/auth/changes/secure-session-storage.md b/mobile/apps/auth/changes/secure-session-storage.md
new file mode 100644
index 0000000000..321c282a3b
--- /dev/null
+++ b/mobile/apps/auth/changes/secure-session-storage.md
@@ -0,0 +1 @@
+- Moved the session token to secure storage.
diff --git a/mobile/apps/auth/test/core/configuration_token_test.dart b/mobile/apps/auth/test/core/configuration_token_test.dart
new file mode 100644
index 0000000000..fb3345b253
--- /dev/null
+++ b/mobile/apps/auth/test/core/configuration_token_test.dart
@@ -0,0 +1,161 @@
+import 'dart:io';
+
+import 'package:ente_auth/core/configuration.dart';
+import 'package:ente_configuration/base_configuration.dart';
+import 'package:ente_lock_screen/lock_screen_settings.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const secureStorageChannel = MethodChannel(
+ 'plugins.it_nomads.com/flutter_secure_storage',
+ );
+ const pathsChannel = MethodChannel('plugins.flutter.io/path_provider');
+ final messenger =
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
+ final config = Configuration.instance;
+ late Map<String, String> secureValues;
+ late Set<String> failingCalls;
+
+ setUp(() async {
+ secureValues = {};
+ failingCalls = {};
+ final root = await Directory.systemTemp.createTemp('auth_token_');
+ messenger.setMockMethodCallHandler(pathsChannel, (_) async => root.path);
+ messenger.setMockMethodCallHandler(secureStorageChannel, (call) async {
+ final arguments = call.arguments as Map;
+ final key = arguments['key'] as String?;
+ if (failingCalls.contains('${call.method}:$key')) {
+ throw PlatformException(code: 'unavailable');
+ }
+ switch (call.method) {
+ case 'read':
+ return secureValues[key];
+ case 'write':
+ if (!failingCalls.contains('drop:$key')) {
+ secureValues[key!] = arguments['value'] as String;
+ }
+ case 'delete':
+ secureValues.remove(key);
+ case 'containsKey':
+ return secureValues.containsKey(key);
+ }
+ return null;
+ });
+ addTearDown(() async {
+ failingCalls.clear();
+ await config.logout();
+ messenger.setMockMethodCallHandler(secureStorageChannel, null);
+ messenger.setMockMethodCallHandler(pathsChannel, null);
+ await root.delete(recursive: true);
+ });
+ });
+
+ test('moves a plaintext token into secure storage', () async {
+ SharedPreferences.setMockInitialValues({
+ BaseConfiguration.tokenKey: 'token',
+ });
+ secureValues.addAll({
+ BaseConfiguration.keyKey: 'a2V5',
+ Configuration.offlineAuthSecretKey: 'b2ZmbGluZQ==',
+ });
+
+ await config.init([]);
+
+ final preferences = await SharedPreferences.getInstance();
+ expect(config.getToken(), 'token');
+ expect(secureValues[BaseConfiguration.tokenKey], 'token');
+ expect(preferences.getBool(BaseConfiguration.hasSecureTokenKey), true);
+
+ await config.init([]);
+ expect(preferences.containsKey(BaseConfiguration.tokenKey), false);
+ expect(config.getToken(), 'token');
+ expect(secureValues[BaseConfiguration.tokenKey], 'token');
+
+ await config.logout();
+ expect(secureValues.containsKey(BaseConfiguration.tokenKey), false);
+ expect(secureValues[Configuration.offlineAuthSecretKey], 'b2ZmbGluZQ==');
+ });
+
+ test('keeps the session when a token write is lost', () async {
+ SharedPreferences.setMockInitialValues({
+ BaseConfiguration.tokenKey: 'token',
+ BaseConfiguration.userIDKey: 1,
+ });
+ secureValues[BaseConfiguration.keyKey] = 'a2V5';
+ failingCalls.add('drop:${BaseConfiguration.tokenKey}');
+
+ await config.init([]);
+
+ final preferences = await SharedPreferences.getInstance();
+ expect(preferences.containsKey(BaseConfiguration.hasSecureTokenKey), false);
+
+ failingCalls.clear();
+ await config.init([]);
+ secureValues.remove(BaseConfiguration.tokenKey);
+ await config.init([]);
+
+ expect(config.getToken(), 'token');
+ expect(secureValues[BaseConfiguration.tokenKey], 'token');
+ });
+
+ test('trusts a plaintext token written by an older build', () async {
+ SharedPreferences.setMockInitialValues({
+ BaseConfiguration.tokenKey: 'new-token',
+ BaseConfiguration.hasSecureTokenKey: true,
+ });
+ secureValues.addAll({
+ BaseConfiguration.tokenKey: 'old-token',
+ BaseConfiguration.keyKey: 'a2V5',
+ });
+
+ await config.init([]);
+
+ expect(config.getToken(), 'new-token');
+ expect(secureValues[BaseConfiguration.tokenKey], 'new-token');
+ });
+
+ test('clears secure data left by an earlier install', () async {
+ SharedPreferences.setMockInitialValues({});
+ secureValues.addAll({
+ BaseConfiguration.tokenKey: 'old-token',
+ BaseConfiguration.keyKey: 'b2xkLWtleQ==',
+ Configuration.offlineAuthSecretKey: 'b2ZmbGluZQ==',
+ });
+
+ await config.init([]);
+
+ expect(config.isLoggedIn(), false);
+ expect(secureValues.containsKey(BaseConfiguration.tokenKey), false);
+ expect(secureValues[Configuration.offlineAuthSecretKey], 'b2ZmbGluZQ==');
+ });
+
+ test('keeps the session while secure storage is unavailable', () async {
+ SharedPreferences.setMockInitialValues({
+ BaseConfiguration.hasSecureTokenKey: true,
+ BaseConfiguration.userIDKey: 1,
+ });
+ secureValues.addAll({
+ BaseConfiguration.tokenKey: 'token',
+ BaseConfiguration.keyKey: 'a2V5',
+ LockScreenSettings.pin: 'pin-hash',
+ });
+ failingCalls.addAll([
+ 'read:${BaseConfiguration.tokenKey}',
+ 'read:${BaseConfiguration.keyKey}',
+ ]);
+
+ await config.init([]);
+
+ expect(config.isLoggedIn(), true);
+ expect(secureValues[LockScreenSettings.pin], 'pin-hash');
+
+ failingCalls.clear();
+ await config.init([]);
+
+ expect(config.getToken(), 'token');
+ });
+}
diff --git a/mobile/apps/locker/changes/secure-session-storage.md b/mobile/apps/locker/changes/secure-session-storage.md
new file mode 100644
index 0000000000..321c282a3b
--- /dev/null
+++ b/mobile/apps/locker/changes/secure-session-storage.md
@@ -0,0 +1 @@
+- Moved the session token to secure storage.
diff --git a/mobile/apps/locker/lib/services/feature_flag_service.dart b/mobile/apps/locker/lib/services/feature_flag_service.dart
index 3242e9cec0..bd88ee6ce3 100644
--- a/mobile/apps/locker/lib/services/feature_flag_service.dart
+++ b/mobile/apps/locker/lib/services/feature_flag_service.dart
@@ -5,6 +5,7 @@ import "package:ente_events/models/signed_in_event.dart";
import "package:ente_events/models/signed_out_event.dart";
import "package:ente_feature_flag/ente_feature_flag.dart";
import "package:ente_network/network.dart";
+import "package:locker/services/configuration.dart";
import "package:shared_preferences/shared_preferences.dart";
class FeatureFlagService {
@@ -42,6 +43,10 @@ class FeatureFlagService {
}
void _reset() {
- _flagService = FlagService(_preferences, Network.instance.enteDio);
+ _flagService = FlagService(
+ _preferences,
+ Network.instance.enteDio,
+ Configuration.instance.getToken,
+ );
}
}
diff --git a/mobile/apps/photos/changes/secure-session-storage.md b/mobile/apps/photos/changes/secure-session-storage.md
new file mode 100644
index 0000000000..321c282a3b
--- /dev/null
+++ b/mobile/apps/photos/changes/secure-session-storage.md
@@ -0,0 +1 @@
+- Moved the session token to secure storage.
diff --git a/mobile/apps/photos/integration_test/notification_lifecycle_test.dart b/mobile/apps/photos/integration_test/notification_lifecycle_test.dart
index 95b3503419..f41378007b 100644
--- a/mobile/apps/photos/integration_test/notification_lifecycle_test.dart
+++ b/mobile/apps/photos/integration_test/notification_lifecycle_test.dart
@@ -70,7 +70,7 @@ void main() {
testWidgets('fallback is shown when signed in and suppressed after logout', (
tester,
) async {
- await preferences.setString(Configuration.tokenKey, 'test-session');
+ await preferences.setBool(Configuration.hasSecureTokenKey, true);
Future<void> receive() =>
NotificationService.instance.handlePushNotification(
{'notificationCiphertext': 'invalid'},
@@ -85,7 +85,7 @@ void main() {
final rootToken = RootIsolateToken.instance!;
await compute(_clearAccount, rootToken);
- expect(preferences.getString(Configuration.tokenKey), isNotNull);
+ expect(preferences.getBool(Configuration.hasSecureTokenKey), isTrue);
await receive();
await Future<void>.delayed(const Duration(milliseconds: 500));
expect(await notifications.getActiveNotifications(), isEmpty);
@@ -121,8 +121,9 @@ void main() {
);
ServiceLocator.instance.prefs = preferences;
ServiceLocator.instance.enteDio = dio;
- await Configuration.instance.init(preferences);
await preferences.setString(Configuration.tokenKey, 'test-session');
+ await storage.write(key: Configuration.keyKey, value: 'a2V5');
+ await Configuration.instance.init(preferences);
await preferences.setBool('ls.internal_user_disabled', true);
await preferences.setString('remote_flags', '{"internalUser":false}');
expect(flagService.internalUser, isFalse);
diff --git a/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift b/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift
index e8b48bd64a..ee9cf3cec7 100644
--- a/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift
+++ b/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift
@@ -20,13 +20,6 @@ final class NotificationKeyPlugin: NSObject, FlutterPlugin {
Self.queue.async {
do {
let arguments = call.arguments as? [String: Any] ?? [:]
- if call.method == "getPrivateKey" || call.method == "setPrivateKey" {
- guard let token = arguments["sessionToken"] as? String,
- UserDefaults.standard.string(forKey: "flutter.token") == token
- else {
- throw NotificationKeyStore.StoreError.invalidRecord
- }
- }
let response: Any?
switch call.method {
case "getPrivateKey":
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dart
index e004e49b8d..720dee151e 100644
--- a/mobile/apps/photos/lib/core/configuration.dart
+++ b/mobile/apps/photos/lib/core/configuration.dart
@@ -67,6 +67,7 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
static const lastTempFolderClearTimeKey = "last_temp_folder_clear_time";
static const secretKeyKey = "secret_key";
static const tokenKey = "token";
+ static const hasSecureTokenKey = "has_secure_token";
static const encryptedTokenKey = "encrypted_token";
static const userIDKey = "user_id";
static const hasMigratedSecureStorageKey = "has_migrated_secure_storage";
@@ -114,7 +115,28 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
_sharedDocumentsMediaDirectory =
_documentsDirectory + "/ente-shared-media";
Directory(_sharedDocumentsMediaDirectory).createSync(recursive: true);
- if (!_preferences.containsKey(tokenKey)) {
+ _cachedToken = _preferences.getString(tokenKey);
+ if (_cachedToken != null) {
+ try {
+ final storedToken = _preferences.containsKey(hasSecureTokenKey)
+ ? await _secureStorage.read(key: tokenKey)
+ : null;
+ if (storedToken == _cachedToken) {
+ await _preferences.remove(tokenKey);
+ } else {
+ await _storeTokenSecurely(_cachedToken!);
+ }
+ } catch (e, s) {
+ _logger.warning("Failed to move token to secure storage", e, s);
+ }
+ } else if (_preferences.containsKey(hasSecureTokenKey)) {
+ _cachedToken = await _secureStorage.read(key: tokenKey);
+ if (_cachedToken == null) {
+ _logger.warning("No token found in secure storage");
+ await logout(autoLogout: true);
+ }
+ }
+ if (_cachedToken == null) {
_logger.info(
"(for debugging) Token not found, deleting all secure storage data",
);
@@ -221,10 +243,10 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
await _clearTempFolderOnLogout();
+ _cachedToken = null;
await _preferences.clear();
await _secureStorage.deleteAll();
_key = null;
- _cachedToken = null;
_secretKey = null;
_volatilePassword = null;
clearAuthenticatedSession();
@@ -363,7 +385,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
String? getToken() {
- _cachedToken ??= _preferences.getString(tokenKey);
return _cachedToken;
}
@@ -373,13 +394,22 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
Future<void> setToken(String token) async {
+ await _storeTokenSecurely(token);
+ await _preferences.remove(tokenKey);
_cachedToken = token;
- await _preferences.setString(tokenKey, token);
await localSettings.setAppMode(AppMode.enteGallery);
Bus.instance.fire(AppModeChangedEvent());
Bus.instance.fire(SignedInEvent());
}
+ Future<void> _storeTokenSecurely(String token) async {
+ await _secureStorage.write(key: tokenKey, value: token);
+ if (await _secureStorage.read(key: tokenKey) != token) {
+ throw StateError("Token was not saved to secure storage");
+ }
+ await _preferences.setBool(hasSecureTokenKey, true);
+ }
+
Future<void> setEncryptedToken(String encryptedToken) async {
await _preferences.setString(encryptedTokenKey, encryptedToken);
}
diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dart
index 8ecd745f98..f8146f6d9d 100644
--- a/mobile/apps/photos/lib/service_locator.dart
+++ b/mobile/apps/photos/lib/service_locator.dart
@@ -97,6 +97,7 @@ FlagService get flagService {
_flagService ??= FlagService(
ServiceLocator.instance.prefs,
ServiceLocator.instance.enteDio,
+ Configuration.instance.getToken,
);
return _flagService!;
}
diff --git a/mobile/apps/photos/lib/services/notification_key_service.dart b/mobile/apps/photos/lib/services/notification_key_service.dart
index 645ed1b680..029846a3a5 100644
--- a/mobile/apps/photos/lib/services/notification_key_service.dart
+++ b/mobile/apps/photos/lib/services/notification_key_service.dart
@@ -53,10 +53,9 @@ class NotificationKeyService {
static Future<Uint8List?> getNotificationPrivateKey({
String? sessionToken,
}) async {
+ if (Platform.isIOS) await _ensureCurrentSession(sessionToken);
final encoded = Platform.isIOS
- ? await _channel.invokeMethod<String>('getPrivateKey', {
- 'sessionToken': sessionToken ?? Configuration.instance.getToken(),
- })
+ ? await _channel.invokeMethod<String>('getPrivateKey')
: await _storage.read(key: _storageKey);
return encoded == null ? null : base64Decode(encoded);
}
@@ -69,8 +68,8 @@ class NotificationKeyService {
if (privateKey == null) {
await _channel.invokeMethod<void>('clear');
} else {
+ await _ensureCurrentSession(sessionToken);
await _channel.invokeMethod<void>('setPrivateKey', {
- 'sessionToken': sessionToken ?? Configuration.instance.getToken(),
'privateKey': base64Encode(privateKey),
});
}
@@ -82,4 +81,13 @@ class NotificationKeyService {
await _storage.write(key: _storageKey, value: base64Encode(privateKey));
}
}
+
+ static Future<void> _ensureCurrentSession(String? sessionToken) async {
+ final storedToken = await _storage.read(key: Configuration.tokenKey);
+ final currentToken = Configuration.instance.getToken();
+ final token = sessionToken ?? currentToken;
+ if (token == null || token != currentToken || token != storedToken) {
+ throw StateError('Notification key requested for a stale session');
+ }
+ }
}
diff --git a/mobile/apps/photos/lib/services/notification_service.dart b/mobile/apps/photos/lib/services/notification_service.dart
index 3799e171cf..72c6e258f2 100644
--- a/mobile/apps/photos/lib/services/notification_service.dart
+++ b/mobile/apps/photos/lib/services/notification_service.dart
@@ -61,7 +61,10 @@ class NotificationService {
}
if (event == null) {
await _preferences.reload();
- if (_preferences.getString(Configuration.tokenKey) == null) return;
+ if (!_preferences.containsKey(Configuration.hasSecureTokenKey) &&
+ !_preferences.containsKey(Configuration.tokenKey)) {
+ return;
+ }
if (shouldShowNotificationsForSharedPhotosAndAlbums()) {
final strings = await LanguageService.locals;
await showNotification(
diff --git a/mobile/apps/photos/lib/services/push_service.dart b/mobile/apps/photos/lib/services/push_service.dart
index 9ed0f1f145..0002266fd6 100644
--- a/mobile/apps/photos/lib/services/push_service.dart
+++ b/mobile/apps/photos/lib/services/push_service.dart
@@ -88,7 +88,7 @@ class PushService {
: null;
_logger.info("Updating token on server");
await _setPushTokenOnServer(fcmToken, apnsToken);
- if (_prefs.getString(Configuration.tokenKey) != sessionToken) return;
+ if (Configuration.instance.getToken() != sessionToken) return;
await _prefs.setString(kFCMPushToken, fcmToken);
await _prefs.setInt(
kLastFCMTokenUpdationTime,
diff --git a/mobile/apps/photos/test/core/configuration_token_test.dart b/mobile/apps/photos/test/core/configuration_token_test.dart
new file mode 100644
index 0000000000..acc260cdc1
--- /dev/null
+++ b/mobile/apps/photos/test/core/configuration_token_test.dart
@@ -0,0 +1,85 @@
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:photos/core/configuration.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const paths = MethodChannel('plugins.flutter.io/path_provider');
+ final messenger =
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
+
+ setUp(() async {
+ final root = await Directory.systemTemp.createTemp('photos_token_');
+ messenger.setMockMethodCallHandler(paths, (_) async => root.path);
+ addTearDown(() async {
+ messenger.setMockMethodCallHandler(paths, null);
+ await root.delete(recursive: true);
+ });
+ });
+
+ test('keeps the session while secure storage is unavailable', () async {
+ const secureStorage = MethodChannel(
+ 'plugins.it_nomads.com/flutter_secure_storage',
+ );
+ final secureValues = {
+ Configuration.tokenKey: 'token',
+ Configuration.keyKey: 'a2V5',
+ };
+ var isAvailable = false;
+ final changes = <String>[];
+ messenger.setMockMethodCallHandler(secureStorage, (call) async {
+ if (call.method != 'read') {
+ changes.add(call.method);
+ return null;
+ }
+ if (!isAvailable) {
+ throw PlatformException(code: 'unavailable');
+ }
+ return secureValues[(call.arguments as Map)['key']];
+ });
+ addTearDown(() => messenger.setMockMethodCallHandler(secureStorage, null));
+ SharedPreferences.setMockInitialValues({
+ Configuration.hasSecureTokenKey: true,
+ Configuration.userIDKey: 1,
+ });
+ final preferences = await SharedPreferences.getInstance();
+ final config = Configuration.instance;
+
+ await config.init(preferences);
+
+ expect(preferences.getBool(Configuration.hasSecureTokenKey), true);
+
+ isAvailable = true;
+ await config.init(preferences);
+
+ expect(config.getToken(), 'token');
+ expect(changes, isEmpty);
+ });
+
+ test('moves a plaintext token into secure storage', () async {
+ SharedPreferences.setMockInitialValues({Configuration.tokenKey: 'token'});
+ final secureValues = {
+ Configuration.keyKey: 'a2V5',
+ Configuration.secretKeyKey: 'c2VjcmV0',
+ };
+ FlutterSecureStorage.setMockInitialValues(secureValues);
+ final config = Configuration.instance;
+
+ await config.init(await SharedPreferences.getInstance());
+
+ final preferences = await SharedPreferences.getInstance();
+ expect(config.getToken(), 'token');
+ expect(secureValues[Configuration.tokenKey], 'token');
+ expect(preferences.getString(Configuration.tokenKey), 'token');
+
+ await config.init(preferences);
+ expect(preferences.containsKey(Configuration.tokenKey), false);
+ expect(config.getToken(), 'token');
+ expect(secureValues[Configuration.tokenKey], 'token');
+ });
+}
diff --git a/mobile/packages/configuration/lib/base_configuration.dart b/mobile/packages/configuration/lib/base_configuration.dart
index 1916851e01..6bd21b970f 100644
--- a/mobile/packages/configuration/lib/base_configuration.dart
+++ b/mobile/packages/configuration/lib/base_configuration.dart
@@ -28,17 +28,19 @@ abstract class BaseConfiguration {
static const keyKey = "key";
static const secretKeyKey = "secret_key";
static const tokenKey = "token";
+ static const hasSecureTokenKey = "has_secure_token";
static const encryptedTokenKey = "encrypted_token";
static const userIDKey = "user_id";
static const endPointKey = "endpoint";
static const lastTempFolderClearTimeKey = "last_temp_folder_clear_time";
- static const accountSecureStorageKeys = [keyKey, secretKeyKey];
+ static const accountSecureStorageKeys = [keyKey, secretKeyKey, tokenKey];
final kTempFolderDeletionTimeBuffer = const Duration(days: 1).inMicroseconds;
static final _logger = Logger("Configuration");
String? _cachedToken;
+ bool _isTokenUnavailable = false;
late SharedPreferences _preferences;
String? _key;
String? _secretKey;
@@ -76,6 +78,8 @@ abstract class BaseConfiguration {
Future<void> logout({bool autoLogout = false}) async {
await _clearTempFolderOnLogout();
+ _cachedToken = null;
+ _isTokenUnavailable = false;
await _preferences.clear();
await resetSecureStorage();
for (final key in lockScreenSecureStorageKeys) {
@@ -85,7 +89,6 @@ abstract class BaseConfiguration {
await db.clearTable();
}
_key = null;
- _cachedToken = null;
_secretKey = null;
Bus.instance.fire(SignedOutEvent());
}
@@ -131,20 +134,29 @@ abstract class BaseConfiguration {
}
String? getToken() {
- _cachedToken ??= _preferences.getString(tokenKey);
return _cachedToken;
}
bool isLoggedIn() {
- return getToken() != null;
+ return getToken() != null || _isTokenUnavailable;
}
Future<void> setToken(String token) async {
+ await _storeTokenSecurely(token);
+ await _preferences.remove(tokenKey);
_cachedToken = token;
- await _preferences.setString(tokenKey, token);
+ _isTokenUnavailable = false;
Bus.instance.fire(SignedInEvent());
}
+ Future<void> _storeTokenSecurely(String token) async {
+ await _secureStorage.write(key: tokenKey, value: token);
+ if (await _secureStorage.read(key: tokenKey) != token) {
+ throw StateError("Token was not saved to secure storage");
+ }
+ await _preferences.setBool(hasSecureTokenKey, true);
+ }
+
Future<void> setEncryptedToken(String encryptedToken) async {
await _preferences.setString(encryptedTokenKey, encryptedToken);
}
@@ -235,8 +247,35 @@ abstract class BaseConfiguration {
}
Future<void> _setupKeys() async {
+ _isTokenUnavailable = false;
try {
- if (!_preferences.containsKey(tokenKey)) {
+ _cachedToken = _preferences.getString(tokenKey);
+ if (_cachedToken != null) {
+ try {
+ final storedToken = _preferences.containsKey(hasSecureTokenKey)
+ ? await _secureStorage.read(key: tokenKey)
+ : null;
+ if (storedToken == _cachedToken) {
+ await _preferences.remove(tokenKey);
+ } else {
+ await _storeTokenSecurely(_cachedToken!);
+ }
+ } catch (e, s) {
+ _logger.warning("Failed to move token to secure storage", e, s);
+ }
+ } else if (_preferences.containsKey(hasSecureTokenKey)) {
+ try {
+ _cachedToken = await _secureStorage.read(key: tokenKey);
+ } on PlatformException {
+ _isTokenUnavailable = true;
+ rethrow;
+ }
+ if (_cachedToken == null) {
+ _logger.warning("No token found in secure storage");
+ await logout(autoLogout: true);
+ return;
+ }
+ } else {
await resetSecureStorage();
return;
}
diff --git a/mobile/packages/feature_flag/lib/src/flag_service.dart b/mobile/packages/feature_flag/lib/src/flag_service.dart
index 2b2301a423..d91f846de7 100644
--- a/mobile/packages/feature_flag/lib/src/flag_service.dart
+++ b/mobile/packages/feature_flag/lib/src/flag_service.dart
@@ -20,8 +20,9 @@ class FlagService {
final SharedPreferences _prefs;
final Dio _enteDio;
+ final String? Function() _getToken;
- FlagService(this._prefs, this._enteDio) {
+ FlagService(this._prefs, this._enteDio, this._getToken) {
Future.delayed(const Duration(seconds: 5), () {
_fetch();
});
@@ -165,7 +166,7 @@ class FlagService {
int? _fetchUserID;
Future<void> _fetch() async {
- final requestToken = _prefs.getString("token");
+ final requestToken = _getToken();
final requestUserID = _prefs.getInt(_userIdKey);
if (requestToken == null) {
log("token not found, skip", name: "FlagService");
@@ -213,7 +214,7 @@ class FlagService {
}
bool _isCurrentAccount(String token, int? userID) =>
- _prefs.getString("token") == token && _prefs.getInt(_userIdKey) == userID;
+ _getToken() == token && _prefs.getInt(_userIdKey) == userID;
Future<void> _updateKeyValue(String key, String value) async {
try {