|
| 1 | +import Foundation |
| 2 | +import Security |
| 3 | + |
| 4 | +// MARK: - KeychainCredentialStore |
| 5 | + |
| 6 | +/// Thin Keychain wrapper for storing scrobbling service credentials. |
| 7 | +/// Uses `kSecClassGenericPassword` with `kSecAttrAccessibleAfterFirstUnlock`. |
| 8 | +@MainActor |
| 9 | +final class KeychainCredentialStore { |
| 10 | + private let servicePrefix: String |
| 11 | + |
| 12 | + /// Creates a credential store with the given service prefix. |
| 13 | + /// - Parameter servicePrefix: Prefix for Keychain entries (default: "com.sertacozercan.Kaset"). |
| 14 | + init(servicePrefix: String = "com.sertacozercan.Kaset") { |
| 15 | + self.servicePrefix = servicePrefix |
| 16 | + } |
| 17 | + |
| 18 | + // MARK: - Public API |
| 19 | + |
| 20 | + /// Saves the Last.fm session key to Keychain. |
| 21 | + func saveLastFMSessionKey(_ sessionKey: String) throws { |
| 22 | + try self.save(key: "lastFMSessionKey", value: sessionKey) |
| 23 | + } |
| 24 | + |
| 25 | + /// Retrieves the stored Last.fm session key, if any. |
| 26 | + func getLastFMSessionKey() -> String? { |
| 27 | + self.get(key: "lastFMSessionKey") |
| 28 | + } |
| 29 | + |
| 30 | + /// Saves the Last.fm username to Keychain. |
| 31 | + func saveLastFMUsername(_ username: String) throws { |
| 32 | + try self.save(key: "lastFMUsername", value: username) |
| 33 | + } |
| 34 | + |
| 35 | + /// Retrieves the stored Last.fm username, if any. |
| 36 | + func getLastFMUsername() -> String? { |
| 37 | + self.get(key: "lastFMUsername") |
| 38 | + } |
| 39 | + |
| 40 | + /// Removes all Last.fm credentials from Keychain. |
| 41 | + func removeLastFMCredentials() { |
| 42 | + self.delete(key: "lastFMSessionKey") |
| 43 | + self.delete(key: "lastFMUsername") |
| 44 | + } |
| 45 | + |
| 46 | + // MARK: - Private Helpers |
| 47 | + |
| 48 | + private func save(key: String, value: String) throws { |
| 49 | + guard let data = value.data(using: .utf8) else { |
| 50 | + throw KeychainError.encodingFailed |
| 51 | + } |
| 52 | + |
| 53 | + let account = "\(self.servicePrefix).\(key)" |
| 54 | + |
| 55 | + // Try to update existing item first |
| 56 | + let updateQuery: [String: Any] = [ |
| 57 | + kSecClass as String: kSecClassGenericPassword, |
| 58 | + kSecAttrAccount as String: account, |
| 59 | + kSecAttrService as String: self.servicePrefix, |
| 60 | + ] |
| 61 | + |
| 62 | + let updateAttributes: [String: Any] = [ |
| 63 | + kSecValueData as String: data, |
| 64 | + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock, |
| 65 | + ] |
| 66 | + |
| 67 | + let updateStatus = SecItemUpdate(updateQuery as CFDictionary, updateAttributes as CFDictionary) |
| 68 | + |
| 69 | + if updateStatus == errSecItemNotFound { |
| 70 | + // Item doesn't exist, add it |
| 71 | + var addQuery = updateQuery |
| 72 | + addQuery[kSecValueData as String] = data |
| 73 | + addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock |
| 74 | + |
| 75 | + let addStatus = SecItemAdd(addQuery as CFDictionary, nil) |
| 76 | + guard addStatus == errSecSuccess else { |
| 77 | + throw KeychainError.saveFailed(status: addStatus) |
| 78 | + } |
| 79 | + } else if updateStatus != errSecSuccess { |
| 80 | + throw KeychainError.saveFailed(status: updateStatus) |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + private func get(key: String) -> String? { |
| 85 | + let account = "\(self.servicePrefix).\(key)" |
| 86 | + |
| 87 | + let query: [String: Any] = [ |
| 88 | + kSecClass as String: kSecClassGenericPassword, |
| 89 | + kSecAttrAccount as String: account, |
| 90 | + kSecAttrService as String: self.servicePrefix, |
| 91 | + kSecReturnData as String: true, |
| 92 | + kSecMatchLimit as String: kSecMatchLimitOne, |
| 93 | + ] |
| 94 | + |
| 95 | + var result: AnyObject? |
| 96 | + let status = SecItemCopyMatching(query as CFDictionary, &result) |
| 97 | + |
| 98 | + guard status == errSecSuccess, |
| 99 | + let data = result as? Data, |
| 100 | + let value = String(data: data, encoding: .utf8) |
| 101 | + else { |
| 102 | + return nil |
| 103 | + } |
| 104 | + |
| 105 | + return value |
| 106 | + } |
| 107 | + |
| 108 | + private func delete(key: String) { |
| 109 | + let account = "\(self.servicePrefix).\(key)" |
| 110 | + |
| 111 | + let query: [String: Any] = [ |
| 112 | + kSecClass as String: kSecClassGenericPassword, |
| 113 | + kSecAttrAccount as String: account, |
| 114 | + kSecAttrService as String: self.servicePrefix, |
| 115 | + ] |
| 116 | + |
| 117 | + SecItemDelete(query as CFDictionary) |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +// MARK: - KeychainError |
| 122 | + |
| 123 | +/// Errors that can occur during Keychain operations. |
| 124 | +enum KeychainError: Error, LocalizedError { |
| 125 | + case encodingFailed |
| 126 | + case saveFailed(status: OSStatus) |
| 127 | + |
| 128 | + var errorDescription: String? { |
| 129 | + switch self { |
| 130 | + case .encodingFailed: |
| 131 | + "Failed to encode value for Keychain storage." |
| 132 | + case let .saveFailed(status): |
| 133 | + "Keychain save failed with status: \(status)" |
| 134 | + } |
| 135 | + } |
| 136 | +} |
0 commit comments