SPB Git

Repository Public

AuthStore.swift 3.3 KB 89 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Core/Authentication/AuthStore.swift4//  Description: Account state machine: signed out / signed in, passkey sign-in, enrolment, sign-out with local wipe.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation11import Observation1213@MainActor14@Observable15final class AuthStore {16    enum Phase: Equatable { case signedOut, signedIn }17    private(set) var phase: Phase18    private(set) var isWorking = false19    /// Shown on the sign-in screen (refused verification, revoked session, network).20    var notice: String?2122    @ObservationIgnored private let http: HTTPClient23    @ObservationIgnored private let api: ChatAPI24    @ObservationIgnored let passkeys: PasskeyService25    /// Called after the local session disappeared (sign-out or revocation): caches are wiped by the environment.26    @ObservationIgnored var onSignedOut: (@MainActor () async -> Void)?27    @ObservationIgnored var onSignedIn: (@MainActor () async -> Void)?2829    init(http: HTTPClient, api: ChatAPI, passkeys: PasskeyService, hasStoredSession: Bool) {30        self.http = http; self.api = api; self.passkeys = passkeys31        // A stored token opens the app at once (offline reading); the first request tells whether it is still valid.32        phase = hasStoredSession ? .signedIn : .signedOut33    }3435    func installHandlers() async {36        await http.setSessionLostHandler { [weak self] in await self?.sessionWasRevoked() }37        await http.setReauthHandler { [weak self] in38            guard let self else { throw APIError.cancelled }39            try await self.passkeys.reauthenticate()40        }41    }4243    func signIn() async {44        await run { try await self.passkeys.signIn() }45    }4647    /// Bootstrap or recovery code → enrolment window → passkey for this device → session.48    func enroll(code: String, label: String?) async {49        await run {50            try await self.passkeys.redeemSetupCode(code)51            try await self.passkeys.register(label: label)52        }53    }5455    private func run(_ ceremony: @escaping () async throws -> Void) async {56        guard !isWorking else { return }57        isWorking = true; notice = nil58        defer { isWorking = false }59        do {60            try await ceremony()61            guard await http.hasSession else { notice = String(localized: "Le serveur n’a pas ouvert de session."); return }62            phase = .signedIn63            await onSignedIn?()64        } catch let e as PasskeyError {65            if e.kind != .cancelled { notice = e.message }66        } catch { notice = error.localizedDescription }67    }6869    /// Sign-out: the server revokes the session (best effort when offline), then every local trace is removed.70    func signOut() async {71        try? await api.logout()72        await http.clearSession()73        phase = .signedOut74        await onSignedOut?()75    }7677    /// The server answered 401 `locked`: the session expired or was revoked from another device.78    private func sessionWasRevoked() async {79        guard phase == .signedIn else { return }80        phase = .signedOut81        notice = String(localized: "Session terminée. Connecte-toi de nouveau avec ta clé d’accès.")82        await onSignedOut?()83    }8485    #if DEBUG86    func debugMarkSignedIn() { phase = .signedIn }87    #endif88}89
Files main
Menu

Theme