--------- Co-authored-by: intelligence <intelligence@debian.local> Co-authored-by: jourintown <jourintown@proton.me> Reviewed-on: #2
46 lines
1.4 KiB
Swift
46 lines
1.4 KiB
Swift
import Foundation
|
|
import Security
|
|
|
|
enum KeychainAccount: String {
|
|
case hosted = "remote-api-key"
|
|
case local = "local-api-key"
|
|
}
|
|
|
|
enum KeychainStore {
|
|
private static let service = "io.github.transui.macos"
|
|
|
|
static func read(_ account: KeychainAccount) -> String {
|
|
let query: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account.rawValue,
|
|
kSecReturnData as String: true,
|
|
kSecMatchLimit as String: kSecMatchLimitOne,
|
|
]
|
|
var item: CFTypeRef?
|
|
guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
|
|
let data = item as? Data
|
|
else { return "" }
|
|
return String(data: data, encoding: .utf8) ?? ""
|
|
}
|
|
|
|
static func write(_ value: String, account: KeychainAccount) {
|
|
let identity: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account.rawValue,
|
|
]
|
|
if value.isEmpty {
|
|
SecItemDelete(identity as CFDictionary)
|
|
return
|
|
}
|
|
let data = Data(value.utf8)
|
|
let attributes = [kSecValueData as String: data]
|
|
if SecItemUpdate(identity as CFDictionary, attributes as CFDictionary) == errSecItemNotFound {
|
|
var item = identity
|
|
item[kSecValueData as String] = data
|
|
SecItemAdd(item as CFDictionary, nil)
|
|
}
|
|
}
|
|
}
|