Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/AppLock.swift3// Description: Optional local lock of the notes on this Mac (Touch ID or the Mac password through LocalAuthentication). Unrelated to the server session.4import SwiftUI5import LocalAuthentication67/// Hides the notes until the person at the keyboard proves to macOS who they are. This is a screen lock of the app, not8/// encryption: the local database is protected by the macOS account and FileVault, not by this lock.9@Observable final class AppLock {10 private(set) var isLocked = false11 private(set) var isAuthenticating = false12 var message: String?13 @ObservationIgnored private let preferences: Preferences14 @ObservationIgnored private var lastActive = Date()1516 init(preferences: Preferences) { self.preferences = preferences; isLocked = preferences.lockOnLaunch }1718 var isAvailable: Bool { var e: NSError?; return LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: &e) }19 var biometryName: String { let c = LAContext(); var e: NSError?; _ = c.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &e); return c.biometryType == .touchID ? "Touch ID" : "le mot de passe du Mac" }2021 func lock() { isLocked = true; message = nil }22 func noteActivity() { lastActive = Date() }23 /// Called when the application comes back to the front.24 func applicationBecameActive() {25 let minutes = preferences.lockAfterMinutes26 if minutes > 0, !isLocked, Date().timeIntervalSince(lastActive) > Double(minutes) * 60 { lock() }27 lastActive = Date()28 }29 func applicationResigned() { lastActive = Date() }3031 func unlock() async {32 guard isLocked, !isAuthenticating else { return }33 isAuthenticating = true; defer { isAuthenticating = false }34 let context = LAContext(); context.localizedCancelTitle = "Annuler"35 do {36 if try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "déverrouiller tes notes") { isLocked = false; message = nil; lastActive = Date() }37 } catch let e as LAError where e.code == .userCancel || e.code == .appCancel || e.code == .systemCancel { message = nil }38 catch { message = "Le déverrouillage n'a pas abouti." }39 }40}41