76 lines
2.6 KiB
Swift
76 lines
2.6 KiB
Swift
import Foundation
|
|
import Security
|
|
|
|
enum SecureStore {
|
|
private static let service = "cn.toplc.zonghengjia.credentials"
|
|
private static let tokenAccount = "access-token"
|
|
private static let deviceAccount = "device-id"
|
|
private static let lastLoginKey = "ucvl.last-login"
|
|
|
|
static var lastLogin: String {
|
|
get { UserDefaults.standard.string(forKey: lastLoginKey) ?? "" }
|
|
set { UserDefaults.standard.set(newValue, forKey: lastLoginKey) }
|
|
}
|
|
|
|
static func token() -> String? {
|
|
read(account: tokenAccount)
|
|
}
|
|
|
|
static func saveToken(_ token: String) throws {
|
|
try write(token, account: tokenAccount)
|
|
}
|
|
|
|
static func clearToken() {
|
|
delete(account: tokenAccount)
|
|
}
|
|
|
|
static func deviceID() -> String {
|
|
if let stored = read(account: deviceAccount), !stored.isEmpty {
|
|
return stored
|
|
}
|
|
let created = "ios-\(UUID().uuidString.lowercased())"
|
|
try? write(created, account: deviceAccount)
|
|
return created
|
|
}
|
|
|
|
private static func read(account: String) -> String? {
|
|
let query: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
kSecMatchLimit as String: kSecMatchLimitOne,
|
|
kSecReturnData as String: true,
|
|
]
|
|
var result: CFTypeRef?
|
|
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
|
|
let data = result as? Data
|
|
else { return nil }
|
|
return String(data: data, encoding: .utf8)
|
|
}
|
|
|
|
private static func write(_ value: String, account: String) throws {
|
|
guard let data = value.data(using: .utf8) else { return }
|
|
delete(account: account)
|
|
let query: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
|
kSecValueData as String: data,
|
|
]
|
|
let status = SecItemAdd(query as CFDictionary, nil)
|
|
guard status == errSecSuccess else {
|
|
throw UCVLError.invalidConfiguration("无法安全保存登录授权(\(status))。")
|
|
}
|
|
}
|
|
|
|
private static func delete(account: String) {
|
|
let query: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
]
|
|
SecItemDelete(query as CFDictionary)
|
|
}
|
|
}
|