diff --git a/Forji/Forji/Services/AuthenticationService.swift b/Forji/Forji/Services/AuthenticationService.swift index b506ada..99f180c 100644 --- a/Forji/Forji/Services/AuthenticationService.swift +++ b/Forji/Forji/Services/AuthenticationService.swift @@ -95,9 +95,21 @@ class AuthenticationService { return true } - func logout(modelContext: ModelContext? = nil) async { + func logout(modelContext: ModelContext) async { if let instance = currentInstance { let normalizedURL = ForgejoClient.normalizeServerURL(instance.serverURL) + // Remove the instance from SwiftData first. If the save fails, keep the + // credentials so the account stays usable instead of becoming an + // unauthenticatable orphan, and bail out without clearing the session. + instance.isDefault = false + modelContext.delete(instance) + do { + try modelContext.save() + } catch { + assertionFailure("SwiftData save failed during logout: \(error)") + return + } + // Delete credentials only after the instance is gone from SwiftData. do { try await KeychainManager.shared.deleteCredentials( for: normalizedURL, @@ -109,12 +121,6 @@ class AuthenticationService { print("Keychain delete failed during logout: \(error)") #endif } - // Remove the instance from SwiftData and unset default - if let modelContext { - instance.isDefault = false - modelContext.delete(instance) - try? modelContext.save() - } } // Clears cache for all instances since keys are hashed and cannot be scoped per-instance DiskCache.removeAll()