Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Core/Account/Account.swift10// Description : session du compte (facultatif) — état connecté ou non,11// jeton gardé dans le trousseau, opérations du compte,12// passage propre à l'état déconnecté sur un 40113// `non_authentifie`. La mémoire locale n'est jamais effacée14// par cette couche.15// Module : ImmoKa16// Repository : https://git.spboucher.ai/immo-ka-ios-v317// Project Website : https://www.immo-ka.com18// Created : 2026-11-3019// Last Modified : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import Observation9596@MainActor97@Observable98final class Account {99 private static let tokenKey = "session.token"100 private static let userKey = "session.user"101102 /// Utilisateur connecté ; nil : pas de compte sur cet appareil.103 private(set) var user: AccountUser?104 /// Vrai une fois : la session a été fermée par le serveur (expirée, révoquée) ; l'interface le dit.105 var sessionEnded = false106107 @ObservationIgnored let api: AccountAPI108 @ObservationIgnored let sync: SyncEngine109 /// Messagerie avec les courtiers (pastille des non-lus, brouillon en attente de connexion).110 let messaging: Messaging111 @ObservationIgnored private let store: any SecretStore112 @ObservationIgnored private let tokenBox: TokenBox113 @ObservationIgnored private let prefs: UserDefaults?114115 var isSignedIn: Bool { user != nil }116117 /// Jeton lu par le client d'API depuis n'importe quel fil, sans retourner au trousseau à chaque requête.118 final class TokenBox: @unchecked Sendable {119 private let lock = NSLock()120 private var value: String?121 func get() -> String? { lock.withLock { value } }122 func set(_ v: String?) { lock.withLock { value = v } }123 }124125 /// Adresse des routes de compte : la production, sauf adresse imposée pour les essais126 /// (`-IKBaseURL <url>` ou `IMMOKA_BASE_URL`). Jamais le repli de l'API publique : un mot de passe ne part127 /// que vers l'adresse voulue.128 nonisolated static func baseURL() -> URL {129 if let forced = UserDefaults.standard.string(forKey: "IKBaseURL") ?? ProcessInfo.processInfo.environment["IMMOKA_BASE_URL"],130 let u = URL(string: forced), u.scheme == "https" || u.host == "127.0.0.1" || u.host == "localhost" {131 return u132 }133 return APIClient.primary134 }135136 /// - Parameters:137 /// - store: trousseau (ou coffre en mémoire pour les tests et la base jetable)138 /// - defaults: où garder les retraits en attente ; nil : nulle part139 init(library: Library, store: any SecretStore = KeychainStore(), session: URLSession = AccountAPI.defaultSession,140 base: @escaping @Sendable () async -> URL = { Account.baseURL() }, defaults: UserDefaults? = .standard) {141 self.store = store142 prefs = defaults143 let box = TokenBox()144 tokenBox = box145 api = AccountAPI(session: session, base: base, token: { box.get() })146 sync = SyncEngine(library: library, api: api, defaults: defaults)147 messaging = Messaging(api: api)148 if let token = store.string(Account.tokenKey), !token.isEmpty {149 box.set(token)150 // fiche gardée avec le jeton : l'état « connecté » s'affiche sans attendre le réseau151 user = store.read(Account.userKey).flatMap { try? JSONDecoder().decode(AccountUser.self, from: $0) }152 ?? AccountUser(id: "")153 }154 // les favoris d'un compte de courtier ne sont pas synchronisés (comme sur le site)155 sync.isSignedIn = { [weak self] in self?.user.map { !$0.isBroker } ?? false }156 sync.onUnauthenticated = { [weak self] in self?.endSession(byServer: true) }157 messaging.user = { [weak self] in self?.user }158 messaging.onUnauthenticated = { [weak self] in self?.endSession(byServer: true) }159 }160161 // MARK: État162163 private func begin(_ s: AccountSession) throws {164 guard let token = s.session?.token, !token.isEmpty else { throw AccountError.decoding }165 guard store.set(Account.tokenKey, token) else { throw AccountError.http(0) }166 tokenBox.set(token)167 remember(s.user)168 sessionEnded = false169 }170171 private func remember(_ u: AccountUser) {172 user = u173 if let d = try? JSONEncoder().encode(u) { store.write(Account.userKey, d) }174 }175176 /// Repasse à l'état déconnecté : jeton effacé, plus rien n'est envoyé. La mémoire locale reste.177 private func endSession(byServer: Bool) {178 guard isSignedIn || tokenBox.get() != nil else { return }179 store.delete(Account.tokenKey)180 store.delete(Account.userKey)181 tokenBox.set(nil)182 user = nil183 sync.reset()184 messaging.reset()185 if byServer { sessionEnded = true }186 }187188 /// Exécute un appel authentifié ; un 401 `non_authentifie` ferme la session locale.189 private func authed<T: Sendable>(_ call: () async throws -> T) async throws -> T {190 do { return try await call() } catch let e as AccountError {191 if e.isUnauthenticated { endSession(byServer: true) }192 throw e193 }194 }195196 // MARK: Inscription, vérification, connexion197198 /// Ce que le serveur offre à l'inscription ; `fallback` (courriel seul) tant qu'il n'a pas répondu.199 private(set) var options = AccountOptions.fallback200201 /// Relit les options du serveur. Si la requête échoue, le cellulaire n'est pas offert.202 func loadOptions() async {203 options = (try? await api.options()) ?? .fallback204 }205206 /// Dernier mode de connexion choisi (courriel ou cellulaire). Seul le mode est gardé, jamais le numéro.207 nonisolated static let modeKey = "compte.mode"208 var lastMode: AccountIdentifier.Mode {209 get { AccountIdentifier.Mode(rawValue: prefs?.string(forKey: Account.modeKey) ?? "") ?? .email }210 set { prefs?.set(newValue.rawValue, forKey: Account.modeKey) }211 }212213 /// Inscription ; rend ce que le serveur dit de l'envoi (`phone_display` pour un texto).214 @discardableResult215 func signUp(_ id: AccountIdentifier, password: String, name: String) async throws -> AccountAccepted {216 try await api.signUp(id, password: password, name: name.trimmingCharacters(in: .whitespacesAndNewlines))217 }218219 func resendCode(_ id: AccountIdentifier) async throws { try await api.resendVerification(id) }220221 /// Code reçu par courriel ou par texto : ouvre la session, puis synchronise.222 func verify(_ id: AccountIdentifier, code: String) async throws {223 try begin(try await api.verify(id, code: code))224 lastMode = id.mode225 await sync.sync()226 await messaging.refreshUnread(active: true)227 }228229 /// Connexion par courriel ou par numéro, avec le mot de passe (jamais de texto à la connexion).230 func signIn(_ id: AccountIdentifier, password: String) async throws {231 try begin(try await api.signIn(id, password: password))232 lastMode = id.mode233 await sync.sync()234 await messaging.refreshUnread(active: true)235 }236237 func forgotPassword(_ id: AccountIdentifier) async throws { try await api.forgotPassword(id) }238239 func resetPassword(_ id: AccountIdentifier, code: String, password: String) async throws {240 try begin(try await api.resetPassword(id, code: code, password: password))241 lastMode = id.mode242 await sync.sync()243 await messaging.refreshUnread(active: true)244 }245246 // formes par courriel, gardées pour les appelants existants247 func signUp(email: String, password: String, name: String) async throws { try await signUp(.email(email), password: password, name: name) }248 func resendCode(email: String) async throws { try await resendCode(.email(email)) }249 func forgotPassword(email: String) async throws { try await forgotPassword(.email(email)) }250 func verify(email: String, code: String) async throws { try await verify(.email(email), code: code) }251 func signIn(email: String, password: String) async throws { try await signIn(.email(email), password: password) }252 func resetPassword(email: String, code: String, password: String) async throws { try await resetPassword(.email(email), code: code, password: password) }253254 /// Se déconnecter : la session du serveur est fermée si le réseau le permet ; l'appareil l'oublie de toute façon.255 func signOut() async {256 await sync.settle()257 try? await api.signOut()258 endSession(byServer: false)259 }260261 // MARK: Compte262263 /// Relit le compte (nom changé ailleurs, session toujours valide ?). Hors ligne : sans effet.264 func refresh() async {265 guard isSignedIn else { return }266 if let s = try? await authed({ try await api.me() }) { remember(s.user) }267 }268269 func rename(_ name: String) async throws {270 remember(try await authed { try await api.rename(name.trimmingCharacters(in: .whitespacesAndNewlines)) })271 }272273 func changePassword(current: String, new: String) async throws {274 try await authed { try await api.changePassword(current: current, new: new) }275 }276277 func devices() async throws -> [DeviceSession] { try await authed { try await api.sessions() } }278 func revoke(_ device: DeviceSession) async throws { try await authed { try await api.revokeSession(device.id) } }279 func signOutEverywhereElse() async throws -> Int { try await authed { try await api.signOutEverywhereElse() } }280281 /// Supprime le compte et tout ce qu'il contient sur le serveur. La mémoire de l'appareil reste.282 func deleteAccount(password: String) async throws {283 await sync.settle()284 try await authed { try await api.deleteAccount(password: password) }285 endSession(byServer: false)286 }287288 /// Retour au premier plan : la session est-elle toujours valide, quoi de neuf sur les autres appareils ?289 func activate() async {290 guard isSignedIn else { return }291 await sync.syncIfStale()292 if isSignedIn, user?.id.isEmpty == true { await refresh() }293 await messaging.refreshUnread(active: true)294 }295296 // MARK: Validation locale (le serveur fait foi ; ceci évite un aller-retour évident)297298 nonisolated static func clean(_ email: String) -> String { email.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }299300 nonisolated static func emailLooksValid(_ email: String) -> Bool {301 let e = clean(email)302 guard e.count <= 254, let at = e.firstIndex(of: "@"), at != e.startIndex else { return false }303 let domain = e[e.index(after: at)...]304 return !domain.contains("@") && !e.contains(" ") && domain.contains(".") && !domain.hasPrefix(".") && !domain.hasSuffix(".")305 }306307 static let passwordMin = 8308 nonisolated static func codeDigits(_ s: String) -> String { String(s.filter(\.isNumber).prefix(6)) }309}310