2023-01-17 10:36:01 +00:00
|
|
|
import CryptoKit
|
2022-12-01 08:05:26 +00:00
|
|
|
import KeychainSwift
|
|
|
|
import Models
|
2023-01-17 10:36:01 +00:00
|
|
|
import Network
|
|
|
|
import SwiftUI
|
2022-12-01 08:05:26 +00:00
|
|
|
|
2023-01-25 20:18:34 +00:00
|
|
|
extension AppAccount {
|
2023-01-13 12:05:43 +00:00
|
|
|
private static var keychain: KeychainSwift {
|
|
|
|
let keychain = KeychainSwift()
|
|
|
|
#if !DEBUG
|
|
|
|
keychain.accessGroup = AppInfo.keychainGroup
|
|
|
|
#endif
|
|
|
|
return keychain
|
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2023-01-12 17:17:21 +00:00
|
|
|
public func save() throws {
|
2022-12-01 08:05:26 +00:00
|
|
|
let encoder = JSONEncoder()
|
|
|
|
let data = try encoder.encode(self)
|
2023-01-13 12:05:43 +00:00
|
|
|
Self.keychain.set(data, forKey: key)
|
2022-12-01 08:05:26 +00:00
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2023-01-12 17:17:21 +00:00
|
|
|
public func delete() {
|
2023-01-13 12:05:43 +00:00
|
|
|
Self.keychain.delete(key)
|
2022-12-01 08:05:26 +00:00
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2023-01-12 17:17:21 +00:00
|
|
|
public static func retrieveAll() -> [AppAccount] {
|
2023-01-13 12:05:43 +00:00
|
|
|
migrateLegacyAccounts()
|
|
|
|
let keychain = Self.keychain
|
2022-12-01 08:05:26 +00:00
|
|
|
let decoder = JSONDecoder()
|
|
|
|
let keys = keychain.allKeys
|
|
|
|
var accounts: [AppAccount] = []
|
|
|
|
for key in keys {
|
|
|
|
if let data = keychain.getData(key) {
|
2023-01-08 09:22:52 +00:00
|
|
|
if let account = try? decoder.decode(AppAccount.self, from: data) {
|
|
|
|
accounts.append(account)
|
|
|
|
}
|
2022-12-01 08:05:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return accounts
|
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2023-01-13 12:05:43 +00:00
|
|
|
public static func migrateLegacyAccounts() {
|
2022-12-01 08:05:26 +00:00
|
|
|
let keychain = KeychainSwift()
|
2023-01-13 12:05:43 +00:00
|
|
|
let decoder = JSONDecoder()
|
|
|
|
let keys = keychain.allKeys
|
|
|
|
for key in keys {
|
|
|
|
if let data = keychain.getData(key) {
|
|
|
|
if let account = try? decoder.decode(AppAccount.self, from: data) {
|
|
|
|
try? account.save()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2023-01-13 12:05:43 +00:00
|
|
|
public static func deleteAll() {
|
|
|
|
let keychain = Self.keychain
|
2022-12-01 08:05:26 +00:00
|
|
|
let keys = keychain.allKeys
|
|
|
|
for key in keys {
|
|
|
|
keychain.delete(key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|