jel/Jel/Controllers/AuthStateController.swift

53 lines
1.5 KiB
Swift
Raw Normal View History

2023-12-12 06:22:43 +00:00
//
// 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?
2023-12-13 00:51:54 +00:00
@Published var userId: String?
2024-01-07 21:58:38 +00:00
@Published var username: String?
2023-12-12 06:22:43 +00:00
private let defaults = UserDefaults.standard
2023-12-12 22:09:15 +00:00
static let shared = AuthStateController()
2024-01-07 21:58:38 +00:00
init(loggedIn: Bool = false, serverUrl: URL? = nil, authToken: String? = nil, userId: String? = nil, username: String? = nil) {
2023-12-12 06:22:43 +00:00
self.loggedIn = loggedIn
self.serverUrl = serverUrl
self.authToken = authToken
2023-12-13 00:51:54 +00:00
self.userId = userId
2024-01-07 21:58:38 +00:00
self.username = username
2023-12-12 06:22:43 +00:00
}
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
}
2023-12-13 00:51:54 +00:00
if let oldUserId = defaults.string(forKey: "AuthState_userId") {
self.userId = oldUserId
}
2024-01-07 21:58:38 +00:00
if let oldUsername = defaults.string(forKey: "AuthState_username") {
self.username = oldUsername
}
2023-12-12 06:22:43 +00:00
}
func save() {
defaults.set(self.loggedIn, forKey: "AuthState_loggedIn")
defaults.set(self.serverUrl, forKey: "AuthState_serverUrl")
defaults.set(self.authToken, forKey: "AuthState_authToken")
2023-12-13 00:51:54 +00:00
defaults.set(self.userId, forKey: "AuthState_userId")
2024-01-07 21:58:38 +00:00
defaults.set(self.username, forKey: "AuthState_username")
2023-12-12 06:22:43 +00:00
}
}