|
| 1 | +import LocalAuthentication |
| 2 | +import Foundation |
| 3 | +import SwiftUI |
| 4 | +import Combine |
| 5 | + |
| 6 | +func authenticateWithTouchIDOrPassword(completion: @escaping (Bool) -> Void) { |
| 7 | + let context = LAContext() |
| 8 | + var error: NSError? |
| 9 | + |
| 10 | + if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { |
| 11 | + // Try Touch ID/Face ID |
| 12 | + context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Authenticate to elevate privileges") { success, authError in |
| 13 | + if success { |
| 14 | + // Authentication successful |
| 15 | + DispatchQueue.main.async { |
| 16 | + completion(true) |
| 17 | + } |
| 18 | + } else { |
| 19 | + // Fallback to password |
| 20 | + authenticateWithPassword(completion: completion) |
| 21 | + } |
| 22 | + } |
| 23 | + } else { |
| 24 | + // Biometrics unavailable, fallback to password |
| 25 | + authenticateWithPassword(completion: completion) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +func authenticateWithPassword(completion: @escaping (Bool) -> Void) { |
| 30 | + let context = LAContext() |
| 31 | + var error: NSError? |
| 32 | + |
| 33 | + // Check if deviceOwnerAuthentication (password fallback) is available |
| 34 | + if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) { |
| 35 | + context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Authenticate to elevate privileges") { success, authError in |
| 36 | + DispatchQueue.main.async { |
| 37 | + if success { |
| 38 | + // Authentication successful |
| 39 | + completion(true) |
| 40 | + } else { |
| 41 | + // Authentication failed |
| 42 | + completion(false) |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } else { |
| 47 | + // Device owner authentication not available |
| 48 | + DispatchQueue.main.async { |
| 49 | + completion(false) |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func saveReasonToDisk(reason: String) { |
| 55 | + let fileManager = FileManager.default |
| 56 | + let appState = AppStateManager.shared |
| 57 | + |
| 58 | + // Get the Application Support directory |
| 59 | + guard let appSupportDirectory = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { |
| 60 | + Logger.shared.logError("Failed to locate Application Support directory.") |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // Create a subdirectory for your app if needed |
| 65 | + let appDirectory = appSupportDirectory.appendingPathComponent("SupportCompanion") |
| 66 | + |
| 67 | + do { |
| 68 | + // Ensure the directory exists |
| 69 | + if !fileManager.fileExists(atPath: appDirectory.path) { |
| 70 | + try fileManager.createDirectory(at: appDirectory, withIntermediateDirectories: true, attributes: nil) |
| 71 | + } |
| 72 | + } catch { |
| 73 | + Logger.shared.logError("Error creating app directory: \(error.localizedDescription)") |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + // Define the file URL |
| 78 | + let fileURL = appDirectory.appendingPathComponent("ElevationReasons.json") |
| 79 | + |
| 80 | + // Debug: Log the file URL |
| 81 | + Logger.shared.logDebug("Saving reason to: \(fileURL.path)") |
| 82 | + |
| 83 | + // Get the current date |
| 84 | + let dateFormatter = ISO8601DateFormatter() |
| 85 | + let currentDate = dateFormatter.string(from: Date()) |
| 86 | + |
| 87 | + // Create a dictionary to save |
| 88 | + let entry: [String: Any] = [ |
| 89 | + "reason": reason, |
| 90 | + "date": currentDate, |
| 91 | + "user": NSUserName(), |
| 92 | + "host": Host.current().localizedName ?? "Unknown", |
| 93 | + "serial": appState.deviceInfoManager.deviceInfo?.serialNumber ?? "Unknown", |
| 94 | + "severity": appState.preferences.elevationSeverity |
| 95 | + ] |
| 96 | + |
| 97 | + var existingEntries: [[String: Any]] = [] |
| 98 | + |
| 99 | + // Read existing entries if the file exists |
| 100 | + if let data = try? Data(contentsOf: fileURL), |
| 101 | + let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String: String]] { |
| 102 | + existingEntries = json |
| 103 | + } |
| 104 | + |
| 105 | + // Add the new entry |
| 106 | + existingEntries.append(entry) |
| 107 | + |
| 108 | + // Save back to disk |
| 109 | + do { |
| 110 | + let data = try JSONSerialization.data(withJSONObject: existingEntries, options: [.prettyPrinted]) |
| 111 | + try data.write(to: fileURL, options: .atomic) // Atomic ensures safe writes |
| 112 | + Logger.shared.logDebug("Reason saved successfully.") |
| 113 | + } catch { |
| 114 | + Logger.shared.logError("Error saving reason: \(error.localizedDescription)") |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +func sendReasonToWebhook(reason: String) { |
| 119 | + let dateFormatter = ISO8601DateFormatter() |
| 120 | + let appState = AppStateManager.shared |
| 121 | + |
| 122 | + // Define the webhook URL |
| 123 | + let webhookURL = URL(string: appState.preferences.elevationWebhookURL)! |
| 124 | + |
| 125 | + // Create a dictionary with the reason |
| 126 | + let payload: [String: Any] = [ |
| 127 | + "reason": reason, |
| 128 | + "date": dateFormatter.string(from: Date()), |
| 129 | + "user": NSUserName(), |
| 130 | + "host": Host.current().localizedName ?? "Unknown", |
| 131 | + "serial": appState.deviceInfoManager.deviceInfo?.serialNumber ?? "Unknown", |
| 132 | + "severity":appState.preferences.elevationSeverity |
| 133 | + ] |
| 134 | + |
| 135 | + // Serialize the dictionary to JSON |
| 136 | + guard let jsonData = try? JSONSerialization.data(withJSONObject: payload) else { |
| 137 | + print("Failed to serialize JSON.") |
| 138 | + return |
| 139 | + } |
| 140 | + |
| 141 | + // Create a POST request |
| 142 | + var request = URLRequest(url: webhookURL) |
| 143 | + request.httpMethod = "POST" |
| 144 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 145 | + request.httpBody = jsonData |
| 146 | + |
| 147 | + // Create a URLSession task |
| 148 | + let task = URLSession.shared.dataTask(with: request) { data, response, error in |
| 149 | + if let error = error { |
| 150 | + saveReasonToDisk(reason: reason) |
| 151 | + Logger.shared.logError("Failed to send reason to webhook: \(error.localizedDescription)") |
| 152 | + return |
| 153 | + } |
| 154 | + |
| 155 | + if let response = response as? HTTPURLResponse { |
| 156 | + if response.statusCode == 200 || response.statusCode == 202 { |
| 157 | + print("Reason sent to webhook successfully.") |
| 158 | + } else { |
| 159 | + // Fallback to save to disk if webhook fails |
| 160 | + saveReasonToDisk(reason: reason) |
| 161 | + Logger.shared.logError("Failed to send reason to webhook. Status code: \(response.statusCode)") |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + // Start the task |
| 167 | + task.resume() |
| 168 | +} |
0 commit comments