PhoneAuthProvider.swift 28 KB

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