jel/Jel/Controllers/AuthStateController.swift

53 lines
1.5 KiB
Swift

//
// AuthStateController.swift
// Jel
//
// Created by zerocool on 12/11/23.
//
import Foundation
class AuthStateController: ObservableObject {
@Published var loggedIn: Bool
@Published var serverUrl: URL?
@Published var authToken: String?
@Published var userId: String?
@Published var username: String?
private let defaults = UserDefaults.standard
static let shared = AuthStateController()
init(loggedIn: Bool = false, serverUrl: URL? = nil, authToken: String? = nil, userId: String? = nil, username: String? = nil) {
self.loggedIn = loggedIn
self.serverUrl = serverUrl
self.authToken = authToken
self.userId = userId
self.username = username
}
func load() {
self.loggedIn = defaults.bool(forKey: "AuthState_loggedIn")
if let oldServerUrl = defaults.url(forKey: "AuthState_serverUrl") {
self.serverUrl = oldServerUrl
}
if let oldAuthToken = defaults.string(forKey: "AuthState_authToken") {
self.authToken = oldAuthToken
}
if let oldUserId = defaults.string(forKey: "AuthState_userId") {
self.userId = oldUserId
}
if let oldUsername = defaults.string(forKey: "AuthState_username") {
self.username = oldUsername
}
}
func save() {
defaults.set(self.loggedIn, forKey: "AuthState_loggedIn")
defaults.set(self.serverUrl, forKey: "AuthState_serverUrl")
defaults.set(self.authToken, forKey: "AuthState_authToken")
defaults.set(self.userId, forKey: "AuthState_userId")
defaults.set(self.username, forKey: "AuthState_username")
}
}