Persist auth across preview rerenders
This commit is contained in:
1 parent
d6b35fe346
commit
d9a996aa98
5 files changed
+163
-8
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
final class AuthSessionStore: ObservableObject {
|
||||
@@ -11,18 +12,34 @@ final class AuthSessionStore: ObservableObject {
|
||||
@Published private(set) var state: State = .checking
|
||||
@Published private(set) var isSigningIn = false
|
||||
|
||||
static let shared = AuthSessionStore()
|
||||
private let api = MusicAPI()
|
||||
|
||||
init(initialState: State = .checking) {
|
||||
state = initialState
|
||||
debug("store initialized; state=\(stateName(state))")
|
||||
}
|
||||
|
||||
func restoreSession() async {
|
||||
debug("restore requested; state=\(stateName(state))")
|
||||
guard state == .checking else { return }
|
||||
|
||||
do {
|
||||
state = try await api.sessionStatus().authenticated ? .signedIn : .signedOut
|
||||
let authenticated = try await api.sessionStatus().authenticated
|
||||
guard !Task.isCancelled else {
|
||||
debug("session restore cancelled; leaving state unchanged")
|
||||
return
|
||||
}
|
||||
state = authenticated ? .signedIn : .signedOut
|
||||
debug("session restore completed; authenticated=\(authenticated)")
|
||||
} catch is CancellationError {
|
||||
debug("session restore cancelled; leaving state unchanged")
|
||||
} catch {
|
||||
guard !Task.isCancelled else {
|
||||
debug("session restore cancelled after request error; leaving state unchanged")
|
||||
return
|
||||
}
|
||||
debug("session restore failed: \(error.localizedDescription)")
|
||||
state = .signedOut
|
||||
}
|
||||
}
|
||||
@@ -34,4 +51,18 @@ final class AuthSessionStore: ObservableObject {
|
||||
try await api.signIn(email: email, password: password)
|
||||
state = .signedIn
|
||||
}
|
||||
|
||||
private func debug(_ message: String) {
|
||||
#if DEBUG
|
||||
print("[AuthSessionStore] pid=\(ProcessInfo.processInfo.processIdentifier) \(message)")
|
||||
#endif
|
||||
}
|
||||
|
||||
private func stateName(_ state: State) -> String {
|
||||
switch state {
|
||||
case .checking: "checking"
|
||||
case .signedOut: "signedOut"
|
||||
case .signedIn: "signedIn"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user