A cross platform Audiobookshelf client for Android and iOS
Dart
Add unlink OpenID and editing a saved server's address
Barnabas42b4e57e5e58
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex 7c5051c2..607c7aa7 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -955,6 +955,44 @@ class AuthProvider extends ChangeNotifier {return true;}+ /// Change the server URL of a saved account in place (e.g. a dynamic-DNS+ /// hostname changed) without re-adding it. The account's per-user data is+ /// migrated to the new scope by [UserAccountService.updateAccountUrl]. If the+ /// edited account is the live session, its URL is updated immediately so the+ /// next API call (and the [apiService] getter) uses the new address.+ /// Returns true if the account was found and updated.+ Future<bool> editServerUrl(SavedAccount account, String newServerUrl) async {+ // Normalize the same way login() does.+ String url = newServerUrl.trim();+ if (url.isEmpty) return false;+ if (!url.startsWith('http://') && !url.startsWith('https://')) {+ url = 'http://$url';+ }+ if (url.endsWith('/')) {+ url = url.substring(0, url.length - 1);+ }+ if (url == account.serverUrl) return true; // nothing to change++ final ok = await UserAccountService()+ .updateAccountUrl(account.serverUrl, account.username, url);+ if (!ok) return false;++ // If we just edited the currently active session, update it live.+ final isActiveSession =+ account.serverUrl == _serverUrl && account.username == _username;+ if (isActiveSession) {+ _serverUrl = url;+ _serverReachable = true;+ try {+ final prefs = await SharedPreferences.getInstance();+ await prefs.setString('server_url', url);+ } catch (_) {}+ _pushSessionToWear();+ notifyListeners();+ }+ return true;+ }+/// Get all saved accounts (for the account switcher UI).List<SavedAccount> get savedAccounts => UserAccountService().accounts;}diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dartindex 5db8b8ab..e47ac6ab 100644--- a/lib/screens/admin_users_screen.dart+++ b/lib/screens/admin_users_screen.dart@@ -802,6 +802,8 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {final Set<String> _selectedLibraries = {};bool _saving = false;bool _deleting = false;+ bool _unlinking = false;+ late bool _hasOpenIDLink;bool get _isNew => widget.user == null;@@ -822,6 +824,7 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {_accessAllLibraries = p['accessAllLibraries'] as bool? ?? true;final accessible = (u?['librariesAccessible'] as List?)?.cast<String>() ?? [];_selectedLibraries.addAll(accessible);+ _hasOpenIDLink = u?['hasOpenIDLink'] as bool? ?? false;}@override@@ -896,6 +899,20 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {));}),],+ if (!_isNew && _hasOpenIDLink) ...[+ const SizedBox(height: 20),+ SizedBox(width: double.infinity, child: OutlinedButton.icon(+ onPressed: _unlinking ? null : _unlinkOpenID,+ icon: _unlinking+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.error))+ : Icon(Icons.link_off_rounded, size: 18, color: cs.error),+ label: Text(l.adminUsersUnlinkOpenId, style: TextStyle(color: cs.error, fontWeight: FontWeight.w600)),+ style: OutlinedButton.styleFrom(+ padding: const EdgeInsets.symmetric(vertical: 12),+ side: BorderSide(color: cs.error.withValues(alpha: 0.4)),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),+ )),+ ],]))),Padding(padding: EdgeInsets.fromLTRB(20, 8, 20, MediaQuery.of(context).padding.bottom + 12),child: SizedBox(width: double.infinity, height: 48, child: FilledButton(@@ -989,6 +1006,27 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {}}+ Future<void> _unlinkOpenID() async {+ final l = AppLocalizations.of(context)!;+ final name = widget.user?['username'] as String? ?? l.adminUsersThisUser;+ final yes = await showDialog<bool>(context: context, builder: (ctx) => AlertDialog(+ title: Text(l.adminUsersUnlinkOpenIdTitle),+ content: Text(l.adminUsersUnlinkOpenIdContent(name)),+ actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),+ TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.adminUsersUnlinkOpenId, style: TextStyle(color: Colors.red.shade300)))],+ ));+ if (yes != true) return;+ final api = context.read<AuthProvider>().apiService; if (api == null) return;+ setState(() => _unlinking = true);+ final ok = await api.unlinkOpenID(widget.user!['id'] as String);+ if (mounted) {+ final l2 = AppLocalizations.of(context)!;+ setState(() { _unlinking = false; if (ok) _hasOpenIDLink = false; });+ if (ok) { widget.onSaved(); _snk(l2.adminUsersOpenIdUnlinked); }+ else { _snk(l2.adminUsersFailedUnlinkOpenId); }+ }+ }+void _snk(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));}diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 083dda7e..b70100a4 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -1932,6 +1932,19 @@ class ApiService {return false;}+ /// Unlink a user from their OpenID/SSO connection (admin only). Clears the+ /// server's stored authOpenIDSub so the user can re-enroll. The server+ /// returns 200 even if there was no link to begin with.+ Future<bool> unlinkOpenID(String userId) async {+ try {+ final r = await _authPatch(+ Uri.parse('$_cleanBaseUrl/api/users/$userId/openid-unlink'),+ );+ return r.statusCode == 200;+ } catch (e) { debugPrint('unlinkOpenID error: $e'); }+ return false;+ }+/// List all API keys (admin only). Each entry includes the expanded `user`/// ({id, username, type}) plus name, isActive, expiresAt, lastUsedAt, createdAt./// The actual key string is never returned here, only on creation.diff --git a/lib/services/user_account_service.dart b/lib/services/user_account_service.dartindex 5107d3ff..341bf33b 100644--- a/lib/services/user_account_service.dart+++ b/lib/services/user_account_service.dart@@ -156,6 +156,83 @@ class UserAccountService {}}+ /// Change the server URL of a saved account (e.g. a dynamic-DNS hostname+ /// changed) WITHOUT losing the account's per-user data. The scopeKey is+ /// derived from the URL, so every scoped SharedPreferences key is migrated+ /// from the old scope to the new one. Returns true if the account was found.+ Future<bool> updateAccountUrl(+ String oldServerUrl, String username, String newServerUrl) async {+ final idx = _accounts.indexWhere(+ (a) => a.serverUrl == oldServerUrl && a.username == username);+ if (idx < 0) return false;++ final old = _accounts[idx];+ final updated = SavedAccount(+ serverUrl: newServerUrl,+ username: old.username,+ token: old.token,+ refreshToken: old.refreshToken,+ userId: old.userId,+ isLegacyToken: old.isLegacyToken,+ );++ final oldScope = old.scopeKey;+ final newScope = updated.scopeKey;+ await _migrateScopedData(oldScope, newScope);++ _accounts[idx] = updated;+ // If this was the active account, re-point the active scope so scoped+ // reads/writes land on the migrated data.+ if (_activeScopeKey == oldScope) {+ _activeScopeKey = newScope;+ }+ await _persist();+ debugPrint(+ '[UserAccount] Updated server URL for $username: $oldServerUrl -> $newServerUrl');+ return true;+ }++ /// Copy every `oldScope:*` SharedPreferences key to `newScope:*` (without+ /// clobbering keys that already exist under the new scope), then remove the+ /// old ones. No-op when the scope is unchanged.+ Future<void> _migrateScopedData(String oldScope, String newScope) async {+ if (oldScope.isEmpty || newScope.isEmpty || oldScope == newScope) return;+ final prefs = await SharedPreferences.getInstance();+ final oldPrefix = '$oldScope:';+ final newPrefix = '$newScope:';+ int moved = 0;+ for (final key in prefs.getKeys().toList()) {+ if (!key.startsWith(oldPrefix)) continue;+ final newKey = '$newPrefix${key.substring(oldPrefix.length)}';+ if (prefs.containsKey(newKey)) {+ // Target already has data for this key; drop the stale old copy.+ await prefs.remove(key);+ continue;+ }+ final value = prefs.get(key);+ bool copied = true;+ if (value is String) {+ await prefs.setString(newKey, value);+ } else if (value is bool) {+ await prefs.setBool(newKey, value);+ } else if (value is int) {+ await prefs.setInt(newKey, value);+ } else if (value is double) {+ await prefs.setDouble(newKey, value);+ } else if (value is List<String>) {+ await prefs.setStringList(newKey, value);+ } else {+ copied = false; // unknown type — leave the old key untouched+ }+ if (copied) {+ await prefs.remove(key);+ moved++;+ }+ }+ debugPrint(+ '[UserAccount] Migrated $moved scoped key(s): $oldScope -> $newScope');+ }+// ── Scoped key helpers ──────────────────────────────────/// Returns a SharedPreferences key scoped to the active user.