payfrit-beacon-ios/PayfritBeacon/ViewModels/AppState.swift
2026-02-01 23:39:29 -08:00

49 lines
1.5 KiB
Swift

import SwiftUI
@MainActor
final class AppState: ObservableObject {
@Published var userId: Int?
@Published var userName: String?
@Published var userPhotoUrl: String?
@Published var userToken: String?
@Published var businessId: Int = 0
@Published var businessName: String = ""
@Published var isAuthenticated = false
func setAuth(userId: Int, token: String, userName: String? = nil, photoUrl: String? = nil) {
self.userId = userId
self.userToken = token
self.userName = userName
self.userPhotoUrl = photoUrl
self.isAuthenticated = true
}
func setBusiness(id: Int, name: String) {
self.businessId = id
self.businessName = name
}
func clearAuth() {
userId = nil
userToken = nil
userName = nil
userPhotoUrl = nil
isAuthenticated = false
businessId = 0
businessName = ""
}
/// Handle 401 unauthorized clear everything and force re-login
func handleUnauthorized() async {
await AuthStorage.shared.clearAuth()
await APIService.shared.logout()
clearAuth()
}
func loadSavedAuth() async {
let creds = await AuthStorage.shared.loadAuth()
guard let creds = creds else { return }
await APIService.shared.setAuth(token: creds.token, userId: creds.userId)
setAuth(userId: creds.userId, token: creds.token, userName: creds.userName, photoUrl: creds.photoUrl)
}
}