Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Security/AppLock.swift4// Description: Optional biometric lock of the app (Face ID / Touch ID / device passcode) with LocalAuthentication.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation11import LocalAuthentication12import Observation1314/// Local lock of the app's window. It protects the content already on the device from someone holding the unlocked15/// phone; it is independent of the server session and nothing biometric is ever sent anywhere: LocalAuthentication16/// answers yes or no.17@MainActor18@Observable19final class AppLock {20 enum Grace: Int, CaseIterable, Identifiable, Sendable {21 case immediately = 0, oneMinute = 60, fiveMinutes = 30022 var id: Int { rawValue }23 }24 private(set) var isLocked = false25 private(set) var isAuthenticating = false26 private(set) var lastError: String?27 /// True while the app is not active: the content is covered in the app switcher.28 var isObscured = false2930 var isEnabled: Bool { didSet { defaults.set(isEnabled, forKey: Keys.enabled) } }31 var grace: Grace { didSet { defaults.set(grace.rawValue, forKey: Keys.grace) } }3233 private let defaults: UserDefaults34 private var backgroundedAt: Date?35 private enum Keys { static let enabled = "applock.enabled"; static let grace = "applock.grace" }3637 init(defaults: UserDefaults = .standard) {38 self.defaults = defaults39 isEnabled = defaults.bool(forKey: Keys.enabled)40 grace = Grace(rawValue: defaults.integer(forKey: Keys.grace)) ?? .immediately41 isLocked = isEnabled42 }4344 /// What the device can do, for labels ("Face ID", "Touch ID", "code de l'appareil").45 static var biometryName: String {46 let ctx = LAContext(); _ = ctx.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)47 switch ctx.biometryType {48 case .faceID: return "Face ID"49 case .touchID: return "Touch ID"50 case .opticID: return "Optic ID"51 default: return String(localized: "le code de l’appareil")52 }53 }54 static var canAuthenticate: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }5556 func didEnterBackground() {57 backgroundedAt = Date()58 }5960 func willEnterForeground() {61 guard isEnabled, let t = backgroundedAt else { return }62 if Date().timeIntervalSince(t) >= Double(grace.rawValue) { isLocked = true }63 backgroundedAt = nil64 }6566 /// Turning the lock on requires proving the user can pass it (otherwise the app could lock its owner out).67 func setEnabled(_ on: Bool) async -> Bool {68 guard await evaluate(reason: on ? String(localized: "Activer le verrouillage de SP Chat") : String(localized: "Désactiver le verrouillage de SP Chat")) else { return false }69 isEnabled = on; isLocked = false70 return true71 }7273 func unlock() async {74 guard isLocked, !isAuthenticating else { return }75 if await evaluate(reason: String(localized: "Déverrouiller SP Chat")) { isLocked = false; lastError = nil }76 }7778 /// Right after a passkey sign-in (the owner has just passed Face ID / Touch ID): the lock is switched on by default,79 /// so every later opening of the app asks for biometrics, like the web app asks for the passkey. It stays a80 /// choice: the owner can turn it off in the settings, and that choice is then respected.81 func enableByDefaultAfterSignIn() {82 guard defaults.object(forKey: Keys.enabled) == nil, Self.canAuthenticate else { return }83 isEnabled = true; isLocked = false84 }8586 /// Forgets the lock setting (sign-out).87 func reset() { isEnabled = false; isLocked = false; backgroundedAt = nil; defaults.removeObject(forKey: Keys.enabled) }8889 private func evaluate(reason: String) async -> Bool {90 isAuthenticating = true; defer { isAuthenticating = false }91 let ctx = LAContext()92 ctx.localizedCancelTitle = String(localized: "Annuler")93 var err: NSError?94 // deviceOwnerAuthentication: biometrics first, device passcode as the system fallback95 guard ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: &err) else {96 lastError = String(localized: "Aucun code ni biométrie n’est configuré sur cet appareil.")97 return false98 }99 do { return try await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) }100 catch let e as LAError {101 if e.code != .userCancel && e.code != .appCancel && e.code != .systemCancel { lastError = String(localized: "Vérification refusée.") }102 return false103 } catch { return false }104 }105}106