|
1 | 1 | import Foundation |
2 | 2 | import WordPressShared |
| 3 | +import KeychainAccess |
| 4 | + |
| 5 | +enum ApplicationPasswordUseCaseError: Error { |
| 6 | + case duplicateName |
| 7 | + case applicationPasswordsDisabled |
| 8 | +} |
3 | 9 |
|
4 | 10 | struct ApplicationPassword { |
5 | 11 | /// WordPress org username that the application password belongs to |
@@ -28,3 +34,235 @@ protocol ApplicationPasswordUseCase { |
28 | 34 | /// |
29 | 35 | func deletePassword() async throws |
30 | 36 | } |
| 37 | + |
| 38 | +final class DefaultApplicationPasswordUseCase: ApplicationPasswordUseCase { |
| 39 | + /// WordPress.com Credentials. |
| 40 | + /// |
| 41 | + private let credentials: Credentials |
| 42 | + |
| 43 | + /// SiteID needed when using WPCOM credentials |
| 44 | + /// |
| 45 | + private let siteID: Int64 |
| 46 | + |
| 47 | + /// To generate and delete application password |
| 48 | + /// |
| 49 | + private let network: Network |
| 50 | + |
| 51 | + /// Stores the application password |
| 52 | + /// |
| 53 | + private let keychain: Keychain |
| 54 | + |
| 55 | + /// Used to name the password in wpadmin. |
| 56 | + /// |
| 57 | + private var applicationPasswordName: String { |
| 58 | + get async { |
| 59 | + let bundleIdentifier = Bundle.main.bundleIdentifier ?? "Unknown" |
| 60 | + let model = await UIDevice.current.model |
| 61 | + return bundleIdentifier + ".ios-app-client." + model |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + init(siteID: Int64, |
| 66 | + networkcredentials: Credentials, |
| 67 | + network: Network? = nil, |
| 68 | + keychain: Keychain = Keychain(service: KeychainServiceName.name)) { |
| 69 | + self.siteID = siteID |
| 70 | + self.credentials = networkcredentials |
| 71 | + self.keychain = keychain |
| 72 | + |
| 73 | + if let network { |
| 74 | + self.network = network |
| 75 | + } else { |
| 76 | + self.network = ApplicationPasswordNetwork(credentials: networkcredentials) |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// Returns the locally saved ApplicationPassword if available |
| 81 | + /// |
| 82 | + var applicationPassword: ApplicationPassword? { |
| 83 | + guard let password = keychain.applicationPassword, |
| 84 | + let username = keychain.applicationPasswordUsername else { |
| 85 | + return nil |
| 86 | + } |
| 87 | + return ApplicationPassword(wpOrgUsername: username, password: Secret(password)) |
| 88 | + } |
| 89 | + |
| 90 | + /// Generates new ApplicationPassword |
| 91 | + /// |
| 92 | + /// When `duplicateName` error occurs this method will delete the password and try generating again |
| 93 | + /// |
| 94 | + /// - Returns: Generated `ApplicationPassword` instance |
| 95 | + /// |
| 96 | + func generateNewPassword() async throws -> ApplicationPassword { |
| 97 | + async let password = try { |
| 98 | + do { |
| 99 | + return try await createApplicationPasswordUsingWPCOMAuthToken() |
| 100 | + } catch ApplicationPasswordUseCaseError.duplicateName { |
| 101 | + try await deletePassword() |
| 102 | + return try await createApplicationPasswordUsingWPCOMAuthToken() |
| 103 | + } |
| 104 | + }() |
| 105 | + async let username = try fetchWPAdminUsername() |
| 106 | + |
| 107 | + let applicationPassword = try await ApplicationPassword(wpOrgUsername: username, password: Secret(password)) |
| 108 | + saveApplicationPassword(applicationPassword) |
| 109 | + return applicationPassword |
| 110 | + } |
| 111 | + |
| 112 | + /// Deletes the application password |
| 113 | + /// |
| 114 | + /// Deletes locally and also sends an API request to delete it from the site |
| 115 | + /// |
| 116 | + func deletePassword() async throws { |
| 117 | + try await deleteApplicationPasswordUsingWPCOMAuthToken() |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +private extension DefaultApplicationPasswordUseCase { |
| 122 | + /// Creates application password using WordPress.com authentication token |
| 123 | + /// |
| 124 | + /// - Returns: Application password as `String` |
| 125 | + /// |
| 126 | + func createApplicationPasswordUsingWPCOMAuthToken() async throws -> String { |
| 127 | + let passwordName = await applicationPasswordName |
| 128 | + |
| 129 | + let parameters = [ParameterKey.name: passwordName] |
| 130 | + let request = JetpackRequest(wooApiVersion: .none, method: .post, siteID: siteID, path: Path.applicationPasswords, parameters: parameters) |
| 131 | + |
| 132 | + return try await withCheckedThrowingContinuation { continuation in |
| 133 | + network.responseData(for: request) { result in |
| 134 | + switch result { |
| 135 | + case .success(let data): |
| 136 | + do { |
| 137 | + let validator = request.responseDataValidator() |
| 138 | + try validator.validate(data: data) |
| 139 | + let mapper = ApplicationPasswordMapper() |
| 140 | + let password = try mapper.map(response: data) |
| 141 | + continuation.resume(returning: password) |
| 142 | + } catch let DotcomError.unknown(code, _) where code == ErrorCode.applicationPasswordsDisabledErrorCode { |
| 143 | + continuation.resume(throwing: ApplicationPasswordUseCaseError.applicationPasswordsDisabled) |
| 144 | + } catch let DotcomError.unknown(code, _) where code == ErrorCode.duplicateNameErrorCode { |
| 145 | + continuation.resume(throwing: ApplicationPasswordUseCaseError.duplicateName) |
| 146 | + } catch { |
| 147 | + continuation.resume(throwing: error) |
| 148 | + } |
| 149 | + case .failure(let error): |
| 150 | + continuation.resume(throwing: error) |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + /// Fetches wpadmin username using WordPress.com authentication token |
| 157 | + /// |
| 158 | + /// - Returns: wpadmin username |
| 159 | + /// |
| 160 | + func fetchWPAdminUsername() async throws -> String { |
| 161 | + let parameters = [ |
| 162 | + "context": "edit", |
| 163 | + "fields": "id,username,id_wpcom,email,first_name,last_name,nickname,roles" |
| 164 | + ] |
| 165 | + let request = JetpackRequest(wooApiVersion: .none, method: .get, siteID: siteID, path: Path.users, parameters: parameters) |
| 166 | + |
| 167 | + return try await withCheckedThrowingContinuation { continuation in |
| 168 | + network.responseData(for: request) { [weak self] result in |
| 169 | + guard let self else { return } |
| 170 | + |
| 171 | + switch result { |
| 172 | + case .success(let data): |
| 173 | + do { |
| 174 | + let validator = request.responseDataValidator() |
| 175 | + try validator.validate(data: data) |
| 176 | + let mapper = UserMapper(siteID: self.siteID) |
| 177 | + let username = try mapper.map(response: data).username |
| 178 | + continuation.resume(returning: username) |
| 179 | + } catch { |
| 180 | + continuation.resume(throwing: error) |
| 181 | + } |
| 182 | + case .failure(let error): |
| 183 | + continuation.resume(throwing: error) |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + /// Deletes application password using WordPress.com authentication token |
| 190 | + /// |
| 191 | + func deleteApplicationPasswordUsingWPCOMAuthToken() async throws { |
| 192 | + // Delete password from keychain |
| 193 | + keychain.applicationPassword = nil |
| 194 | + keychain.applicationPasswordUsername = nil |
| 195 | + |
| 196 | + let passwordName = await applicationPasswordName |
| 197 | + |
| 198 | + let parameters = [ParameterKey.name: passwordName] |
| 199 | + let request = JetpackRequest(wooApiVersion: .none, method: .delete, siteID: siteID, path: Path.applicationPasswords, parameters: parameters) |
| 200 | + |
| 201 | + try await withCheckedThrowingContinuation { continuation in |
| 202 | + network.responseData(for: request) { result in |
| 203 | + switch result { |
| 204 | + case .success(let data): |
| 205 | + do { |
| 206 | + let validator = request.responseDataValidator() |
| 207 | + try validator.validate(data: data) |
| 208 | + continuation.resume() |
| 209 | + } catch { |
| 210 | + continuation.resume(throwing: error) |
| 211 | + } |
| 212 | + case .failure(let error): |
| 213 | + continuation.resume(throwing: error) |
| 214 | + } |
| 215 | + } |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + /// Saves application password into keychain |
| 220 | + /// |
| 221 | + /// - Parameter password: `ApplicationPasword` to be saved |
| 222 | + /// |
| 223 | + func saveApplicationPassword(_ password: ApplicationPassword) { |
| 224 | + keychain.applicationPassword = password.wpOrgUsername |
| 225 | + keychain.applicationPasswordUsername = password.password.secretValue |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +// MARK: - Constants |
| 230 | +// |
| 231 | +private extension DefaultApplicationPasswordUseCase { |
| 232 | + enum KeychainServiceName { |
| 233 | + /// Matching `WooConstants.keychainServiceName` |
| 234 | + /// |
| 235 | + static let name = "com.automattic.woocommerce" |
| 236 | + } |
| 237 | + |
| 238 | + enum Path { |
| 239 | + static let applicationPasswords = "wp/v2/users/me/application-passwords" |
| 240 | + static let users = "wp/v2/users/me" |
| 241 | + } |
| 242 | + |
| 243 | + enum ParameterKey { |
| 244 | + static let name = "name" |
| 245 | + } |
| 246 | + |
| 247 | + enum ErrorCode { |
| 248 | + static let applicationPasswordsDisabledErrorCode = "application_passwords_disabled" |
| 249 | + static let duplicateNameErrorCode = "application_password_duplicate_name" |
| 250 | + } |
| 251 | +} |
| 252 | + |
| 253 | +// MARK: - For storing the application password in keychain |
| 254 | +// |
| 255 | +private extension Keychain { |
| 256 | + private static let keychainApplicationPassword = "ApplicationPassword" |
| 257 | + private static let keychainApplicationPasswordUsername = "ApplicationPasswordUsername" |
| 258 | + |
| 259 | + var applicationPassword: String? { |
| 260 | + get { self[Keychain.keychainApplicationPassword] } |
| 261 | + set { self[Keychain.keychainApplicationPassword] = newValue } |
| 262 | + } |
| 263 | + |
| 264 | + var applicationPasswordUsername: String? { |
| 265 | + get { self[Keychain.keychainApplicationPasswordUsername] } |
| 266 | + set { self[Keychain.keychainApplicationPasswordUsername] = newValue } |
| 267 | + } |
| 268 | +} |
0 commit comments