Repository Public
1// SP Music iOS2// File: Core/Sources/SPMusicCore/Authentication/AuthService.swift3// Description: Session state, sign-in flows, sign-out, optional biometric app lock.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import AuthenticationServices9import Foundation10import LocalAuthentication11import Observation1213/// Who is using the app. The session is the site's own (passkeys, 30 days; device link, 90 days); the token lives in14/// the Keychain, so the app opens without asking again while the session is valid — and opens offline too.15@MainActor @Observable16public final class AuthService {17 public enum State: Equatable, Sendable { case launching, signedOut, signedIn }18 public private(set) var state = State.launching19 public private(set) var me: Me?20 /// The server could not be reached at launch: the session is assumed valid until it says otherwise.21 public private(set) var unverified = false22 /// Signed out, but listening to what is on the device.23 public var offlineGuest = false2425 @ObservationIgnored public let api: APIClient26 @ObservationIgnored private let defaults: UserDefaults27 @ObservationIgnored private var onSignedIn: [@MainActor () async -> Void] = []28 @ObservationIgnored private var onSignedOut: [@MainActor () async -> Void] = []2930 public init(api: APIClient, defaults: UserDefaults = .standard) {31 self.api = api; self.defaults = defaults32 me = defaults.data(forKey: "account.me").flatMap { try? JSONDecoder().decode(Me.self, from: $0) }33 api.onUnauthenticated { [weak self] in Task { @MainActor in await self?.sessionEnded() } }34 }3536 public func whenSignedIn(_ f: @escaping @MainActor () async -> Void) { onSignedIn.append(f) }37 public func whenSignedOut(_ f: @escaping @MainActor () async -> Void) { onSignedOut.append(f) }38 public var canUseLibrary: Bool { state == .signedIn || offlineGuest }3940 /// At launch, and again when the network comes back.41 public func refresh() async {42 guard api.hasSession else { me = nil; state = .signedOut; return }43 do {44 let s = try await api.sessionInfo()45 if s.authenticated, let user = s.user { await adopt(user) }46 else { await sessionEnded() }47 } catch {48 // Offline or server down: keep going with what is on the device.49 unverified = true50 if state != .signedIn { state = .signedIn; for f in onSignedIn { await f() } }51 }52 }5354 private func adopt(_ user: Me) async {55 let wasSignedIn = state == .signedIn && !unverified56 me = user; unverified = false; offlineGuest = false57 if let d = try? JSONEncoder().encode(user) { defaults.set(d, forKey: "account.me") }58 state = .signedIn59 if !wasSignedIn { for f in onSignedIn { await f() } }60 }6162 private func completeSignIn() async throws {63 let s = try await api.sessionInfo()64 guard s.authenticated, let user = s.user else { throw APIError(status: 401, code: "login_failed", message: "Connexion refusée") }65 state = .signedOut // force the sign-in hooks to run for the new session66 await adopt(user)67 }6869 public func signInWithPasskey(anchor: ASPresentationAnchor) async throws {70 try await api.signInWithPasskey(anchor: anchor)71 try await completeSignIn()72 }7374 /// `link` is the enrolment link received from the administrator (https://…/setup#<token>) or the bare token.75 public func enrol(link: String, anchor: ASPresentationAnchor, deviceName: String) async throws -> [String]? {76 let token = Self.setupToken(from: link)77 guard token.count >= 20 else { throw APIError(status: 403, code: "invalid_setup_token", message: "Lien invalide") }78 let codes = try await api.registerPasskey(anchor: anchor, setupToken: token, name: deviceName)79 try await completeSignIn()80 return codes81 }82 public nonisolated static func setupToken(from link: String) -> String {83 let s = link.trimmingCharacters(in: .whitespacesAndNewlines)84 return s.split(separator: "#").count > 1 ? String(s.split(separator: "#").last!) : s85 }8687 /// Adds a passkey for this device to the account that is signed in (after a device link or a recovery code).88 public func addPasskey(anchor: ASPresentationAnchor, deviceName: String) async throws {89 _ = try await api.registerPasskey(anchor: anchor, setupToken: nil, name: deviceName)90 }9192 public func signIn(recoveryCode: String) async throws {93 try await api.loginWithRecoveryCode(recoveryCode.trimmingCharacters(in: .whitespacesAndNewlines).lowercased())94 try await completeSignIn()95 }9697 /// Device link: the app shows a code, a browser already signed in approves it at /appareil.98 public func startDeviceLink(deviceName: String) async throws -> DeviceLinkStart { try await api.startDeviceLink(deviceName: deviceName) }99 public func awaitDeviceLink(_ link: DeviceLinkStart) async throws {100 let deadline = Date().addingTimeInterval(TimeInterval(link.expiresIn))101 while Date() < deadline {102 try await Task.sleep(for: .seconds(max(2, link.interval)))103 let r: DeviceLinkPoll104 do { r = try await api.pollDeviceLink(deviceCode: link.deviceCode) }105 catch let e as APIError where e.isNetwork { continue }106 if r.status == "approved", let token = r.sessionToken {107 api.adoptSession(token: token, csrf: r.csrfToken)108 try await completeSignIn()109 return110 }111 }112 throw APIError(status: 410, code: "expired", message: "Le code a expiré.")113 }114115 public func signOut() async {116 try? await api.logout()117 await sessionEnded()118 }119120 private func sessionEnded() async {121 guard state != .signedOut || api.hasSession else { state = .signedOut; return }122 api.forgetSession()123 me = nil; unverified = false124 defaults.removeObject(forKey: "account.me")125 state = .signedOut126 for f in onSignedOut { await f() }127 }128}129130/// Optional app lock: Face ID / Touch ID (or the device passcode) when the app comes to the front.131/// It protects the screen of an unlocked phone; it is not what protects the session (the Keychain does).132public enum BiometricLock {133 public static var kindName: String {134 let c = LAContext()135 _ = c.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)136 switch c.biometryType {137 case .faceID: return "Face ID"138 case .touchID: return "Touch ID"139 case .opticID: return "Optic ID"140 default: return "code de l'appareil"141 }142 }143 public static var isAvailable: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }144 public static func unlock(reason: String = "Déverrouiller SP Music") async -> Bool {145 let c = LAContext()146 c.localizedCancelTitle = "Annuler"147 guard c.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) else { return true } // nothing to check against148 return (try? await c.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) ?? false149 }150}151