Persist auth across preview rerenders

This commit is contained in:
lucast committed 2026-10-07 02:14:28 +02:00
1 parent d6b35fe346
commit d9a996aa98
5 files changed
+163 -8

No files matched your search

+20
View File
@@ -66,6 +66,9 @@ public final class APIClient: @unchecked Sendable {
config.httpShouldSetCookies = true config.httpShouldSetCookies = true
self.session = URLSession(configuration: config) self.session = URLSession(configuration: config)
} }
if let cookieStorage = self.session.configuration.httpCookieStorage {
AuthCookiePersistence.restore(into: cookieStorage, for: configuration.apiBaseURL)
}
let decoder = JSONDecoder() let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601 decoder.dateDecodingStrategy = .iso8601
self.decoder = decoder self.decoder = decoder
@@ -105,6 +108,12 @@ public final class APIClient: @unchecked Sendable {
} }
if !query.isEmpty { components.queryItems = query } if !query.isEmpty { components.queryItems = query }
guard let url = components.url else { throw APIError.invalidURL } guard let url = components.url else { throw APIError.invalidURL }
if let cookieStorage = session.configuration.httpCookieStorage {
AuthCookiePersistence.restore(into: cookieStorage, for: url)
if path.hasPrefix("auth/") {
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "before \(path)")
}
}
var request = URLRequest(url: url) var request = URLRequest(url: url)
request.httpMethod = method request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Accept")
@@ -119,6 +128,12 @@ public final class APIClient: @unchecked Sendable {
} }
do { do {
let (data, rawResponse) = try await session.data(for: request) let (data, rawResponse) = try await session.data(for: request)
if let cookieStorage = session.configuration.httpCookieStorage {
AuthCookiePersistence.save(from: cookieStorage, for: url)
if path.hasPrefix("auth/") {
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "after \(path)")
}
}
guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse } guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse }
guard (200..<300).contains(http.statusCode) else { guard (200..<300).contains(http.statusCode) else {
let message = let message =
@@ -163,6 +178,11 @@ public final class APIClient: @unchecked Sendable {
return try decoder.decode(Response.self, from: data) return try decoder.decode(Response.self, from: data)
} catch { throw APIError.decoding(String(describing: error)) } } catch { throw APIError.decoding(String(describing: error)) }
} catch let error as APIError { throw error } catch { } catch let error as APIError { throw error } catch {
if Task.isCancelled || error is CancellationError
|| (error as? URLError)?.code == .cancelled
{
throw CancellationError()
}
throw APIError.transport(error.localizedDescription) throw APIError.transport(error.localizedDescription)
} }
} }
+96
View File
@@ -0,0 +1,96 @@
import Foundation
import Security
/// Keeps the backend's HttpOnly session and refresh cookies available when Xcode
/// replaces a SwiftUI preview process. Cookie values stay in the Keychain.
enum AuthCookiePersistence {
private static let service = "dk.lucasskt.MusicApp.auth-cookies"
private static let account = "music.lucasskt.dk"
static func restore(into storage: HTTPCookieStorage, for url: URL) {
guard let data = read() else {
debug("restore: no Keychain record for host=\(url.host ?? "?")")
return
}
guard let properties = try? PropertyListSerialization.propertyList(
from: data, options: [], format: nil) as? [[HTTPCookiePropertyKey: Any]] else {
debug("restore: Keychain data could not be decoded (\(data.count) bytes)")
return
}
let cookies = properties.compactMap(HTTPCookie.init(properties:))
.filter { $0.domain.hasSuffix("music.lucasskt.dk") && $0.expiresDate.map { $0 > Date() } ?? true }
storage.setCookies(cookies, for: url, mainDocumentURL: nil)
debug("restore: loaded \(cookies.count) cookies [\(cookieNames(cookies))] for host=\(url.host ?? "?")")
}
static func save(from storage: HTTPCookieStorage, for url: URL) {
let properties = storage.cookies(for: url)?
.filter { $0.domain.hasSuffix("music.lucasskt.dk") }
.compactMap(\.properties) ?? []
guard let data = try? PropertyListSerialization.data(
fromPropertyList: properties, format: .binary, options: 0)
else {
debug("save: cookie properties could not be encoded [\(cookieNames(storage.cookies(for: url) ?? []))]")
return
}
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
let update: [String: Any] = [kSecValueData as String: data]
let status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
if status == errSecItemNotFound {
var insert = query
insert[kSecValueData as String] = data
insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
let addStatus = SecItemAdd(insert as CFDictionary, nil)
debug("save: insert status=\(addStatus), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
} else {
debug("save: update status=\(status), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
}
}
static func logRequestCookies(from storage: HTTPCookieStorage, for url: URL, phase: String) {
debug("\(phase): request cookie names [\(cookieNames(storage.cookies(for: url) ?? []))] host=\(url.host ?? "?")")
}
static func clear() {
SecItemDelete([
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
] as CFDictionary)
}
private static func read() -> Data? {
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
query[kSecUseAuthenticationUI as String] = kSecUseAuthenticationUIFail
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess else {
debug("read: Keychain status=\(status)")
return nil
}
debug("read: Keychain success")
return result as? Data
}
private static func cookieNames(_ cookies: [HTTPCookie]) -> String {
cookies.map(\.name).sorted().joined(separator: ",")
}
private static func debug(_ message: String) {
#if DEBUG
print("[AuthCookiePersistence] pid=\(ProcessInfo.processInfo.processIdentifier) bundle=\(Bundle.main.bundleIdentifier ?? "?") \(message)")
#endif
}
}
+3 -1
View File
@@ -27,7 +27,9 @@ public struct MusicAPI: Sendable {
try await client.request("POST", path: "auth/session") try await client.request("POST", path: "auth/session")
} }
public func signOut() async throws -> SignOutResponse { public func signOut() async throws -> SignOutResponse {
try await client.request("POST", path: "auth/signout") let response: SignOutResponse = try await client.request("POST", path: "auth/signout")
AuthCookiePersistence.clear()
return response
} }
public func currentUser() async throws -> User { try await client.request("GET", path: "user") } public func currentUser() async throws -> User { try await client.request("GET", path: "user") }
+32 -1
View File
@@ -1,4 +1,5 @@
import Combine import Combine
import Foundation
@MainActor @MainActor
final class AuthSessionStore: ObservableObject { final class AuthSessionStore: ObservableObject {
@@ -11,18 +12,34 @@ final class AuthSessionStore: ObservableObject {
@Published private(set) var state: State = .checking @Published private(set) var state: State = .checking
@Published private(set) var isSigningIn = false @Published private(set) var isSigningIn = false
static let shared = AuthSessionStore()
private let api = MusicAPI() private let api = MusicAPI()
init(initialState: State = .checking) { init(initialState: State = .checking) {
state = initialState state = initialState
debug("store initialized; state=\(stateName(state))")
} }
func restoreSession() async { func restoreSession() async {
debug("restore requested; state=\(stateName(state))")
guard state == .checking else { return } guard state == .checking else { return }
do { 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 { } catch {
guard !Task.isCancelled else {
debug("session restore cancelled after request error; leaving state unchanged")
return
}
debug("session restore failed: \(error.localizedDescription)")
state = .signedOut state = .signedOut
} }
} }
@@ -34,4 +51,18 @@ final class AuthSessionStore: ObservableObject {
try await api.signIn(email: email, password: password) try await api.signIn(email: email, password: password)
state = .signedIn 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"
}
}
} }
+12 -6
View File
@@ -1,12 +1,15 @@
import SwiftUI import SwiftUI
struct ContentView: View { struct ContentView: View {
@StateObject private var session = AuthSessionStore() @StateObject private var session: AuthSessionStore
private let restoresSession: Bool private let restoresSession: Bool
@MainActor init(session: AuthSessionStore? = nil, restoresSession: Bool = true) { @MainActor init(session: AuthSessionStore? = nil, restoresSession: Bool = true) {
_session = StateObject(wrappedValue: session ?? AuthSessionStore()) _session = StateObject(wrappedValue: session ?? AuthSessionStore.shared)
self.restoresSession = restoresSession self.restoresSession = restoresSession
#if DEBUG
print("[ContentView] initialized; injectedSession=\(session != nil), restoresSession=\(restoresSession)")
#endif
} }
var body: some View { var body: some View {
@@ -26,6 +29,12 @@ struct ContentView: View {
} }
.task { .task {
guard restoresSession else { return } guard restoresSession else { return }
#if DEBUG
print("[ContentView] session restore task started")
defer {
print("[ContentView] session restore task ended; cancelled=\(Task.isCancelled)")
}
#endif
await session.restoreSession() await session.restoreSession()
} }
} }
@@ -33,9 +42,6 @@ struct ContentView: View {
struct ContentView_Previews: PreviewProvider { struct ContentView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
ContentView( ContentView()
session: AuthSessionStore(initialState: .signedOut),
restoresSession: false
)
} }
} }