Feat macos (#2)
--------- Co-authored-by: intelligence <intelligence@debian.local> Co-authored-by: jourintown <jourintown@proton.me> Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
1 parent
136bf7cfa3
commit
32e7f32e0a
22 files changed
+1360
-7
No files matched your search
@@ -0,0 +1,45 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user