← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/AppLock.swift (8578B)

1import LocalAuthentication
2import OSLog
3import SwiftUI
4
5/// Whether the app locks, and how long after it's left. Kept in
6/// `UserDefaults` on each device and never synced.
7struct AppLockSettings: Codable, Equatable, Sendable {
8    /// How long the app can be in the background before it locks again.
9    enum Delay: Int, Codable, CaseIterable, Sendable {
10        case immediately = 0
11        case oneMinute = 60
12        case fiveMinutes = 300
13        case fifteenMinutes = 900
14
15        var seconds: TimeInterval { TimeInterval(rawValue) }
16    }
17
18    var isEnabled = false
19    var delay = Delay.immediately
20
21    /// Whether the app, left for the background at `leftAt`, is locked
22    /// again on its return at `now`.
23    func locks(leftAt: Date, now: Date) -> Bool {
24        isEnabled && now.timeIntervalSince(leftAt) >= delay.seconds
25    }
26}
27
28extension AppLockSettings {
29    private static let key = "appLockSettings"
30
31    static func load(from defaults: UserDefaults = .standard) -> AppLockSettings {
32        guard let data = defaults.data(forKey: key),
33            let settings = try? JSONDecoder().decode(AppLockSettings.self, from: data)
34        else { return AppLockSettings() }
35        return settings
36    }
37
38    func save(to defaults: UserDefaults = .standard) {
39        guard let data = try? JSONEncoder().encode(self) else { return }
40        defaults.set(data, forKey: Self.key)
41    }
42}
43
44/// Locks the app behind Face ID, or the device passcode when Face ID fails
45/// or isn't set up.
46///
47/// While the app is in the background with the lock on, a window above
48/// everything else blurs it, so the app switcher's snapshot shows nothing
49/// legible. While it's locked, the window shows the lock screen instead, and
50/// a survey opened from a notification waits beneath until the app is
51/// unlocked. Notification actions and App Intents show nothing, so
52/// they work while locked.
53@MainActor
54@Observable
55final class AppLock {
56    private(set) var settings: AppLockSettings
57    private(set) var isLocked: Bool
58    /// Whether the cover is shown: the lock screen while locked, and a blur
59    /// in the background.
60    private(set) var isCovered: Bool
61
62    /// When the app last went into the background unlocked. Only a return
63    /// from the background locks it: Face ID's own prompt and Control
64    /// Center make the app inactive without leaving it.
65    @ObservationIgnored private var leftAt: Date?
66    /// Set on leaving the app, so returning asks for Face ID once. The
67    /// prompt itself makes the app inactive and active again, which mustn't
68    /// ask again if it's cancelled.
69    @ObservationIgnored private var promptsOnReturn = true
70    /// Set while the app is in the background, so the return is handled
71    /// once, at whichever of inactive or active comes first.
72    @ObservationIgnored private var isInBackground = false
73    @ObservationIgnored private var window: UIWindow?
74    @ObservationIgnored private var isAuthenticating = false
75    private let defaults: UserDefaults
76    private let evaluate: @MainActor (String) async -> Bool
77
78    private static let logger = Logger(subsystem: "net.inqk.reportage", category: "AppLock")
79
80    /// `evaluate` asks for the owner with a reason, and says whether they
81    /// were; tests replace it.
82    init(
83        defaults: UserDefaults = .standard,
84        evaluate: @escaping @MainActor (String) async -> Bool = AppLock.askForOwner
85    ) {
86        self.defaults = defaults
87        self.evaluate = evaluate
88        let settings = AppLockSettings.load(from: defaults)
89        self.settings = settings
90        isLocked = settings.isEnabled
91        isCovered = settings.isEnabled
92    }
93
94    /// 'Face ID', 'Touch ID' or 'Passcode', whichever unlocks the app here.
95    var methodName: LocalizedStringResource {
96        let context = LAContext()
97        _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
98        switch context.biometryType {
99        case .faceID: return "Face ID"
100        case .touchID: return "Touch ID"
101        case .opticID: return "Optic ID"
102        default: return "Passcode"
103        }
104    }
105
106    /// Whether the device can lock the app at all: it needs a passcode.
107    var isAvailable: Bool {
108        LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)
109    }
110
111    // MARK: Scene phases
112
113    func didEnterBackground(now: Date = Date()) {
114        guard settings.isEnabled else { return }
115        if !isLocked { leftAt = now }
116        promptsOnReturn = true
117        isInBackground = true
118        isCovered = true
119        updateWindow()
120    }
121
122    /// On launch the scene is inactive before it's active, so the cover is
123    /// up before anything else is seen. On a return from the background
124    /// it's inactive first too, so the blur comes off as early as it can.
125    func didBecomeInactive(now: Date = Date()) {
126        returnFromBackground(now: now)
127        updateWindow()
128    }
129
130    /// Face ID can only be asked for once the app is active.
131    func didBecomeActive(now: Date = Date()) {
132        guard settings.isEnabled else { return }
133        returnFromBackground(now: now)
134        if isLocked {
135            updateWindow()
136            if promptsOnReturn {
137                promptsOnReturn = false
138                Task { await unlock() }
139            }
140        } else if isCovered {
141            isCovered = false
142            updateWindow()
143        }
144    }
145
146    /// Locks the app if it was away long enough, and otherwise uncovers it.
147    private func returnFromBackground(now: Date) {
148        guard isInBackground else { return }
149        isInBackground = false
150        if !isLocked, let leftAt, settings.locks(leftAt: leftAt, now: now) {
151            isLocked = true
152        }
153        leftAt = nil
154        if !isLocked { isCovered = false }
155    }
156
157    // MARK: Unlocking
158
159    /// Asks for Face ID, falling back to the passcode, and unlocks if it
160    /// succeeds.
161    func unlock() async {
162        guard isLocked else { return }
163        guard await authenticate(reason: String(localized: "Unlock Reportage")) else { return }
164        isLocked = false
165        isCovered = false
166        updateWindow()
167    }
168
169    /// Turns the lock on or off after Face ID confirms it's the owner, so
170    /// someone holding the unlocked phone can't turn it off.
171    func setEnabled(_ isEnabled: Bool) async {
172        guard isEnabled != settings.isEnabled else { return }
173        let reason =
174            isEnabled
175            ? String(localized: "Turn on the lock for Reportage")
176            : String(localized: "Turn off the lock for Reportage")
177        guard await authenticate(reason: reason) else { return }
178        settings.isEnabled = isEnabled
179        settings.save(to: defaults)
180    }
181
182    func setDelay(_ delay: AppLockSettings.Delay) {
183        settings.delay = delay
184        settings.save(to: defaults)
185    }
186
187    private func authenticate(reason: String) async -> Bool {
188        guard !isAuthenticating else { return false }
189        isAuthenticating = true
190        defer { isAuthenticating = false }
191        return await evaluate(reason)
192    }
193
194    /// Face ID, or the passcode when it fails or isn't set up.
195    static func askForOwner(reason: String) async -> Bool {
196        do {
197            return try await LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)
198        } catch {
199            logger.notice("Authentication didn't succeed: \(error)")
200            return false
201        }
202    }
203
204    // MARK: Cover
205
206    /// Shows or hides the cover window. It's a window of its own because
207    /// sheets, such as a survey, are presented above anything in the app's
208    /// own window.
209    private func updateWindow() {
210        if isCovered {
211            guard window == nil, let scene = Self.windowScene else { return }
212            let window = UIWindow(windowScene: scene)
213            window.windowLevel = .alert + 1
214            // Clear, so the blur shows the app beneath it.
215            let controller = UIHostingController(rootView: CoverView(lock: self))
216            controller.view.backgroundColor = .clear
217            window.rootViewController = controller
218            window.backgroundColor = .clear
219            window.isHidden = false
220            self.window = window
221        } else {
222            window?.isHidden = true
223            window = nil
224        }
225    }
226
227    private static var windowScene: UIWindowScene? {
228        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
229        return scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
230    }
231}