IceCubesApp/Packages/AppAccount/Sources/AppAccount/AppAccount.swift

64 lines
1.5 KiB
Swift
Raw Normal View History

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-27 19:36:40 +00:00
public extension AppAccount {
private static var keychain: KeychainSwift {
let keychain = KeychainSwift()
2023-01-27 11:06:44 +00:00
#if !DEBUG && !targetEnvironment(simulator)
keychain.accessGroup = AppInfo.keychainGroup
#endif
return keychain
}
2023-01-17 10:36:01 +00:00
2023-01-27 19:36:40 +00:00
func save() throws {
2022-12-01 08:05:26 +00:00
let encoder = JSONEncoder()
let data = try encoder.encode(self)
Self.keychain.set(data, forKey: key, withAccess: .accessibleAfterFirstUnlock)
2022-12-01 08:05:26 +00:00
}
2023-01-17 10:36:01 +00:00
2023-01-27 19:36:40 +00:00
func delete() {
Self.keychain.delete(key)
2022-12-01 08:05:26 +00:00
}
2023-01-17 10:36:01 +00:00
2023-01-27 19:36:40 +00:00
static func retrieveAll() -> [AppAccount] {
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)
2023-02-14 13:15:31 +00:00
try? account.save()
2023-01-08 09:22:52 +00:00
}
2022-12-01 08:05:26 +00:00
}
}
return accounts
}
2023-01-17 10:36:01 +00:00
2023-01-27 19:36:40 +00:00
static func migrateLegacyAccounts() {
2022-12-01 08:05:26 +00:00
let keychain = KeychainSwift()
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-27 19:36:40 +00:00
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)
}
}
}