IceCubes/IceCubesApp/App/AppAccounts/AppAccount.swift

63 lines
1.3 KiB
Swift
Raw Normal View History

2022-12-01 09:05:26 +01:00
import SwiftUI
import Timeline
import Network
import KeychainSwift
import Models
2023-01-08 10:22:52 +01:00
import CryptoKit
2022-12-01 09:05:26 +01:00
2022-12-30 08:36:22 +01:00
struct AppAccount: Codable, Identifiable {
2022-12-01 09:05:26 +01:00
let server: String
let oauthToken: OauthToken?
2022-12-30 08:36:22 +01:00
var id: String {
key
}
2022-12-01 09:05:26 +01:00
var key: String {
if let oauthToken {
return "\(server):\(oauthToken.createdAt)"
} else {
return "\(server):anonymous:\(Date().timeIntervalSince1970)"
}
}
2023-01-08 10:22:52 +01:00
internal init(server: String, oauthToken: OauthToken? = nil) {
self.server = server
self.oauthToken = oauthToken
}
2022-12-01 09:05:26 +01:00
func save() throws {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
let keychain = KeychainSwift()
keychain.set(data, forKey: key)
}
func delete() {
KeychainSwift().delete(key)
}
2023-01-08 10:22:52 +01:00
static func retrieveAll() -> [AppAccount] {
2022-12-01 09:05:26 +01:00
let keychain = KeychainSwift()
let decoder = JSONDecoder()
let keys = keychain.allKeys
var accounts: [AppAccount] = []
for key in keys {
if let data = keychain.getData(key) {
2023-01-08 10:22:52 +01:00
if let account = try? decoder.decode(AppAccount.self, from: data) {
accounts.append(account)
}
2022-12-01 09:05:26 +01:00
}
}
return accounts
}
static func deleteAll() {
let keychain = KeychainSwift()
let keys = keychain.allKeys
for key in keys {
keychain.delete(key)
}
}
}