FIRAuthBackend.m 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  17. #if SWIFT_PACKAGE
  18. @import GTMSessionFetcherCore;
  19. #else
  20. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  21. #import <GTMSessionFetcher/GTMSessionFetcherService.h>
  22. #endif
  23. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FirebaseAuth.h"
  24. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  25. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  26. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIRequest.h"
  27. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIResponse.h"
  28. #import "FirebaseAuth/Sources/Backend/RPC/FIRDeleteAccountRequest.h"
  29. #import "FirebaseAuth/Sources/Backend/RPC/FIRDeleteAccountResponse.h"
  30. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
  31. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
  32. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoRequest.h"
  33. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoResponse.h"
  34. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
  35. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
  36. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetProjectConfigRequest.h"
  37. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetProjectConfigResponse.h"
  38. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordRequest.h"
  39. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordResponse.h"
  40. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenRequest.h"
  41. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenResponse.h"
  42. #import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeRequest.h"
  43. #import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeResponse.h"
  44. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
  45. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
  46. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterRequest.h"
  47. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterResponse.h"
  48. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
  49. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
  50. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
  51. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
  52. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyClientRequest.h"
  53. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyClientResponse.h"
  54. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
  55. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
  56. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
  57. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
  58. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
  59. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
  60. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  61. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  62. #if TARGET_OS_IOS
  63. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
  64. #import "FirebaseAuth/Sources/AuthProvider/Phone/FIRPhoneAuthCredential_Internal.h"
  65. #import "FirebaseAuth/Sources/MultiFactor/Phone/FIRPhoneMultiFactorInfo+Internal.h"
  66. #endif
  67. NS_ASSUME_NONNULL_BEGIN
  68. /** @var kClientVersionHeader
  69. @brief HTTP header name for the client version.
  70. */
  71. static NSString *const kClientVersionHeader = @"X-Client-Version";
  72. /** @var kIosBundleIdentifierHeader
  73. @brief HTTP header name for iOS bundle ID.
  74. */
  75. static NSString *const kIosBundleIdentifierHeader = @"X-Ios-Bundle-Identifier";
  76. /** @var kFirebaseLocalHeader
  77. @brief HTTP header name for the firebase locale.
  78. */
  79. static NSString *const kFirebaseLocalHeader = @"X-Firebase-Locale";
  80. /** @var kFirebaseAuthCoreFrameworkMarker
  81. @brief The marker in the HTTP header that indicates the request comes from Firebase Auth Core.
  82. */
  83. static NSString *const kFirebaseAuthCoreFrameworkMarker = @"FirebaseCore-iOS";
  84. /** @var kJSONContentType
  85. @brief The value of the HTTP content-type header for JSON payloads.
  86. */
  87. static NSString *const kJSONContentType = @"application/json";
  88. /** @var kErrorDataKey
  89. @brief Key for error data in NSError returned by @c GTMSessionFetcher.
  90. */
  91. static NSString *const kErrorDataKey = @"data";
  92. /** @var kErrorKey
  93. @brief The key for the "error" value in JSON responses from the server.
  94. */
  95. static NSString *const kErrorKey = @"error";
  96. /** @var kErrorsKey
  97. @brief The key for the "errors" value in JSON responses from the server.
  98. */
  99. static NSString *const kErrorsKey = @"errors";
  100. /** @var kReasonKey
  101. @brief The key for the "reason" value in JSON responses from the server.
  102. */
  103. static NSString *const kReasonKey = @"reason";
  104. /** @var kInvalidKeyReasonValue
  105. @brief The value for the "reason" key indicating an invalid API Key was received by the server.
  106. */
  107. static NSString *const kInvalidKeyReasonValue = @"keyInvalid";
  108. /** @var kAppNotAuthorizedReasonValue
  109. @brief The value for the "reason" key indicating the App is not authorized to use Firebase
  110. Authentication.
  111. */
  112. static NSString *const kAppNotAuthorizedReasonValue = @"ipRefererBlocked";
  113. /** @var kErrorMessageKey
  114. @brief The key for an error's "message" value in JSON responses from the server.
  115. */
  116. static NSString *const kErrorMessageKey = @"message";
  117. /** @var kReturnIDPCredentialErrorMessageKey
  118. @brief The key for "errorMessage" value in JSON responses from the server, In case
  119. returnIDPCredential of a verifyAssertion request is set to @YES.
  120. */
  121. static NSString *const kReturnIDPCredentialErrorMessageKey = @"errorMessage";
  122. /** @var kUserNotFoundErrorMessage
  123. @brief This is the error message returned when the user is not found, which means the user
  124. account has been deleted given the token was once valid.
  125. */
  126. static NSString *const kUserNotFoundErrorMessage = @"USER_NOT_FOUND";
  127. /** @var kUserDeletedErrorMessage
  128. @brief This is the error message the server will respond with if the user entered an invalid
  129. email address.
  130. */
  131. static NSString *const kUserDeletedErrorMessage = @"EMAIL_NOT_FOUND";
  132. /** @var kInvalidLocalIDErrorMessage
  133. @brief This is the error message the server responds with if the user local id in the id token
  134. does not exit.
  135. */
  136. static NSString *const kInvalidLocalIDErrorMessage = @"INVALID_LOCAL_ID";
  137. /** @var kUserTokenExpiredErrorMessage
  138. @brief The error returned by the server if the token issue time is older than the account's
  139. valid_since time.
  140. */
  141. static NSString *const kUserTokenExpiredErrorMessage = @"TOKEN_EXPIRED";
  142. /** @var kTooManyRequestsErrorMessage
  143. @brief This is the error message the server will respond with if too many requests were made to
  144. a server method.
  145. */
  146. static NSString *const kTooManyRequestsErrorMessage = @"TOO_MANY_ATTEMPTS_TRY_LATER";
  147. /** @var kInvalidCustomTokenErrorMessage
  148. @brief This is the error message the server will respond with if there is a validation error
  149. with the custom token.
  150. */
  151. static NSString *const kInvalidCustomTokenErrorMessage = @"INVALID_CUSTOM_TOKEN";
  152. /** @var kCustomTokenMismatch
  153. @brief This is the error message the server will respond with if the service account and API key
  154. belong to different projects.
  155. */
  156. static NSString *const kCustomTokenMismatch = @"CREDENTIAL_MISMATCH";
  157. /** @var kInvalidCredentialErrorMessage
  158. @brief This is the error message the server responds with if the IDP token or requestUri is
  159. invalid.
  160. */
  161. static NSString *const kInvalidCredentialErrorMessage = @"INVALID_IDP_RESPONSE";
  162. /** @var kUserDisabledErrorMessage
  163. @brief The error returned by the server if the user account is diabled.
  164. */
  165. static NSString *const kUserDisabledErrorMessage = @"USER_DISABLED";
  166. /** @var kOperationNotAllowedErrorMessage
  167. @brief This is the error message the server will respond with if Admin disables IDP specified by
  168. provider.
  169. */
  170. static NSString *const kOperationNotAllowedErrorMessage = @"OPERATION_NOT_ALLOWED";
  171. /** @var kPasswordLoginDisabledErrorMessage
  172. @brief This is the error message the server responds with if password login is disabled.
  173. */
  174. static NSString *const kPasswordLoginDisabledErrorMessage = @"PASSWORD_LOGIN_DISABLED";
  175. /** @var kEmailAlreadyInUseErrorMessage
  176. @brief This is the error message the server responds with if the email address already exists.
  177. */
  178. static NSString *const kEmailAlreadyInUseErrorMessage = @"EMAIL_EXISTS";
  179. /** @var kInvalidEmailErrorMessage
  180. @brief The error returned by the server if the email is invalid.
  181. */
  182. static NSString *const kInvalidEmailErrorMessage = @"INVALID_EMAIL";
  183. /** @var kInvalidIdentifierErrorMessage
  184. @brief The error returned by the server if the identifier is invalid.
  185. */
  186. static NSString *const kInvalidIdentifierErrorMessage = @"INVALID_IDENTIFIER";
  187. /** @var kWrongPasswordErrorMessage
  188. @brief This is the error message the server will respond with if the user entered a wrong
  189. password.
  190. */
  191. static NSString *const kWrongPasswordErrorMessage = @"INVALID_PASSWORD";
  192. /** @var kCredentialTooOldErrorMessage
  193. @brief This is the error message the server responds with if account change is attempted 5
  194. minutes after signing in.
  195. */
  196. static NSString *const kCredentialTooOldErrorMessage = @"CREDENTIAL_TOO_OLD_LOGIN_AGAIN";
  197. /** @var kFederatedUserIDAlreadyLinkedMessage
  198. @brief This is the error message the server will respond with if the federated user ID has been
  199. already linked with another account.
  200. */
  201. static NSString *const kFederatedUserIDAlreadyLinkedMessage = @"FEDERATED_USER_ID_ALREADY_LINKED";
  202. /** @var kInvalidUserTokenErrorMessage
  203. @brief This is the error message the server responds with if user's saved auth credential is
  204. invalid, and the user needs to sign in again.
  205. */
  206. static NSString *const kInvalidUserTokenErrorMessage = @"INVALID_ID_TOKEN";
  207. /** @var kWeakPasswordErrorMessagePrefix
  208. @brief This is the prefix for the error message the server responds with if user's new password
  209. to be set is too weak.
  210. */
  211. static NSString *const kWeakPasswordErrorMessagePrefix = @"WEAK_PASSWORD";
  212. /** @var kExpiredActionCodeErrorMessage
  213. @brief This is the error message the server will respond with if the action code is expired.
  214. */
  215. static NSString *const kExpiredActionCodeErrorMessage = @"EXPIRED_OOB_CODE";
  216. /** @var kInvalidActionCodeErrorMessage
  217. @brief This is the error message the server will respond with if the action code is invalid.
  218. */
  219. static NSString *const kInvalidActionCodeErrorMessage = @"INVALID_OOB_CODE";
  220. /** @var kMissingEmailErrorMessage
  221. @brief This is the error message the server will respond with if the email address is missing
  222. during a "send password reset email" attempt.
  223. */
  224. static NSString *const kMissingEmailErrorMessage = @"MISSING_EMAIL";
  225. /** @var kInvalidSenderEmailErrorMessage
  226. @brief This is the error message the server will respond with if the sender email is invalid
  227. during a "send password reset email" attempt.
  228. */
  229. static NSString *const kInvalidSenderEmailErrorMessage = @"INVALID_SENDER";
  230. /** @var kInvalidMessagePayloadErrorMessage
  231. @brief This is the error message the server will respond with if there are invalid parameters in
  232. the payload during a "send password reset email" attempt.
  233. */
  234. static NSString *const kInvalidMessagePayloadErrorMessage = @"INVALID_MESSAGE_PAYLOAD";
  235. /** @var kInvalidRecipientEmailErrorMessage
  236. @brief This is the error message the server will respond with if the recipient email is invalid.
  237. */
  238. static NSString *const kInvalidRecipientEmailErrorMessage = @"INVALID_RECIPIENT_EMAIL";
  239. /** @var kMissingIosBundleIDErrorMessage
  240. @brief This is the error message the server will respond with if iOS bundle ID is missing but
  241. the iOS App store ID is provided.
  242. */
  243. static NSString *const kMissingIosBundleIDErrorMessage = @"MISSING_IOS_BUNDLE_ID";
  244. /** @var kMissingAndroidPackageNameErrorMessage
  245. @brief This is the error message the server will respond with if Android Package Name is missing
  246. but the flag indicating the app should be installed is set to true.
  247. */
  248. static NSString *const kMissingAndroidPackageNameErrorMessage = @"MISSING_ANDROID_PACKAGE_NAME";
  249. /** @var kUnauthorizedDomainErrorMessage
  250. @brief This is the error message the server will respond with if the domain of the continue URL
  251. specified is not allowlisted in the Firebase console.
  252. */
  253. static NSString *const kUnauthorizedDomainErrorMessage = @"UNAUTHORIZED_DOMAIN";
  254. /** @var kInvalidProviderIDErrorMessage
  255. @brief This is the error message the server will respond with if the provider id given for the
  256. web operation is invalid.
  257. */
  258. static NSString *const kInvalidProviderIDErrorMessage = @"INVALID_PROVIDER_ID";
  259. /** @var kInvalidDynamicLinkDomainErrorMessage
  260. @brief This is the error message the server will respond with if the dynamic link domain
  261. provided in the request is invalid.
  262. */
  263. static NSString *const kInvalidDynamicLinkDomainErrorMessage = @"INVALID_DYNAMIC_LINK_DOMAIN";
  264. /** @var kInvalidContinueURIErrorMessage
  265. @brief This is the error message the server will respond with if the continue URL provided in
  266. the request is invalid.
  267. */
  268. static NSString *const kInvalidContinueURIErrorMessage = @"INVALID_CONTINUE_URI";
  269. /** @var kMissingContinueURIErrorMessage
  270. @brief This is the error message the server will respond with if there was no continue URI
  271. present in a request that required one.
  272. */
  273. static NSString *const kMissingContinueURIErrorMessage = @"MISSING_CONTINUE_URI";
  274. /** @var kInvalidPhoneNumberErrorMessage
  275. @brief This is the error message the server will respond with if an incorrectly formatted phone
  276. number is provided.
  277. */
  278. static NSString *const kInvalidPhoneNumberErrorMessage = @"INVALID_PHONE_NUMBER";
  279. /** @var kInvalidVerificationCodeErrorMessage
  280. @brief This is the error message the server will respond with if an invalid verification code is
  281. provided.
  282. */
  283. static NSString *const kInvalidVerificationCodeErrorMessage = @"INVALID_CODE";
  284. /** @var kInvalidSessionInfoErrorMessage
  285. @brief This is the error message the server will respond with if an invalid session info
  286. (verification ID) is provided.
  287. */
  288. static NSString *const kInvalidSessionInfoErrorMessage = @"INVALID_SESSION_INFO";
  289. /** @var kSessionExpiredErrorMessage
  290. @brief This is the error message the server will respond with if the SMS code has expired before
  291. it is used.
  292. */
  293. static NSString *const kSessionExpiredErrorMessage = @"SESSION_EXPIRED";
  294. /** @var kMissingOrInvalidNonceErrorMessage
  295. @brief This is the error message the server will respond with if the nonce is missing or
  296. invalid.
  297. */
  298. static NSString *const kMissingOrInvalidNonceErrorMessage = @"MISSING_OR_INVALID_NONCE";
  299. /** @var kMissingAppTokenErrorMessage
  300. @brief This is the error message the server will respond with if the APNS token is missing in a
  301. verifyClient request.
  302. */
  303. static NSString *const kMissingAppTokenErrorMessage = @"MISSING_IOS_APP_TOKEN";
  304. /** @var kMissingAppCredentialErrorMessage
  305. @brief This is the error message the server will respond with if the app token is missing in a
  306. sendVerificationCode request.
  307. */
  308. static NSString *const kMissingAppCredentialErrorMessage = @"MISSING_APP_CREDENTIAL";
  309. /** @var kInvalidAppCredentialErrorMessage
  310. @brief This is the error message the server will respond with if the app credential in a
  311. sendVerificationCode request is invalid.
  312. */
  313. static NSString *const kInvalidAppCredentialErrorMessage = @"INVALID_APP_CREDENTIAL";
  314. /** @var kQuoutaExceededErrorMessage
  315. @brief This is the error message the server will respond with if the quota for SMS text messages
  316. has been exceeded for the project.
  317. */
  318. static NSString *const kQuoutaExceededErrorMessage = @"QUOTA_EXCEEDED";
  319. /** @var kAppNotVerifiedErrorMessage
  320. @brief This is the error message the server will respond with if Firebase could not verify the
  321. app during a phone authentication flow.
  322. */
  323. static NSString *const kAppNotVerifiedErrorMessage = @"APP_NOT_VERIFIED";
  324. /** @var kMissingClientIdentifier
  325. @brief This is the error message the server will respond with if Firebase could not verify the
  326. app during a phone authentication flow when a real phone number is used and app verification
  327. is disabled for testing.
  328. */
  329. static NSString *const kMissingClientIdentifier = @"MISSING_CLIENT_IDENTIFIER";
  330. /** @var kCaptchaCheckFailedErrorMessage
  331. @brief This is the error message the server will respond with if the reCAPTCHA token provided is
  332. invalid.
  333. */
  334. static NSString *const kCaptchaCheckFailedErrorMessage = @"CAPTCHA_CHECK_FAILED";
  335. /** @var kTenantIDMismatch
  336. @brief This is the error message the server will respond with if the tenant id mismatches.
  337. */
  338. static NSString *const kTenantIDMismatch = @"TENANT_ID_MISMATCH";
  339. /** @var kUnsupportedTenantOperation
  340. @brief This is the error message the server will respond with if the operation does not support
  341. multi-tenant.
  342. */
  343. static NSString *const kUnsupportedTenantOperation = @"UNSUPPORTED_TENANT_OPERATION";
  344. /** @var kMissingMFAPendingCredentialErrorMessage
  345. @brief This is the error message the server will respond with if the MFA pending credential is
  346. missing.
  347. */
  348. static NSString *const kMissingMFAPendingCredentialErrorMessage = @"MISSING_MFA_PENDING_CREDENTIAL";
  349. /** @var kMissingMFAEnrollmentIDErrorMessage
  350. @brief This is the error message the server will respond with if the MFA enrollment ID is missing.
  351. */
  352. static NSString *const kMissingMFAEnrollmentIDErrorMessage = @"MISSING_MFA_ENROLLMENT_ID";
  353. /** @var kInvalidMFAPendingCredentialErrorMessage
  354. @brief This is the error message the server will respond with if the MFA pending credential is
  355. invalid.
  356. */
  357. static NSString *const kInvalidMFAPendingCredentialErrorMessage = @"INVALID_MFA_PENDING_CREDENTIAL";
  358. /** @var kMFAEnrollmentNotFoundErrorMessage
  359. @brief This is the error message the server will respond with if the MFA enrollment info is not
  360. found.
  361. */
  362. static NSString *const kMFAEnrollmentNotFoundErrorMessage = @"MFA_ENROLLMENT_NOT_FOUND";
  363. /** @var kAdminOnlyOperationErrorMessage
  364. @brief This is the error message the server will respond with if the operation is admin only.
  365. */
  366. static NSString *const kAdminOnlyOperationErrorMessage = @"ADMIN_ONLY_OPERATION";
  367. /** @var kUnverifiedEmailErrorMessage
  368. @brief This is the error message the server will respond with if the email is unverified.
  369. */
  370. static NSString *const kUnverifiedEmailErrorMessage = @"UNVERIFIED_EMAIL";
  371. /** @var kSecondFactorExistsErrorMessage
  372. @brief This is the error message the server will respond with if the second factor already exsists.
  373. */
  374. static NSString *const kSecondFactorExistsErrorMessage = @"SECOND_FACTOR_EXISTS";
  375. /** @var kSecondFactorLimitExceededErrorMessage
  376. @brief This is the error message the server will respond with if the number of second factor
  377. reaches the limit.
  378. */
  379. static NSString *const kSecondFactorLimitExceededErrorMessage = @"SECOND_FACTOR_LIMIT_EXCEEDED";
  380. /** @var kUnsupportedFirstFactorErrorMessage
  381. @brief This is the error message the server will respond with if the first factor doesn't support
  382. MFA.
  383. */
  384. static NSString *const kUnsupportedFirstFactorErrorMessage = @"UNSUPPORTED_FIRST_FACTOR";
  385. /** @var kEmailChangeNeedsVerificationErrorMessage
  386. @brief This is the error message the server will respond with if changing an unverified email.
  387. */
  388. static NSString *const kEmailChangeNeedsVerificationErrorMessage =
  389. @"EMAIL_CHANGE_NEEDS_VERIFICATION";
  390. /** @var kInvalidPendingToken
  391. @brief Generic IDP error codes.
  392. */
  393. static NSString *const kInvalidPendingToken = @"INVALID_PENDING_TOKEN";
  394. /** @var gBackendImplementation
  395. @brief The singleton FIRAuthBackendImplementation instance to use.
  396. */
  397. static id<FIRAuthBackendImplementation> gBackendImplementation;
  398. /** @class FIRAuthBackendRPCImplementation
  399. @brief The default RPC-based backend implementation.
  400. */
  401. @interface FIRAuthBackendRPCImplementation : NSObject <FIRAuthBackendImplementation>
  402. /** @property RPCIssuer
  403. @brief An instance of FIRAuthBackendRPCIssuer for making RPC requests. Allows the RPC
  404. requests/responses to be easily faked.
  405. */
  406. @property(nonatomic, strong) id<FIRAuthBackendRPCIssuer> RPCIssuer;
  407. @end
  408. @implementation FIRAuthBackend
  409. + (id<FIRAuthBackendImplementation>)implementation {
  410. if (!gBackendImplementation) {
  411. gBackendImplementation = [[FIRAuthBackendRPCImplementation alloc] init];
  412. }
  413. return gBackendImplementation;
  414. }
  415. + (void)setBackendImplementation:(id<FIRAuthBackendImplementation>)backendImplementation {
  416. gBackendImplementation = backendImplementation;
  417. }
  418. + (void)setDefaultBackendImplementationWithRPCIssuer:
  419. (nullable id<FIRAuthBackendRPCIssuer>)RPCIssuer {
  420. FIRAuthBackendRPCImplementation *defaultImplementation =
  421. [[FIRAuthBackendRPCImplementation alloc] init];
  422. if (RPCIssuer) {
  423. defaultImplementation.RPCIssuer = RPCIssuer;
  424. }
  425. gBackendImplementation = defaultImplementation;
  426. }
  427. + (void)createAuthURI:(FIRCreateAuthURIRequest *)request
  428. callback:(FIRCreateAuthURIResponseCallback)callback {
  429. [[self implementation] createAuthURI:request callback:callback];
  430. }
  431. + (void)getAccountInfo:(FIRGetAccountInfoRequest *)request
  432. callback:(FIRGetAccountInfoResponseCallback)callback {
  433. [[self implementation] getAccountInfo:request callback:callback];
  434. }
  435. + (void)getProjectConfig:(FIRGetProjectConfigRequest *)request
  436. callback:(FIRGetProjectConfigResponseCallback)callback {
  437. [[self implementation] getProjectConfig:request callback:callback];
  438. }
  439. + (void)setAccountInfo:(FIRSetAccountInfoRequest *)request
  440. callback:(FIRSetAccountInfoResponseCallback)callback {
  441. [[self implementation] setAccountInfo:request callback:callback];
  442. }
  443. + (void)verifyAssertion:(FIRVerifyAssertionRequest *)request
  444. callback:(FIRVerifyAssertionResponseCallback)callback {
  445. [[self implementation] verifyAssertion:request callback:callback];
  446. }
  447. + (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request
  448. callback:(FIRVerifyCustomTokenResponseCallback)callback {
  449. [[self implementation] verifyCustomToken:request callback:callback];
  450. }
  451. + (void)verifyPassword:(FIRVerifyPasswordRequest *)request
  452. callback:(FIRVerifyPasswordResponseCallback)callback {
  453. [[self implementation] verifyPassword:request callback:callback];
  454. }
  455. + (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request
  456. callback:(FIREmailLinkSigninResponseCallback)callback {
  457. [[self implementation] emailLinkSignin:request callback:callback];
  458. }
  459. + (void)secureToken:(FIRSecureTokenRequest *)request
  460. callback:(FIRSecureTokenResponseCallback)callback {
  461. [[self implementation] secureToken:request callback:callback];
  462. }
  463. + (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request
  464. callback:(FIRGetOOBConfirmationCodeResponseCallback)callback {
  465. [[self implementation] getOOBConfirmationCode:request callback:callback];
  466. }
  467. + (void)signUpNewUser:(FIRSignUpNewUserRequest *)request
  468. callback:(FIRSignupNewUserCallback)callback {
  469. [[self implementation] signUpNewUser:request callback:callback];
  470. }
  471. + (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback {
  472. [[self implementation] deleteAccount:request callback:callback];
  473. }
  474. + (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request
  475. callback:(FIRSignInWithGameCenterResponseCallback)callback {
  476. [[self implementation] signInWithGameCenter:request callback:callback];
  477. }
  478. #if TARGET_OS_IOS
  479. + (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request
  480. callback:(FIRSendVerificationCodeResponseCallback)callback {
  481. [[self implementation] sendVerificationCode:request callback:callback];
  482. }
  483. + (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request
  484. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  485. [[self implementation] verifyPhoneNumber:request callback:callback];
  486. }
  487. + (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback {
  488. [[self implementation] verifyClient:request callback:callback];
  489. }
  490. #endif
  491. + (void)resetPassword:(FIRResetPasswordRequest *)request
  492. callback:(FIRResetPasswordCallback)callback {
  493. [[self implementation] resetPassword:request callback:callback];
  494. }
  495. + (NSString *)authUserAgent {
  496. return [NSString stringWithFormat:@"FirebaseAuth.iOS/%@ %@", FIRFirebaseVersion(),
  497. GTMFetcherStandardUserAgentString(nil)];
  498. }
  499. @end
  500. @interface FIRAuthBackendRPCIssuerImplementation : NSObject <FIRAuthBackendRPCIssuer>
  501. @end
  502. @implementation FIRAuthBackendRPCIssuerImplementation {
  503. /** @var The session fetcher service.
  504. */
  505. GTMSessionFetcherService *_fetcherService;
  506. }
  507. - (instancetype)init {
  508. self = [super init];
  509. if (self) {
  510. _fetcherService = [[GTMSessionFetcherService alloc] init];
  511. _fetcherService.userAgent = [FIRAuthBackend authUserAgent];
  512. _fetcherService.callbackQueue = FIRAuthGlobalWorkQueue();
  513. // Avoid reusing the session to prevent
  514. // https://github.com/firebase/firebase-ios-sdk/issues/1261
  515. _fetcherService.reuseSession = NO;
  516. }
  517. return self;
  518. }
  519. - (void)asyncPostToURLWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  520. URL:(NSURL *)URL
  521. body:(nullable NSData *)body
  522. contentType:(NSString *)contentType
  523. completionHandler:
  524. (void (^)(NSData *_Nullable, NSError *_Nullable))handler {
  525. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  526. [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
  527. NSString *additionalFrameworkMarker =
  528. requestConfiguration.additionalFrameworkMarker ?: kFirebaseAuthCoreFrameworkMarker;
  529. NSString *clientVersion = [NSString
  530. stringWithFormat:@"iOS/FirebaseSDK/%@/%@", FIRFirebaseVersion(), additionalFrameworkMarker];
  531. [request setValue:clientVersion forHTTPHeaderField:kClientVersionHeader];
  532. NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
  533. [request setValue:bundleID forHTTPHeaderField:kIosBundleIdentifierHeader];
  534. NSArray<NSString *> *preferredLocalizations = [NSBundle mainBundle].preferredLocalizations;
  535. if (preferredLocalizations.count) {
  536. NSString *acceptLanguage = preferredLocalizations.firstObject;
  537. [request setValue:acceptLanguage forHTTPHeaderField:@"Accept-Language"];
  538. }
  539. NSString *languageCode = requestConfiguration.languageCode;
  540. if (languageCode.length) {
  541. [request setValue:languageCode forHTTPHeaderField:kFirebaseLocalHeader];
  542. }
  543. GTMSessionFetcher *fetcher = [_fetcherService fetcherWithRequest:request];
  544. NSString *emulatorHostAndPort = requestConfiguration.emulatorHostAndPort;
  545. if (emulatorHostAndPort) {
  546. fetcher.allowLocalhostRequest = YES;
  547. fetcher.allowedInsecureSchemes = @[ @"http" ];
  548. }
  549. fetcher.bodyData = body;
  550. [fetcher beginFetchWithCompletionHandler:handler];
  551. }
  552. @end
  553. @implementation FIRAuthBackendRPCImplementation
  554. - (instancetype)init {
  555. self = [super init];
  556. if (self) {
  557. _RPCIssuer = [[FIRAuthBackendRPCIssuerImplementation alloc] init];
  558. }
  559. return self;
  560. }
  561. - (void)createAuthURI:(FIRCreateAuthURIRequest *)request
  562. callback:(FIRCreateAuthURIResponseCallback)callback {
  563. FIRCreateAuthURIResponse *response = [[FIRCreateAuthURIResponse alloc] init];
  564. [self postWithRequest:request
  565. response:response
  566. callback:^(NSError *error) {
  567. if (error) {
  568. callback(nil, error);
  569. } else {
  570. callback(response, nil);
  571. }
  572. }];
  573. }
  574. - (void)getAccountInfo:(FIRGetAccountInfoRequest *)request
  575. callback:(FIRGetAccountInfoResponseCallback)callback {
  576. FIRGetAccountInfoResponse *response = [[FIRGetAccountInfoResponse alloc] init];
  577. [self postWithRequest:request
  578. response:response
  579. callback:^(NSError *error) {
  580. if (error) {
  581. callback(nil, error);
  582. } else {
  583. callback(response, nil);
  584. }
  585. }];
  586. }
  587. - (void)getProjectConfig:(FIRGetProjectConfigRequest *)request
  588. callback:(FIRGetProjectConfigResponseCallback)callback {
  589. FIRGetProjectConfigResponse *response = [[FIRGetProjectConfigResponse alloc] init];
  590. [self postWithRequest:request
  591. response:response
  592. callback:^(NSError *error) {
  593. if (error) {
  594. callback(nil, error);
  595. } else {
  596. callback(response, nil);
  597. }
  598. }];
  599. }
  600. - (void)setAccountInfo:(FIRSetAccountInfoRequest *)request
  601. callback:(FIRSetAccountInfoResponseCallback)callback {
  602. FIRSetAccountInfoResponse *response = [[FIRSetAccountInfoResponse alloc] init];
  603. [self postWithRequest:request
  604. response:response
  605. callback:^(NSError *error) {
  606. if (error) {
  607. callback(nil, error);
  608. } else {
  609. callback(response, nil);
  610. }
  611. }];
  612. }
  613. - (void)verifyAssertion:(FIRVerifyAssertionRequest *)request
  614. callback:(FIRVerifyAssertionResponseCallback)callback {
  615. FIRVerifyAssertionResponse *response = [[FIRVerifyAssertionResponse alloc] init];
  616. [self
  617. postWithRequest:request
  618. response:response
  619. callback:^(NSError *error) {
  620. if (error) {
  621. callback(nil, error);
  622. } else {
  623. if (!response.IDToken && response.MFAInfo) {
  624. #if TARGET_OS_IOS
  625. NSMutableArray<FIRMultiFactorInfo *> *multiFactorInfo = [NSMutableArray array];
  626. for (FIRAuthProtoMFAEnrollment *MFAEnrollment in response.MFAInfo) {
  627. FIRPhoneMultiFactorInfo *info =
  628. [[FIRPhoneMultiFactorInfo alloc] initWithProto:MFAEnrollment];
  629. [multiFactorInfo addObject:info];
  630. }
  631. NSError *multiFactorRequiredError = [FIRAuthErrorUtils
  632. secondFactorRequiredErrorWithPendingCredential:response.MFAPendingCredential
  633. hints:multiFactorInfo];
  634. callback(nil, multiFactorRequiredError);
  635. #endif
  636. } else {
  637. callback(response, nil);
  638. }
  639. }
  640. }];
  641. }
  642. - (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request
  643. callback:(FIRVerifyCustomTokenResponseCallback)callback {
  644. FIRVerifyCustomTokenResponse *response = [[FIRVerifyCustomTokenResponse alloc] init];
  645. [self postWithRequest:request
  646. response:response
  647. callback:^(NSError *error) {
  648. if (error) {
  649. callback(nil, error);
  650. } else {
  651. callback(response, nil);
  652. }
  653. }];
  654. }
  655. - (void)verifyPassword:(FIRVerifyPasswordRequest *)request
  656. callback:(FIRVerifyPasswordResponseCallback)callback {
  657. FIRVerifyPasswordResponse *response = [[FIRVerifyPasswordResponse alloc] init];
  658. [self
  659. postWithRequest:request
  660. response:response
  661. callback:^(NSError *error) {
  662. if (error) {
  663. callback(nil, error);
  664. } else {
  665. if (!response.IDToken && response.MFAInfo) {
  666. #if TARGET_OS_IOS
  667. NSMutableArray<FIRMultiFactorInfo *> *multiFactorInfo = [NSMutableArray array];
  668. for (FIRAuthProtoMFAEnrollment *MFAEnrollment in response.MFAInfo) {
  669. FIRPhoneMultiFactorInfo *info =
  670. [[FIRPhoneMultiFactorInfo alloc] initWithProto:MFAEnrollment];
  671. [multiFactorInfo addObject:info];
  672. }
  673. NSError *multiFactorRequiredError = [FIRAuthErrorUtils
  674. secondFactorRequiredErrorWithPendingCredential:response.MFAPendingCredential
  675. hints:multiFactorInfo];
  676. callback(nil, multiFactorRequiredError);
  677. #endif
  678. } else {
  679. callback(response, nil);
  680. }
  681. }
  682. }];
  683. }
  684. - (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request
  685. callback:(FIREmailLinkSigninResponseCallback)callback {
  686. FIREmailLinkSignInResponse *response = [[FIREmailLinkSignInResponse alloc] init];
  687. [self
  688. postWithRequest:request
  689. response:response
  690. callback:^(NSError *error) {
  691. if (error) {
  692. callback(nil, error);
  693. } else {
  694. if (!response.IDToken && response.MFAInfo) {
  695. #if TARGET_OS_IOS
  696. NSMutableArray<FIRMultiFactorInfo *> *multiFactorInfo = [NSMutableArray array];
  697. for (FIRAuthProtoMFAEnrollment *MFAEnrollment in response.MFAInfo) {
  698. FIRPhoneMultiFactorInfo *info =
  699. [[FIRPhoneMultiFactorInfo alloc] initWithProto:MFAEnrollment];
  700. [multiFactorInfo addObject:info];
  701. }
  702. NSError *multiFactorRequiredError = [FIRAuthErrorUtils
  703. secondFactorRequiredErrorWithPendingCredential:response.MFAPendingCredential
  704. hints:multiFactorInfo];
  705. callback(nil, multiFactorRequiredError);
  706. #endif
  707. } else {
  708. callback(response, nil);
  709. }
  710. }
  711. }];
  712. }
  713. - (void)secureToken:(FIRSecureTokenRequest *)request
  714. callback:(FIRSecureTokenResponseCallback)callback {
  715. FIRSecureTokenResponse *response = [[FIRSecureTokenResponse alloc] init];
  716. [self postWithRequest:request
  717. response:response
  718. callback:^(NSError *error) {
  719. if (error) {
  720. callback(nil, error);
  721. } else {
  722. callback(response, nil);
  723. }
  724. }];
  725. }
  726. - (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request
  727. callback:(FIRGetOOBConfirmationCodeResponseCallback)callback {
  728. FIRGetOOBConfirmationCodeResponse *response = [[FIRGetOOBConfirmationCodeResponse alloc] init];
  729. [self postWithRequest:request
  730. response:response
  731. callback:^(NSError *error) {
  732. if (error) {
  733. callback(nil, error);
  734. } else {
  735. callback(response, nil);
  736. }
  737. }];
  738. }
  739. - (void)signUpNewUser:(FIRSignUpNewUserRequest *)request
  740. callback:(FIRSignupNewUserCallback)callback {
  741. FIRSignUpNewUserResponse *response = [[FIRSignUpNewUserResponse alloc] init];
  742. [self postWithRequest:request
  743. response:response
  744. callback:^(NSError *error) {
  745. if (error) {
  746. callback(nil, error);
  747. } else {
  748. callback(response, nil);
  749. }
  750. }];
  751. }
  752. - (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback {
  753. FIRDeleteAccountResponse *response = [[FIRDeleteAccountResponse alloc] init];
  754. [self postWithRequest:request response:response callback:callback];
  755. }
  756. #if TARGET_OS_IOS
  757. - (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request
  758. callback:(FIRSendVerificationCodeResponseCallback)callback {
  759. FIRSendVerificationCodeResponse *response = [[FIRSendVerificationCodeResponse alloc] init];
  760. [self postWithRequest:request
  761. response:response
  762. callback:^(NSError *error) {
  763. if (error) {
  764. callback(nil, error);
  765. } else {
  766. callback(response, error);
  767. }
  768. }];
  769. }
  770. - (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request
  771. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  772. FIRVerifyPhoneNumberResponse *response = [[FIRVerifyPhoneNumberResponse alloc] init];
  773. [self
  774. postWithRequest:request
  775. response:response
  776. callback:^(NSError *error) {
  777. if (error) {
  778. callback(nil, error);
  779. return;
  780. }
  781. // Check whether or not the successful response is actually the special case phone
  782. // auth flow that returns a temporary proof and phone number.
  783. if (response.phoneNumber.length && response.temporaryProof.length) {
  784. FIRPhoneAuthCredential *credential =
  785. [[FIRPhoneAuthCredential alloc] initWithTemporaryProof:response.temporaryProof
  786. phoneNumber:response.phoneNumber
  787. providerID:FIRPhoneAuthProviderID];
  788. callback(nil, [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:nil
  789. credential:credential
  790. email:nil]);
  791. return;
  792. }
  793. callback(response, nil);
  794. }];
  795. }
  796. - (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback {
  797. FIRVerifyClientResponse *response = [[FIRVerifyClientResponse alloc] init];
  798. [self postWithRequest:request
  799. response:response
  800. callback:^(NSError *error) {
  801. if (error) {
  802. callback(nil, error);
  803. return;
  804. }
  805. callback(response, nil);
  806. }];
  807. }
  808. #endif
  809. - (void)resetPassword:(FIRResetPasswordRequest *)request
  810. callback:(FIRResetPasswordCallback)callback {
  811. FIRResetPasswordResponse *response = [[FIRResetPasswordResponse alloc] init];
  812. [self postWithRequest:request
  813. response:response
  814. callback:^(NSError *error) {
  815. if (error) {
  816. callback(nil, error);
  817. return;
  818. }
  819. callback(response, nil);
  820. }];
  821. }
  822. - (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request
  823. callback:(FIRSignInWithGameCenterResponseCallback)callback {
  824. FIRSignInWithGameCenterResponse *response = [[FIRSignInWithGameCenterResponse alloc] init];
  825. [self postWithRequest:request
  826. response:response
  827. callback:^(NSError *error) {
  828. if (error) {
  829. if (callback) {
  830. callback(nil, error);
  831. }
  832. } else {
  833. if (callback) {
  834. callback(response, nil);
  835. }
  836. }
  837. }];
  838. }
  839. #pragma mark - Generic RPC handling methods
  840. /** @fn postWithRequest:response:callback:
  841. @brief Calls the RPC using HTTP POST.
  842. @remarks Possible error responses:
  843. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  844. @see FIRAuthInternalErrorCodeJSONSerializationError
  845. @see FIRAuthInternalErrorCodeNetworkError
  846. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  847. @see FIRAuthInternalErrorCodeUnexpectedResponse
  848. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  849. @param request The request.
  850. @param response The empty response to be filled.
  851. @param callback The callback for both success and failure.
  852. */
  853. - (void)postWithRequest:(id<FIRAuthRPCRequest>)request
  854. response:(id<FIRAuthRPCResponse>)response
  855. callback:(void (^)(NSError *_Nullable error))callback {
  856. NSError *error;
  857. NSData *bodyData;
  858. if ([request containsPostBody]) {
  859. id postBody = [request unencodedHTTPRequestBodyWithError:&error];
  860. if (!postBody) {
  861. callback([FIRAuthErrorUtils RPCRequestEncodingErrorWithUnderlyingError:error]);
  862. return;
  863. }
  864. NSJSONWritingOptions JSONWritingOptions = 0;
  865. #if DEBUG
  866. JSONWritingOptions |= NSJSONWritingPrettyPrinted;
  867. #endif
  868. if ([NSJSONSerialization isValidJSONObject:postBody]) {
  869. bodyData = [NSJSONSerialization dataWithJSONObject:postBody
  870. options:JSONWritingOptions
  871. error:&error];
  872. if (!bodyData) {
  873. // This is an untested case. This happens exclusively when there is an error in the
  874. // framework implementation of dataWithJSONObject:options:error:. This shouldn't normally
  875. // occur as isValidJSONObject: should return NO in any case we should encounter an error.
  876. error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:error];
  877. }
  878. } else {
  879. error = [FIRAuthErrorUtils JSONSerializationErrorForUnencodableType];
  880. }
  881. if (!bodyData) {
  882. callback(error);
  883. return;
  884. }
  885. }
  886. [_RPCIssuer
  887. asyncPostToURLWithRequestConfiguration:[request requestConfiguration]
  888. URL:[request requestURL]
  889. body:bodyData
  890. contentType:kJSONContentType
  891. completionHandler:^(NSData *data, NSError *error) {
  892. // If there is an error with no body data at all, then this must be a
  893. // network error.
  894. if (error && !data) {
  895. callback([FIRAuthErrorUtils networkErrorWithUnderlyingError:error]);
  896. return;
  897. }
  898. // Try to decode the HTTP response data which may contain either a
  899. // successful response or error message.
  900. NSError *jsonError;
  901. NSDictionary *dictionary =
  902. [NSJSONSerialization JSONObjectWithData:data
  903. options:NSJSONReadingMutableLeaves
  904. error:&jsonError];
  905. if (!dictionary) {
  906. if (error) {
  907. // We have an error, but we couldn't decode the body, so we have no
  908. // additional information other than the raw response and the
  909. // original NSError (the jsonError is infered by the error code
  910. // (FIRAuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  911. callback([FIRAuthErrorUtils
  912. unexpectedErrorResponseWithData:data
  913. underlyingError:error]);
  914. } else {
  915. // This is supposed to be a "successful" response, but we couldn't
  916. // deserialize the body.
  917. callback([FIRAuthErrorUtils unexpectedResponseWithData:data
  918. underlyingError:jsonError]);
  919. }
  920. return;
  921. }
  922. if (![dictionary isKindOfClass:[NSDictionary class]]) {
  923. if (error) {
  924. callback([FIRAuthErrorUtils
  925. unexpectedErrorResponseWithDeserializedResponse:dictionary
  926. underlyingError:error]);
  927. } else {
  928. callback([FIRAuthErrorUtils
  929. unexpectedResponseWithDeserializedResponse:dictionary]);
  930. }
  931. return;
  932. }
  933. // At this point we either have an error with successfully decoded
  934. // details in the body, or we have a response which must pass further
  935. // validation before we know it's truly successful. We deal with the
  936. // case where we have an error with successfully decoded error details
  937. // first:
  938. if (error) {
  939. NSDictionary *errorDictionary = dictionary[kErrorKey];
  940. if ([errorDictionary isKindOfClass:[NSDictionary class]]) {
  941. id<NSObject> errorMessage = errorDictionary[kErrorMessageKey];
  942. if ([errorMessage isKindOfClass:[NSString class]]) {
  943. NSString *errorMessageString = (NSString *)errorMessage;
  944. // Contruct client error.
  945. NSError *clientError = [[self class]
  946. clientErrorWithServerErrorMessage:errorMessageString
  947. errorDictionary:errorDictionary
  948. response:response];
  949. if (clientError) {
  950. callback(clientError);
  951. return;
  952. }
  953. }
  954. // Not a message we know, return the message directly.
  955. if (errorMessage) {
  956. NSError *unexpecterErrorResponse = [FIRAuthErrorUtils
  957. unexpectedErrorResponseWithDeserializedResponse:
  958. errorDictionary
  959. underlyingError:error];
  960. callback(unexpecterErrorResponse);
  961. return;
  962. }
  963. }
  964. // No error message at all, return the decoded response.
  965. callback([FIRAuthErrorUtils
  966. unexpectedErrorResponseWithDeserializedResponse:dictionary
  967. underlyingError:error]);
  968. return;
  969. }
  970. // Finally, we try to populate the response object with the JSON
  971. // values.
  972. if (![response setWithDictionary:dictionary error:&error]) {
  973. callback([FIRAuthErrorUtils
  974. RPCResponseDecodingErrorWithDeserializedResponse:dictionary
  975. underlyingError:error]);
  976. return;
  977. }
  978. // In case returnIDPCredential of a verifyAssertion request is set to
  979. // @YES, the server may return a 200 with a response that may contain a
  980. // server error.
  981. if ([request isKindOfClass:[FIRVerifyAssertionRequest class]]) {
  982. FIRVerifyAssertionRequest *verifyAssertionRequest =
  983. (FIRVerifyAssertionRequest *)request;
  984. if (verifyAssertionRequest.returnIDPCredential) {
  985. NSString *errorMessage =
  986. dictionary[kReturnIDPCredentialErrorMessageKey];
  987. if ([errorMessage isKindOfClass:[NSString class]]) {
  988. NSString *errorString = (NSString *)errorMessage;
  989. NSError *clientError =
  990. [[self class] clientErrorWithServerErrorMessage:errorString
  991. errorDictionary:@{}
  992. response:response];
  993. if (clientError) {
  994. callback(clientError);
  995. return;
  996. }
  997. }
  998. }
  999. }
  1000. // Success! The response object originally passed in can be used by the
  1001. // caller.
  1002. callback(nil);
  1003. }];
  1004. }
  1005. /** @fn clientErrorWithServerErrorMessage:errorDictionary:
  1006. @brief Translates known server errors to client errors.
  1007. @param serverErrorMessage The error message from the server.
  1008. @param errorDictionary The error part of the response from the server.
  1009. @param response The response from the server RPC.
  1010. @return A client error, if any.
  1011. */
  1012. + (nullable NSError *)clientErrorWithServerErrorMessage:(NSString *)serverErrorMessage
  1013. errorDictionary:(NSDictionary *)errorDictionary
  1014. response:(id<FIRAuthRPCResponse>)response {
  1015. NSString *shortErrorMessage = serverErrorMessage;
  1016. NSString *serverDetailErrorMessage;
  1017. NSRange colonRange = [serverErrorMessage rangeOfString:@":"];
  1018. if (colonRange.location != NSNotFound) {
  1019. shortErrorMessage = [serverErrorMessage substringToIndex:colonRange.location];
  1020. shortErrorMessage =
  1021. [shortErrorMessage stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  1022. serverDetailErrorMessage = [serverErrorMessage substringFromIndex:colonRange.location + 1];
  1023. serverDetailErrorMessage = [serverDetailErrorMessage
  1024. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  1025. }
  1026. // Delegate the responsibility for constructing the client error to the response object,
  1027. // if possible.
  1028. SEL clientErrorWithServerErrorMessageSelector = @selector(clientErrorWithShortErrorMessage:
  1029. detailErrorMessage:);
  1030. if ([response respondsToSelector:clientErrorWithServerErrorMessageSelector]) {
  1031. NSError *error = [response clientErrorWithShortErrorMessage:shortErrorMessage
  1032. detailErrorMessage:serverDetailErrorMessage];
  1033. if (error) {
  1034. return error;
  1035. }
  1036. }
  1037. if ([shortErrorMessage isEqualToString:kUserNotFoundErrorMessage]) {
  1038. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  1039. }
  1040. if ([shortErrorMessage isEqualToString:kUserDeletedErrorMessage]) {
  1041. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  1042. }
  1043. if ([shortErrorMessage isEqualToString:kInvalidLocalIDErrorMessage]) {
  1044. // This case shouldn't be necessary but it is for now: b/27908364 .
  1045. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  1046. }
  1047. if ([shortErrorMessage isEqualToString:kUserTokenExpiredErrorMessage]) {
  1048. return [FIRAuthErrorUtils userTokenExpiredErrorWithMessage:serverDetailErrorMessage];
  1049. }
  1050. if ([shortErrorMessage isEqualToString:kTooManyRequestsErrorMessage]) {
  1051. return [FIRAuthErrorUtils tooManyRequestsErrorWithMessage:serverDetailErrorMessage];
  1052. }
  1053. if ([shortErrorMessage isEqualToString:kInvalidCustomTokenErrorMessage]) {
  1054. return [FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:serverDetailErrorMessage];
  1055. }
  1056. if ([shortErrorMessage isEqualToString:kCustomTokenMismatch]) {
  1057. return [FIRAuthErrorUtils customTokenMistmatchErrorWithMessage:serverDetailErrorMessage];
  1058. }
  1059. if ([shortErrorMessage isEqualToString:kInvalidCredentialErrorMessage] ||
  1060. [shortErrorMessage isEqualToString:kInvalidPendingToken]) {
  1061. return [FIRAuthErrorUtils invalidCredentialErrorWithMessage:serverDetailErrorMessage];
  1062. }
  1063. if ([shortErrorMessage isEqualToString:kUserDisabledErrorMessage]) {
  1064. return [FIRAuthErrorUtils userDisabledErrorWithMessage:serverDetailErrorMessage];
  1065. }
  1066. if ([shortErrorMessage isEqualToString:kOperationNotAllowedErrorMessage]) {
  1067. return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage];
  1068. }
  1069. if ([shortErrorMessage isEqualToString:kPasswordLoginDisabledErrorMessage]) {
  1070. return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage];
  1071. }
  1072. if ([shortErrorMessage isEqualToString:kEmailAlreadyInUseErrorMessage]) {
  1073. return [FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:nil];
  1074. }
  1075. if ([shortErrorMessage isEqualToString:kInvalidEmailErrorMessage]) {
  1076. return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage];
  1077. }
  1078. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  1079. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in this
  1080. // case.
  1081. if ([shortErrorMessage isEqualToString:kInvalidIdentifierErrorMessage]) {
  1082. return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage];
  1083. }
  1084. if ([shortErrorMessage isEqualToString:kWrongPasswordErrorMessage]) {
  1085. return [FIRAuthErrorUtils wrongPasswordErrorWithMessage:serverDetailErrorMessage];
  1086. }
  1087. if ([shortErrorMessage isEqualToString:kCredentialTooOldErrorMessage]) {
  1088. return [FIRAuthErrorUtils requiresRecentLoginErrorWithMessage:serverDetailErrorMessage];
  1089. }
  1090. if ([shortErrorMessage isEqualToString:kInvalidUserTokenErrorMessage]) {
  1091. return [FIRAuthErrorUtils invalidUserTokenErrorWithMessage:serverDetailErrorMessage];
  1092. }
  1093. if ([shortErrorMessage isEqualToString:kFederatedUserIDAlreadyLinkedMessage]) {
  1094. FIROAuthCredential *credential;
  1095. NSString *email;
  1096. if ([response isKindOfClass:[FIRVerifyAssertionResponse class]]) {
  1097. FIRVerifyAssertionResponse *verifyAssertion = (FIRVerifyAssertionResponse *)response;
  1098. credential = [[FIROAuthCredential alloc] initWithVerifyAssertionResponse:verifyAssertion];
  1099. email = verifyAssertion.email;
  1100. }
  1101. return [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:serverDetailErrorMessage
  1102. credential:credential
  1103. email:email];
  1104. }
  1105. if ([shortErrorMessage isEqualToString:kWeakPasswordErrorMessagePrefix]) {
  1106. return [FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:serverDetailErrorMessage];
  1107. }
  1108. if ([shortErrorMessage isEqualToString:kExpiredActionCodeErrorMessage]) {
  1109. return [FIRAuthErrorUtils expiredActionCodeErrorWithMessage:serverDetailErrorMessage];
  1110. }
  1111. if ([shortErrorMessage isEqualToString:kInvalidActionCodeErrorMessage]) {
  1112. return [FIRAuthErrorUtils invalidActionCodeErrorWithMessage:serverDetailErrorMessage];
  1113. }
  1114. if ([shortErrorMessage isEqualToString:kMissingEmailErrorMessage]) {
  1115. return [FIRAuthErrorUtils missingEmailErrorWithMessage:serverDetailErrorMessage];
  1116. }
  1117. if ([shortErrorMessage isEqualToString:kInvalidSenderEmailErrorMessage]) {
  1118. return [FIRAuthErrorUtils invalidSenderErrorWithMessage:serverDetailErrorMessage];
  1119. }
  1120. if ([shortErrorMessage isEqualToString:kInvalidMessagePayloadErrorMessage]) {
  1121. return [FIRAuthErrorUtils invalidMessagePayloadErrorWithMessage:serverDetailErrorMessage];
  1122. }
  1123. if ([shortErrorMessage isEqualToString:kInvalidRecipientEmailErrorMessage]) {
  1124. return [FIRAuthErrorUtils invalidRecipientEmailErrorWithMessage:serverDetailErrorMessage];
  1125. }
  1126. if ([shortErrorMessage isEqualToString:kMissingIosBundleIDErrorMessage]) {
  1127. return [FIRAuthErrorUtils missingIosBundleIDErrorWithMessage:serverDetailErrorMessage];
  1128. }
  1129. if ([shortErrorMessage isEqualToString:kMissingAndroidPackageNameErrorMessage]) {
  1130. return [FIRAuthErrorUtils missingAndroidPackageNameErrorWithMessage:serverDetailErrorMessage];
  1131. }
  1132. if ([shortErrorMessage isEqualToString:kUnauthorizedDomainErrorMessage]) {
  1133. return [FIRAuthErrorUtils unauthorizedDomainErrorWithMessage:serverDetailErrorMessage];
  1134. }
  1135. if ([shortErrorMessage isEqualToString:kInvalidContinueURIErrorMessage]) {
  1136. return [FIRAuthErrorUtils invalidContinueURIErrorWithMessage:serverDetailErrorMessage];
  1137. }
  1138. if ([shortErrorMessage isEqualToString:kInvalidProviderIDErrorMessage]) {
  1139. return [FIRAuthErrorUtils invalidProviderIDErrorWithMessage:serverDetailErrorMessage];
  1140. }
  1141. if ([shortErrorMessage isEqualToString:kInvalidDynamicLinkDomainErrorMessage]) {
  1142. return [FIRAuthErrorUtils invalidDynamicLinkDomainErrorWithMessage:serverDetailErrorMessage];
  1143. }
  1144. if ([shortErrorMessage isEqualToString:kMissingContinueURIErrorMessage]) {
  1145. return [FIRAuthErrorUtils missingContinueURIErrorWithMessage:serverDetailErrorMessage];
  1146. }
  1147. if ([shortErrorMessage isEqualToString:kInvalidPhoneNumberErrorMessage]) {
  1148. return [FIRAuthErrorUtils invalidPhoneNumberErrorWithMessage:serverDetailErrorMessage];
  1149. }
  1150. if ([shortErrorMessage isEqualToString:kInvalidSessionInfoErrorMessage]) {
  1151. return [FIRAuthErrorUtils invalidVerificationIDErrorWithMessage:serverDetailErrorMessage];
  1152. }
  1153. if ([shortErrorMessage isEqualToString:kInvalidVerificationCodeErrorMessage]) {
  1154. return [FIRAuthErrorUtils invalidVerificationCodeErrorWithMessage:serverDetailErrorMessage];
  1155. }
  1156. if ([shortErrorMessage isEqualToString:kSessionExpiredErrorMessage]) {
  1157. return [FIRAuthErrorUtils sessionExpiredErrorWithMessage:serverDetailErrorMessage];
  1158. }
  1159. if ([shortErrorMessage isEqualToString:kMissingAppTokenErrorMessage]) {
  1160. return [FIRAuthErrorUtils missingAppTokenErrorWithUnderlyingError:nil];
  1161. }
  1162. if ([shortErrorMessage isEqualToString:kMissingAppCredentialErrorMessage]) {
  1163. return [FIRAuthErrorUtils missingAppCredentialWithMessage:serverDetailErrorMessage];
  1164. }
  1165. if ([shortErrorMessage isEqualToString:kInvalidAppCredentialErrorMessage]) {
  1166. return [FIRAuthErrorUtils invalidAppCredentialWithMessage:serverDetailErrorMessage];
  1167. }
  1168. if ([shortErrorMessage isEqualToString:kQuoutaExceededErrorMessage]) {
  1169. return [FIRAuthErrorUtils quotaExceededErrorWithMessage:serverErrorMessage];
  1170. }
  1171. if ([shortErrorMessage isEqualToString:kAppNotVerifiedErrorMessage]) {
  1172. return [FIRAuthErrorUtils appNotVerifiedErrorWithMessage:serverErrorMessage];
  1173. }
  1174. if ([shortErrorMessage isEqualToString:kMissingClientIdentifier]) {
  1175. return [FIRAuthErrorUtils missingClientIdentifierErrorWithMessage:serverErrorMessage];
  1176. }
  1177. if ([shortErrorMessage isEqualToString:kCaptchaCheckFailedErrorMessage]) {
  1178. return [FIRAuthErrorUtils captchaCheckFailedErrorWithMessage:serverErrorMessage];
  1179. }
  1180. if ([shortErrorMessage isEqualToString:kMissingOrInvalidNonceErrorMessage]) {
  1181. return [FIRAuthErrorUtils missingOrInvalidNonceErrorWithMessage:serverDetailErrorMessage];
  1182. }
  1183. if ([shortErrorMessage isEqualToString:kMissingMFAPendingCredentialErrorMessage]) {
  1184. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMissingMultiFactorSession
  1185. message:serverErrorMessage];
  1186. }
  1187. if ([shortErrorMessage isEqualToString:kMissingMFAEnrollmentIDErrorMessage]) {
  1188. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMissingMultiFactorInfo
  1189. message:serverErrorMessage];
  1190. }
  1191. if ([shortErrorMessage isEqualToString:kInvalidMFAPendingCredentialErrorMessage]) {
  1192. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeInvalidMultiFactorSession
  1193. message:serverErrorMessage];
  1194. }
  1195. if ([shortErrorMessage isEqualToString:kMFAEnrollmentNotFoundErrorMessage]) {
  1196. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMultiFactorInfoNotFound
  1197. message:serverErrorMessage];
  1198. }
  1199. if ([shortErrorMessage isEqualToString:kAdminOnlyOperationErrorMessage]) {
  1200. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeAdminRestrictedOperation
  1201. message:serverErrorMessage];
  1202. }
  1203. if ([shortErrorMessage isEqualToString:kUnverifiedEmailErrorMessage]) {
  1204. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeUnverifiedEmail
  1205. message:serverErrorMessage];
  1206. }
  1207. if ([shortErrorMessage isEqualToString:kSecondFactorExistsErrorMessage]) {
  1208. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeSecondFactorAlreadyEnrolled
  1209. message:serverErrorMessage];
  1210. }
  1211. if ([shortErrorMessage isEqualToString:kSecondFactorLimitExceededErrorMessage]) {
  1212. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMaximumSecondFactorCountExceeded
  1213. message:serverErrorMessage];
  1214. }
  1215. if ([shortErrorMessage isEqualToString:kUnsupportedFirstFactorErrorMessage]) {
  1216. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeUnsupportedFirstFactor
  1217. message:serverErrorMessage];
  1218. }
  1219. if ([shortErrorMessage isEqualToString:kEmailChangeNeedsVerificationErrorMessage]) {
  1220. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeEmailChangeNeedsVerification
  1221. message:serverErrorMessage];
  1222. }
  1223. if ([shortErrorMessage isEqualToString:kTenantIDMismatch]) {
  1224. return [FIRAuthErrorUtils tenantIDMismatchError];
  1225. }
  1226. if ([shortErrorMessage isEqualToString:kUnsupportedTenantOperation]) {
  1227. return [FIRAuthErrorUtils unsupportedTenantOperationError];
  1228. }
  1229. // In this case we handle an error that might be specified in the underlying errors dictionary,
  1230. // the error message in determined based on the @c reason key in the dictionary.
  1231. if (errorDictionary[kErrorsKey]) {
  1232. // Check for underlying error with reason = keyInvalid;
  1233. id underlyingErrors = errorDictionary[kErrorsKey];
  1234. if ([underlyingErrors isKindOfClass:[NSArray class]]) {
  1235. NSArray *underlyingErrorsArray = (NSArray *)underlyingErrors;
  1236. for (id underlyingError in underlyingErrorsArray) {
  1237. if ([underlyingError isKindOfClass:[NSDictionary class]]) {
  1238. NSDictionary *underlyingErrorDictionary = (NSDictionary *)underlyingError;
  1239. NSString *reason = underlyingErrorDictionary[kReasonKey];
  1240. if ([reason hasPrefix:kInvalidKeyReasonValue]) {
  1241. return [FIRAuthErrorUtils invalidAPIKeyError];
  1242. }
  1243. if ([reason isEqualToString:kAppNotAuthorizedReasonValue]) {
  1244. return [FIRAuthErrorUtils appNotAuthorizedError];
  1245. }
  1246. }
  1247. }
  1248. }
  1249. }
  1250. return nil;
  1251. }
  1252. @end
  1253. NS_ASSUME_NONNULL_END