PhoneAuthProvider.swift 30 KB

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