PhoneAuthProvider.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseCore
  15. import Foundation
  16. /// A concrete implementation of `AuthProvider` for phone auth providers.
  17. ///
  18. /// This class is available on iOS only.
  19. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. @objc(FIRPhoneAuthProvider) open class PhoneAuthProvider: NSObject {
  21. /// A string constant identifying the phone identity provider.
  22. @objc public static let id = "phone"
  23. #if os(iOS)
  24. /// Returns an instance of `PhoneAuthProvider` for the default `Auth` object.
  25. @objc(provider) open class func provider() -> PhoneAuthProvider {
  26. return PhoneAuthProvider(auth: Auth.auth())
  27. }
  28. /// Returns an instance of `PhoneAuthProvider` for the provided `Auth` object.
  29. /// - Parameter auth: The auth object to associate with the phone auth provider instance.
  30. @objc(providerWithAuth:)
  31. open class func provider(auth: Auth) -> PhoneAuthProvider {
  32. return PhoneAuthProvider(auth: auth)
  33. }
  34. /// Starts the phone number authentication flow by sending a verification code to the
  35. /// specified phone number.
  36. ///
  37. /// Possible error codes:
  38. /// * `AuthErrorCodeCaptchaCheckFailed` - Indicates that the reCAPTCHA token obtained by
  39. /// the Firebase Auth is invalid or has expired.
  40. /// * `AuthErrorCodeQuotaExceeded` - Indicates that the phone verification quota for this
  41. /// project has been exceeded.
  42. /// * `AuthErrorCodeInvalidPhoneNumber` - Indicates that the phone number provided is invalid.
  43. /// * `AuthErrorCodeMissingPhoneNumber` - Indicates that a phone number was not provided.
  44. /// - Parameter phoneNumber: The phone number to be verified.
  45. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  46. /// retained by this method until the completion block is executed.
  47. /// - Parameter completion: The callback to be invoked when the verification flow is finished.
  48. @objc(verifyPhoneNumber:UIDelegate:completion:)
  49. open func verifyPhoneNumber(_ phoneNumber: String,
  50. uiDelegate: AuthUIDelegate? = nil,
  51. completion: ((_: String?, _: Error?) -> Void)?) {
  52. verifyPhoneNumber(phoneNumber,
  53. uiDelegate: uiDelegate,
  54. multiFactorSession: nil,
  55. completion: completion)
  56. }
  57. /// Verify ownership of the second factor phone number by the current user.
  58. /// - Parameter phoneNumber: The phone number to be verified.
  59. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  60. /// retained by this method until the completion block is executed.
  61. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  62. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  63. /// passed the first factor challenge.
  64. /// - Parameter completion: The callback to be invoked when the verification flow is finished.
  65. @objc(verifyPhoneNumber:UIDelegate:multiFactorSession:completion:)
  66. open func verifyPhoneNumber(_ phoneNumber: String,
  67. uiDelegate: AuthUIDelegate? = nil,
  68. multiFactorSession: MultiFactorSession? = nil,
  69. completion: ((_: String?, _: Error?) -> Void)?) {
  70. Task {
  71. do {
  72. let verificationID = try await verifyPhoneNumber(
  73. phoneNumber,
  74. uiDelegate: uiDelegate,
  75. multiFactorSession: multiFactorSession
  76. )
  77. await MainActor.run {
  78. completion?(verificationID, nil)
  79. }
  80. } catch {
  81. await MainActor.run {
  82. completion?(nil, error)
  83. }
  84. }
  85. }
  86. }
  87. /// Verify ownership of the second factor phone number by the current user.
  88. /// - Parameter phoneNumber: The phone number to be verified.
  89. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  90. /// retained by this method until the completion block is executed.
  91. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  92. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  93. /// passed the first factor challenge.
  94. /// - Returns: The verification ID
  95. @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
  96. open func verifyPhoneNumber(_ phoneNumber: String,
  97. uiDelegate: AuthUIDelegate? = nil,
  98. multiFactorSession: MultiFactorSession? = nil) async throws
  99. -> String {
  100. guard AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: callbackScheme,
  101. urlTypes: auth.mainBundleUrlTypes) else {
  102. fatalError(
  103. "Please register custom URL scheme \(callbackScheme) in the app's Info.plist file."
  104. )
  105. }
  106. if let verificationID = try await internalVerify(phoneNumber: phoneNumber,
  107. uiDelegate: uiDelegate,
  108. multiFactorSession: multiFactorSession) {
  109. return verificationID
  110. } else {
  111. throw AuthErrorUtils.invalidVerificationIDError(message: "Invalid verification ID")
  112. }
  113. }
  114. /// Verify ownership of the second factor phone number by the current user.
  115. /// - Parameter multiFactorInfo: The phone multi factor whose number need to be verified.
  116. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  117. /// retained by this method until the completion block is executed.
  118. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  119. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  120. /// passed the first factor challenge.
  121. /// - Parameter completion: The callback to be invoked when the verification flow is finished.
  122. @objc(verifyPhoneNumberWithMultiFactorInfo:UIDelegate:multiFactorSession:completion:)
  123. open func verifyPhoneNumber(with multiFactorInfo: PhoneMultiFactorInfo,
  124. uiDelegate: AuthUIDelegate? = nil,
  125. multiFactorSession: MultiFactorSession?,
  126. completion: ((_: String?, _: Error?) -> Void)?) {
  127. Task {
  128. do {
  129. let verificationID = try await verifyPhoneNumber(
  130. with: multiFactorInfo,
  131. uiDelegate: uiDelegate,
  132. multiFactorSession: multiFactorSession
  133. )
  134. await MainActor.run {
  135. completion?(verificationID, nil)
  136. }
  137. } catch {
  138. await MainActor.run {
  139. completion?(nil, error)
  140. }
  141. }
  142. }
  143. }
  144. /// Verify ownership of the second factor phone number by the current user.
  145. /// - Parameter multiFactorInfo: The phone multi factor whose number need to be verified.
  146. /// - Parameter uiDelegate: An object used to present the SFSafariViewController. The object is
  147. /// retained by this method until the completion block is executed.
  148. /// - Parameter multiFactorSession: A session to identify the MFA flow. For enrollment, this
  149. /// identifies the user trying to enroll. For sign-in, this identifies that the user already
  150. /// passed the first factor challenge.
  151. /// - Returns: The verification ID.
  152. @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
  153. open func verifyPhoneNumber(with multiFactorInfo: PhoneMultiFactorInfo,
  154. uiDelegate: AuthUIDelegate? = nil,
  155. multiFactorSession: MultiFactorSession?) async throws -> String {
  156. multiFactorSession?.multiFactorInfo = multiFactorInfo
  157. return try await verifyPhoneNumber(multiFactorInfo.phoneNumber,
  158. uiDelegate: uiDelegate,
  159. multiFactorSession: multiFactorSession)
  160. }
  161. /// Creates an `AuthCredential` for the phone number provider identified by the
  162. /// verification ID and verification code.
  163. ///
  164. /// - Parameter verificationID: The verification ID obtained from invoking
  165. /// verifyPhoneNumber:completion:
  166. /// - Parameter verificationCode: The verification code obtained from the user.
  167. /// - Returns: The corresponding phone auth credential for the verification ID and verification
  168. /// code provided.
  169. @objc(credentialWithVerificationID:verificationCode:)
  170. open func credential(withVerificationID verificationID: String,
  171. verificationCode: String) -> PhoneAuthCredential {
  172. return PhoneAuthCredential(withProviderID: PhoneAuthProvider.id,
  173. verificationID: verificationID,
  174. verificationCode: verificationCode)
  175. }
  176. private func internalVerify(phoneNumber: String,
  177. uiDelegate: AuthUIDelegate?,
  178. multiFactorSession: MultiFactorSession? = nil) async throws
  179. -> String? {
  180. guard !phoneNumber.isEmpty else {
  181. throw AuthErrorUtils.missingPhoneNumberError(message: nil)
  182. }
  183. guard let manager = auth.notificationManager else {
  184. throw AuthErrorUtils.notificationNotForwardedError()
  185. }
  186. guard await manager.checkNotificationForwarding() else {
  187. throw AuthErrorUtils.notificationNotForwardedError()
  188. }
  189. let recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: auth)
  190. try await recaptchaVerifier.retrieveRecaptchaConfig(forceRefresh: false)
  191. switch recaptchaVerifier.enablementStatus(forProvider: .phone) {
  192. case .off:
  193. return try await verifyClAndSendVerificationCode(
  194. toPhoneNumber: phoneNumber,
  195. retryOnInvalidAppCredential: true,
  196. multiFactorSession: multiFactorSession,
  197. uiDelegate: uiDelegate
  198. )
  199. case .audit:
  200. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  201. toPhoneNumber: phoneNumber,
  202. retryOnInvalidAppCredential: true,
  203. multiFactorSession: multiFactorSession,
  204. uiDelegate: uiDelegate,
  205. recaptchaVerifier: recaptchaVerifier
  206. )
  207. case .enforce:
  208. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  209. toPhoneNumber: phoneNumber,
  210. retryOnInvalidAppCredential: false,
  211. multiFactorSession: multiFactorSession,
  212. uiDelegate: uiDelegate,
  213. recaptchaVerifier: recaptchaVerifier
  214. )
  215. }
  216. }
  217. func verifyClAndSendVerificationCodeWithRecaptcha(toPhoneNumber phoneNumber: String,
  218. retryOnInvalidAppCredential: Bool,
  219. uiDelegate: AuthUIDelegate?,
  220. recaptchaVerifier: AuthRecaptchaVerifier) async throws
  221. -> String? {
  222. let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
  223. codeIdentity: CodeIdentity.empty,
  224. requestConfiguration: auth
  225. .requestConfiguration)
  226. do {
  227. try await recaptchaVerifier.injectRecaptchaFields(
  228. request: request,
  229. provider: .phone,
  230. action: .sendVerificationCode
  231. )
  232. let response = try await AuthBackend.call(with: request)
  233. return response.verificationID
  234. } catch {
  235. return try await handleVerifyErrorWithRetry(error: error,
  236. phoneNumber: phoneNumber,
  237. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  238. multiFactorSession: nil,
  239. uiDelegate: uiDelegate)
  240. }
  241. }
  242. /// Starts the flow to verify the client via silent push notification.
  243. /// - Parameter retryOnInvalidAppCredential: Whether of not the flow should be retried if an
  244. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  245. /// - Parameter phoneNumber: The phone number to be verified.
  246. /// - Parameter callback: The callback to be invoked on the global work queue when the flow is
  247. /// finished.
  248. func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
  249. retryOnInvalidAppCredential: Bool,
  250. uiDelegate: AuthUIDelegate?) async throws
  251. -> String? {
  252. let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
  253. let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
  254. codeIdentity: codeIdentity,
  255. requestConfiguration: auth
  256. .requestConfiguration)
  257. do {
  258. let response = try await AuthBackend.call(with: request)
  259. return response.verificationID
  260. } catch {
  261. return try await handleVerifyErrorWithRetry(
  262. error: error,
  263. phoneNumber: phoneNumber,
  264. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  265. multiFactorSession: nil,
  266. uiDelegate: uiDelegate
  267. )
  268. }
  269. }
  270. /// Starts the flow to verify the client via silent push notification.
  271. /// - Parameter retryOnInvalidAppCredential: Whether of not the flow should be retried if an
  272. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  273. /// - Parameter phoneNumber: The phone number to be verified.
  274. private func verifyClAndSendVerificationCodeWithRecaptcha(toPhoneNumber phoneNumber: String,
  275. retryOnInvalidAppCredential: Bool,
  276. multiFactorSession session: MultiFactorSession?,
  277. uiDelegate: AuthUIDelegate?,
  278. recaptchaVerifier: AuthRecaptchaVerifier) async throws
  279. -> String? {
  280. if let settings = auth.settings,
  281. settings.isAppVerificationDisabledForTesting {
  282. let request = SendVerificationCodeRequest(
  283. phoneNumber: phoneNumber,
  284. codeIdentity: CodeIdentity.empty,
  285. requestConfiguration: auth.requestConfiguration
  286. )
  287. let response = try await AuthBackend.call(with: request)
  288. return response.verificationID
  289. }
  290. guard let session else {
  291. return try await verifyClAndSendVerificationCodeWithRecaptcha(
  292. toPhoneNumber: phoneNumber,
  293. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  294. uiDelegate: uiDelegate,
  295. recaptchaVerifier: recaptchaVerifier
  296. )
  297. }
  298. let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
  299. codeIdentity: CodeIdentity.empty)
  300. do {
  301. if let idToken = session.idToken {
  302. let request = StartMFAEnrollmentRequest(idToken: idToken,
  303. enrollmentInfo: startMFARequestInfo,
  304. requestConfiguration: auth.requestConfiguration)
  305. try await recaptchaVerifier.injectRecaptchaFields(
  306. request: request,
  307. provider: .phone,
  308. action: .startMfaEnrollment
  309. )
  310. let response = try await AuthBackend.call(with: request)
  311. return response.phoneSessionInfo?.sessionInfo
  312. } else {
  313. let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
  314. MFAEnrollmentID: session.multiFactorInfo?.uid,
  315. signInInfo: startMFARequestInfo,
  316. requestConfiguration: auth.requestConfiguration)
  317. try await recaptchaVerifier.injectRecaptchaFields(
  318. request: request,
  319. provider: .phone,
  320. action: .startMfaSignin
  321. )
  322. let response = try await AuthBackend.call(with: request)
  323. return response.responseInfo?.sessionInfo
  324. }
  325. } catch {
  326. return try await handleVerifyErrorWithRetry(
  327. error: error,
  328. phoneNumber: phoneNumber,
  329. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  330. multiFactorSession: session,
  331. uiDelegate: uiDelegate
  332. )
  333. }
  334. }
  335. /// Starts the flow to verify the client via silent push notification.
  336. /// - Parameter retryOnInvalidAppCredential: Whether of not the flow should be retried if an
  337. /// AuthErrorCodeInvalidAppCredential error is returned from the backend.
  338. /// - Parameter phoneNumber: The phone number to be verified.
  339. private func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
  340. retryOnInvalidAppCredential: Bool,
  341. multiFactorSession session: MultiFactorSession?,
  342. uiDelegate: AuthUIDelegate?) async throws
  343. -> String? {
  344. if let settings = auth.settings,
  345. settings.isAppVerificationDisabledForTesting {
  346. let request = SendVerificationCodeRequest(
  347. phoneNumber: phoneNumber,
  348. codeIdentity: CodeIdentity.empty,
  349. requestConfiguration: auth.requestConfiguration
  350. )
  351. let response = try await AuthBackend.call(with: request)
  352. return response.verificationID
  353. }
  354. guard let session else {
  355. return try await verifyClAndSendVerificationCode(
  356. toPhoneNumber: phoneNumber,
  357. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  358. uiDelegate: uiDelegate
  359. )
  360. }
  361. let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
  362. let startMFARequestInfo = AuthProtoStartMFAPhoneRequestInfo(phoneNumber: phoneNumber,
  363. codeIdentity: codeIdentity)
  364. do {
  365. if let idToken = session.idToken {
  366. let request = StartMFAEnrollmentRequest(idToken: idToken,
  367. enrollmentInfo: startMFARequestInfo,
  368. requestConfiguration: auth.requestConfiguration)
  369. let response = try await AuthBackend.call(with: request)
  370. return response.phoneSessionInfo?.sessionInfo
  371. } else {
  372. let request = StartMFASignInRequest(MFAPendingCredential: session.mfaPendingCredential,
  373. MFAEnrollmentID: session.multiFactorInfo?.uid,
  374. signInInfo: startMFARequestInfo,
  375. requestConfiguration: auth.requestConfiguration)
  376. let response = try await AuthBackend.call(with: request)
  377. return response.responseInfo?.sessionInfo
  378. }
  379. } catch {
  380. return try await handleVerifyErrorWithRetry(
  381. error: error,
  382. phoneNumber: phoneNumber,
  383. retryOnInvalidAppCredential: retryOnInvalidAppCredential,
  384. multiFactorSession: session,
  385. uiDelegate: uiDelegate
  386. )
  387. }
  388. }
  389. private func handleVerifyErrorWithRetry(error: Error,
  390. phoneNumber: String,
  391. retryOnInvalidAppCredential: Bool,
  392. multiFactorSession session: MultiFactorSession?,
  393. uiDelegate: AuthUIDelegate?) async throws -> String? {
  394. if (error as NSError).code == AuthErrorCode.invalidAppCredential.rawValue {
  395. if retryOnInvalidAppCredential {
  396. auth.appCredentialManager.clearCredential()
  397. return try await verifyClAndSendVerificationCode(toPhoneNumber: phoneNumber,
  398. retryOnInvalidAppCredential: false,
  399. multiFactorSession: session,
  400. uiDelegate: uiDelegate)
  401. }
  402. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: nil, underlyingError: error)
  403. }
  404. throw error
  405. }
  406. /// Continues the flow to verify the client via silent push notification.
  407. private func verifyClient(withUIDelegate uiDelegate: AuthUIDelegate?) async throws
  408. -> CodeIdentity {
  409. // Remove the simulator check below after FCM supports APNs in simulators
  410. #if targetEnvironment(simulator)
  411. let environment = ProcessInfo().environment
  412. if environment["XCTestConfigurationFilePath"] == nil {
  413. return try await CodeIdentity
  414. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  415. }
  416. #endif
  417. if let credential = auth.appCredentialManager.credential {
  418. return CodeIdentity.credential(credential)
  419. }
  420. var token: AuthAPNSToken
  421. do {
  422. token = try await auth.tokenManager.getToken()
  423. } catch {
  424. return try await CodeIdentity
  425. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  426. }
  427. let request = VerifyClientRequest(withAppToken: token.string,
  428. isSandbox: token.type == AuthAPNSTokenType.sandbox,
  429. requestConfiguration: auth.requestConfiguration)
  430. do {
  431. let verifyResponse = try await AuthBackend.call(with: request)
  432. guard let receipt = verifyResponse.receipt,
  433. let timeout = verifyResponse.suggestedTimeOutDate?.timeIntervalSinceNow else {
  434. fatalError("Internal Auth Error: invalid VerifyClientResponse")
  435. }
  436. let credential = await
  437. auth.appCredentialManager.didStartVerification(withReceipt: receipt, timeout: timeout)
  438. if credential.secret == nil {
  439. AuthLog.logWarning(code: "I-AUT000014", message: "Failed to receive remote " +
  440. "notification to verify app identity within \(timeout) " +
  441. "second(s), falling back to reCAPTCHA verification.")
  442. return try await CodeIdentity
  443. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  444. }
  445. return CodeIdentity.credential(credential)
  446. } catch {
  447. let nserror = error as NSError
  448. // reCAPTCHA Flow if it's an invalid app credential or a missing app token.
  449. if (nserror.code == AuthErrorCode.internalError.rawValue &&
  450. (nserror.userInfo[NSUnderlyingErrorKey] as? NSError)?.code ==
  451. AuthErrorCode.invalidAppCredential.rawValue) ||
  452. nserror.code == AuthErrorCode.missingAppToken.rawValue {
  453. return try await CodeIdentity
  454. .recaptcha(reCAPTCHAFlowWithUIDelegate(withUIDelegate: uiDelegate))
  455. } else {
  456. throw error
  457. }
  458. }
  459. }
  460. /// Continues the flow to verify the client via silent push notification.
  461. private func reCAPTCHAFlowWithUIDelegate(withUIDelegate uiDelegate: AuthUIDelegate?) async throws
  462. -> String {
  463. let eventID = AuthWebUtils.randomString(withLength: 10)
  464. guard let url = try await reCAPTCHAURL(withEventID: eventID) else {
  465. fatalError(
  466. "Internal error: reCAPTCHAURL returned neither a value nor an error. Report issue"
  467. )
  468. }
  469. let callbackMatcher: (URL?) -> Bool = { callbackURL in
  470. AuthWebUtils.isExpectedCallbackURL(
  471. callbackURL,
  472. eventID: eventID,
  473. authType: self.kAuthTypeVerifyApp,
  474. callbackScheme: self.callbackScheme
  475. )
  476. }
  477. return try await withCheckedThrowingContinuation { continuation in
  478. self.auth.authURLPresenter.present(url,
  479. uiDelegate: uiDelegate,
  480. callbackMatcher: callbackMatcher) { callbackURL, error in
  481. if let error {
  482. continuation.resume(throwing: error)
  483. } else {
  484. do {
  485. try continuation.resume(returning: self.reCAPTCHAToken(forURL: callbackURL))
  486. } catch {
  487. continuation.resume(throwing: error)
  488. }
  489. }
  490. }
  491. }
  492. }
  493. /// Parses the reCAPTCHA URL and returns the reCAPTCHA token.
  494. /// - Parameter url: The url to be parsed for a reCAPTCHA token.
  495. /// - Returns: The reCAPTCHA token if successful.
  496. private func reCAPTCHAToken(forURL url: URL?) throws -> String {
  497. guard let url = url else {
  498. let reason = "Internal Auth Error: nil URL trying to access RECAPTCHA token"
  499. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  500. }
  501. let actualURLComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  502. if let queryItems = actualURLComponents?.queryItems,
  503. let deepLinkURL = AuthWebUtils.queryItemValue(name: "deep_link_id", from: queryItems) {
  504. let deepLinkComponents = URLComponents(string: deepLinkURL)
  505. if let queryItems = deepLinkComponents?.queryItems {
  506. if let token = AuthWebUtils.queryItemValue(name: "recaptchaToken", from: queryItems) {
  507. return token
  508. }
  509. if let firebaseError = AuthWebUtils.queryItemValue(
  510. name: "firebaseError",
  511. from: queryItems
  512. ) {
  513. if let errorData = firebaseError.data(using: .utf8) {
  514. var errorDict: [AnyHashable: Any]?
  515. do {
  516. errorDict = try JSONSerialization.jsonObject(with: errorData) as? [AnyHashable: Any]
  517. } catch {
  518. throw AuthErrorUtils.JSONSerializationError(underlyingError: error)
  519. }
  520. if let errorDict,
  521. let code = errorDict["code"] as? String,
  522. let message = errorDict["message"] as? String {
  523. throw AuthErrorUtils.urlResponseError(code: code, message: message)
  524. }
  525. }
  526. }
  527. }
  528. let reason = "An unknown error occurred with the following response: \(deepLinkURL)"
  529. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  530. }
  531. let reason = "Failed to get url Components for url: \(url)"
  532. throw AuthErrorUtils.appVerificationUserInteractionFailure(reason: reason)
  533. }
  534. /// Constructs a URL used for opening a reCAPTCHA app verification flow using a given event ID.
  535. /// - Parameter eventID: The event ID used for this purpose.
  536. private func reCAPTCHAURL(withEventID eventID: String) async throws -> URL? {
  537. let authDomain = try await AuthWebUtils
  538. .fetchAuthDomain(withRequestConfiguration: auth.requestConfiguration)
  539. let bundleID = Bundle.main.bundleIdentifier
  540. let clientID = auth.app?.options.clientID
  541. let appID = auth.app?.options.googleAppID
  542. let apiKey = auth.requestConfiguration.apiKey
  543. let appCheck = auth.requestConfiguration.appCheck
  544. var queryItems = [URLQueryItem(name: "apiKey", value: apiKey),
  545. URLQueryItem(name: "authType", value: kAuthTypeVerifyApp),
  546. URLQueryItem(name: "ibi", value: bundleID ?? ""),
  547. URLQueryItem(name: "v", value: AuthBackend.authUserAgent()),
  548. URLQueryItem(name: "eventId", value: eventID)]
  549. if usingClientIDScheme {
  550. queryItems.append(URLQueryItem(name: "clientId", value: clientID))
  551. } else {
  552. queryItems.append(URLQueryItem(name: "appId", value: appID))
  553. }
  554. if let languageCode = auth.requestConfiguration.languageCode {
  555. queryItems.append(URLQueryItem(name: "hl", value: languageCode))
  556. }
  557. var components = URLComponents(string: "https://\(authDomain)/__/auth/handler?")
  558. components?.queryItems = queryItems
  559. if let appCheck {
  560. let tokenResult = await appCheck.getToken(forcingRefresh: false)
  561. if let error = tokenResult.error {
  562. AuthLog.logWarning(code: "I-AUT000018",
  563. message: "Error getting App Check token; using placeholder " +
  564. "token instead. Error: \(error)")
  565. }
  566. let appCheckTokenFragment = "fac=\(tokenResult.token)"
  567. components?.fragment = appCheckTokenFragment
  568. }
  569. return components?.url
  570. }
  571. private let auth: Auth
  572. private let callbackScheme: String
  573. private let usingClientIDScheme: Bool
  574. private var recaptchaVerifier: AuthRecaptchaVerifier?
  575. init(auth: Auth, recaptchaVerifier: AuthRecaptchaVerifier? = nil) {
  576. self.auth = auth
  577. if let clientID = auth.app?.options.clientID {
  578. let reverseClientIDScheme = clientID.components(separatedBy: ".").reversed()
  579. .joined(separator: ".")
  580. if AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: reverseClientIDScheme,
  581. urlTypes: auth.mainBundleUrlTypes) {
  582. callbackScheme = reverseClientIDScheme
  583. usingClientIDScheme = true
  584. return
  585. }
  586. }
  587. usingClientIDScheme = false
  588. if let appID = auth.app?.options.googleAppID {
  589. let dashedAppID = appID.replacingOccurrences(of: ":", with: "-")
  590. callbackScheme = "app-\(dashedAppID)"
  591. return
  592. }
  593. callbackScheme = ""
  594. self.recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: auth)
  595. }
  596. private let kAuthTypeVerifyApp = "verifyApp"
  597. #endif
  598. }