From 7edc94258102508cced4090c6d0ff5fd92dfa7a9 Mon Sep 17 00:00:00 2001 From: "Mohannad A. Hassan" Date: Fri, 17 Jan 2025 10:23:38 +0200 Subject: [PATCH] Update data if data already exists in Persistence --- .../Sources/Persistence.swift | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Data/AuthenticationClient/Sources/Persistence.swift b/Data/AuthenticationClient/Sources/Persistence.swift index b5c1f9d4..bb960eee 100644 --- a/Data/AuthenticationClient/Sources/Persistence.swift +++ b/Data/AuthenticationClient/Sources/Persistence.swift @@ -32,13 +32,32 @@ final class KeychainPersistence: Persistence { kSecValueData as String: state, ] let status = SecItemAdd(addquery as CFDictionary, nil) - if status != errSecSuccess { + if status == errSecDuplicateItem { + logger.info("State already exists, updating") + try update(state: state) + } else if status != errSecSuccess { logger.error("Failed to persist state -- \(status) status") throw PersistenceError.persistenceFailed } logger.info("State persisted successfully") } + private func update(state: Data) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrAccount as String: itemKey, + ] + let attributes: [String: Any] = [ + kSecValueData as String: state, + ] + let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) + if status != errSecSuccess { + logger.error("Failed to update state -- \(status) status") + throw PersistenceError.persistenceFailed + } + logger.info("State updated") + } + func retrieve() throws -> Data? { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword,