FIRAuthTests.m 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470
  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 <Foundation/Foundation.h>
  17. #import <OCMock/OCMock.h>
  18. #import <XCTest/XCTest.h>
  19. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  20. #import "FirebaseAuth/Interop/FIRAuthInterop.h"
  21. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRActionCodeSettings.h"
  22. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAdditionalUserInfo.h"
  23. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthSettings.h"
  24. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIREmailAuthProvider.h"
  25. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRFacebookAuthProvider.h"
  26. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRGoogleAuthProvider.h"
  27. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIROAuthProvider.h"
  28. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  29. #import "FirebaseAuth/Sources/Auth/FIRAuthDispatcher.h"
  30. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  31. #import "FirebaseAuth/Sources/Auth/FIRAuthOperationType.h"
  32. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  33. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  34. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  35. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIRequest.h"
  36. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIResponse.h"
  37. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
  38. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
  39. #import "FirebaseAuth/Sources/Backend/RPC/FIRFinalizePasskeySignInRequest.h"
  40. #import "FirebaseAuth/Sources/Backend/RPC/FIRFinalizePasskeySignInResponse.h"
  41. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoRequest.h"
  42. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoResponse.h"
  43. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
  44. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
  45. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordRequest.h"
  46. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordResponse.h"
  47. #import "FirebaseAuth/Sources/Backend/RPC/FIRRevokeTokenRequest.h"
  48. #import "FirebaseAuth/Sources/Backend/RPC/FIRRevokeTokenResponse.h"
  49. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenRequest.h"
  50. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenResponse.h"
  51. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
  52. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
  53. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
  54. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
  55. #import "FirebaseAuth/Sources/Backend/RPC/FIRStartPasskeySignInRequest.h"
  56. #import "FirebaseAuth/Sources/Backend/RPC/FIRStartPasskeySignInResponse.h"
  57. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
  58. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
  59. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
  60. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
  61. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
  62. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
  63. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
  64. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
  65. #import "FirebaseAuth/Sources/User/FIRUser_Internal.h"
  66. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  67. #import "FirebaseAuth/Sources/Utilities/FIRAuthRecaptchaVerifier.h"
  68. #import "FirebaseAuth/Tests/Unit/FIRApp+FIRAuthUnitTests.h"
  69. #import "FirebaseAuth/Tests/Unit/OCMStubRecorder+FIRAuthUnitTests.h"
  70. #if TARGET_OS_IOS
  71. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthUIDelegate.h"
  72. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthCredential.h"
  73. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
  74. #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSToken.h"
  75. #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSTokenManager.h"
  76. #import "FirebaseAuth/Sources/SystemService/FIRAuthNotificationManager.h"
  77. #import "FirebaseAuth/Sources/Utilities/FIRAuthURLPresenter.h"
  78. #endif // TARGET_OS_IOS
  79. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  80. #import <AuthenticationServices/AuthenticationServices.h>
  81. #endif
  82. /** @var kAPIKey
  83. @brief The fake API key.
  84. */
  85. static NSString *const kAPIKey = @"FAKE_API_KEY";
  86. /** @var kFirebaseAppID
  87. @brief The fake Firebase app ID.
  88. */
  89. static NSString *const kFirebaseAppID = @"FAKE_APP_ID";
  90. /** @var kAccessToken
  91. @brief The fake access token.
  92. */
  93. static NSString *const kAccessToken = @"ACCESS_TOKEN";
  94. /** @var kNewAccessToken
  95. @brief Another fake access token used to simulate token refreshed via automatic token refresh.
  96. */
  97. NSString *kNewAccessToken = @"NewAccessToken";
  98. /** @var kAccessTokenValidInterval
  99. @brief The time to live for the fake access token.
  100. */
  101. static const NSTimeInterval kAccessTokenTimeToLive = 60 * 60;
  102. /** @var kTestTokenExpirationTimeInterval
  103. @brief The fake time interval that it takes a token to expire.
  104. */
  105. static const NSTimeInterval kTestTokenExpirationTimeInterval = 55 * 60;
  106. /** @var kRefreshToken
  107. @brief The fake refresh token.
  108. */
  109. static NSString *const kRefreshToken = @"REFRESH_TOKEN";
  110. /** @var kEmail
  111. @brief The fake user email.
  112. */
  113. static NSString *const kEmail = @"user@company.com";
  114. /** @var kFakePassword
  115. @brief The fake user password.
  116. */
  117. static NSString *const kFakePassword = @"!@#$%^";
  118. /** @var kPasswordHash
  119. @brief The fake user password hash.
  120. */
  121. static NSString *const kPasswordHash = @"UkVEQUNURUQ=";
  122. /** @var kLocalID
  123. @brief The fake local user ID.
  124. */
  125. static NSString *const kLocalID = @"LOCAL_ID";
  126. /** @var kDisplayName
  127. @brief The fake user display name.
  128. */
  129. static NSString *const kDisplayName = @"User Doe";
  130. /** @var kFakeGivenName
  131. @brief The fake user given name.
  132. */
  133. static NSString *const kFakeGivenName = @"Firstname";
  134. /** @var kFakeFamilyName
  135. @brief The fake user family name.
  136. */
  137. static NSString *const kFakeFamilyName = @"Lastname";
  138. /** @var kGoogleUD
  139. @brief The fake user ID under Google Sign-In.
  140. */
  141. static NSString *const kGoogleID = @"GOOGLE_ID";
  142. /** @var kGoogleEmail
  143. @brief The fake user email under Google Sign-In.
  144. */
  145. static NSString *const kGoogleEmail = @"user@gmail.com";
  146. /** @var kGoogleDisplayName
  147. @brief The fake user display name under Google Sign-In.
  148. */
  149. static NSString *const kGoogleDisplayName = @"Google Doe";
  150. /** @var kGoogleAccessToken
  151. @brief The fake access token from Google Sign-In.
  152. */
  153. static NSString *const kGoogleAccessToken = @"GOOGLE_ACCESS_TOKEN";
  154. /** @var kGoogleIDToken
  155. @brief The fake ID token from Google Sign-In.
  156. */
  157. static NSString *const kGoogleIDToken = @"GOOGLE_ID_TOKEN";
  158. /** @var kAppleAuthProviderID
  159. @brief The provider ID for Apple Sign-In.
  160. */
  161. static NSString *const kAppleAuthProviderID = @"apple.com";
  162. /** @var kAppleIDToken
  163. @brief The fake ID token from Apple Sign-In.
  164. */
  165. static NSString *const kAppleIDToken = @"APPLE_ID_TOKEN";
  166. /** @var kCustomToken
  167. @brief The fake custom token to sign in.
  168. */
  169. static NSString *const kCustomToken = @"CUSTOM_TOKEN";
  170. /** @var kVerificationCode
  171. @brief Fake verification code used for testing.
  172. */
  173. static NSString *const kVerificationCode = @"12345678";
  174. /** @var kVerificationID
  175. @brief Fake verification ID for testing.
  176. */
  177. static NSString *const kVerificationID = @"55432";
  178. /** @var kOAuthRequestURI
  179. @brief Fake OAuthRequest URI for testing.
  180. */
  181. static NSString *const kOAuthRequestURI = @"requestURI";
  182. /** @var kOAuthSessionID
  183. @brief Fake session ID for testing.
  184. */
  185. static NSString *const kOAuthSessionID = @"sessionID";
  186. /** @var kFakeWebSignInUserInteractionFailureReason
  187. @brief Fake reason for FIRAuthErrorCodeWebSignInUserInteractionFailure error while testing.
  188. */
  189. static NSString *const kFakeWebSignInUserInteractionFailureReason = @"fake_reason";
  190. /** @var kContinueURL
  191. @brief Fake string value of continue url.
  192. */
  193. static NSString *const kContinueURL = @"continueURL";
  194. /** @var kCanHandleCodeInAppKey
  195. @brief The key for the request parameter indicating whether the action code can be handled in
  196. the app or not.
  197. */
  198. static NSString *const kCanHandleCodeInAppKey = @"canHandleCodeInApp";
  199. /** @var kFIREmailLinkAuthSignInMethod
  200. @brief Fake email link sign-in method for testing.
  201. */
  202. static NSString *const kFIREmailLinkAuthSignInMethod = @"emailLink";
  203. /** @var kFIRFacebookAuthSignInMethod
  204. @brief Fake Facebook sign-in method for testing.
  205. */
  206. static NSString *const kFIRFacebookAuthSignInMethod = @"facebook.com";
  207. /** @var kBadSignInEmailLink
  208. @brief Bad sign-in link to test email link sign-in
  209. */
  210. static NSString *const kBadSignInEmailLink = @"http://www.facebook.com";
  211. /** @var kFakeEmailSignInDeeplink
  212. @brief Fake email sign-in link
  213. */
  214. static NSString *const kFakeEmailSignInDeeplink =
  215. @"https://example.domain.com/?apiKey=testAPIKey&oobCode=testoobcode&mode=signIn";
  216. /** @var kFakeEmailSignInlink
  217. @brief Fake email sign-in link
  218. */
  219. static NSString *const kFakeEmailSignInlink =
  220. @"https://test.app.goo.gl/?link=https://test.firebase"
  221. "app.com/__/auth/"
  222. "action?apiKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueU"
  223. "rl%3Dhttps://test.apps.com&ibi=com.test.com&ifl=https://test.firebaseapp.com/__/auth/"
  224. "action?ap"
  225. "iKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueUrl%3Dhttps://"
  226. "test.apps.co"
  227. "m";
  228. /** @var kExpectationTimeout
  229. @brief The maximum time waiting for expectations to fulfill.
  230. */
  231. static const NSTimeInterval kExpectationTimeout = 2;
  232. /** @var kWaitInterval
  233. @brief The time waiting for background tasks to finish before continue when necessary.
  234. */
  235. static const NSTimeInterval kWaitInterval = .5;
  236. /** @var kFakeRecaptchaResponse
  237. @brief The fake recaptcha response.
  238. */
  239. static NSString *const kFakeRecaptchaResponse = @"RecaptchaResponse";
  240. /** @var kFakeRecaptchaVersion
  241. @brief The fake recaptcha version.
  242. */
  243. static NSString *const kFakeRecaptchaVersion = @"RecaptchaVersion";
  244. /** @var kRpId
  245. @brief The fake passkey relying party identifier.
  246. */
  247. static NSString *const kRpId = @"fake.rp.id";
  248. /** @var kChallenge
  249. @brief The fake passkey challenge.
  250. */
  251. static NSString *const kChallenge = @"Y2hhbGxlbmdl"; // decode to "challenge"
  252. /** @var kCredentialID
  253. @brief The fake passkey credentialID.
  254. */
  255. static NSString *const kCredentialID = @"Y3JlZGVudGlhbGlk"; // decode to "credentialid"
  256. /** @var kClientDataJson
  257. @brief The fake clientDataJson object
  258. */
  259. static NSString *const kClientDataJson = @"Y2xpZW50ZGF0YWpzb24="; // decode to "clientdatajson"
  260. /** @var kAuthenticatorData
  261. @brief The fake authenticatorData object
  262. */
  263. static NSString *const kAuthenticatorData =
  264. @"YXV0aGVudGljYXRvcmRhdGE="; // decode to "authenticatordata"
  265. /** @var kSignature
  266. @brief The fake signature
  267. */
  268. static NSString *const kSignature = @"c2lnbmF0dXJl"; // decode to "signature"
  269. /** @var kUserID
  270. @brief The fake user ID / user handle
  271. */
  272. static NSString *const kUserID = @"dXNlcmlk"; // decode to "userid"
  273. #if TARGET_OS_IOS
  274. /** @class FIRAuthAppDelegate
  275. @brief Application delegate implementation to test the app delegate proxying
  276. */
  277. @interface FIRAuthAppDelegate : NSObject <UIApplicationDelegate>
  278. @end
  279. @implementation FIRAuthAppDelegate
  280. - (void)application:(UIApplication *)application
  281. didReceiveRemoteNotification:(NSDictionary *)userInfo
  282. fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  283. }
  284. - (BOOL)application:(UIApplication *)app
  285. openURL:(NSURL *)url
  286. options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
  287. return NO;
  288. }
  289. @end
  290. #endif // TARGET_OS_IOS
  291. @interface GULAppDelegateSwizzler (FIRMessagingRemoteNotificationsProxyTest)
  292. + (void)resetProxyOriginalDelegateOnceToken;
  293. @end
  294. /** Category for FIRAuth to expose FIRComponentRegistrant conformance. */
  295. @interface FIRAuth () <FIRLibrary>
  296. @end
  297. /** @class FIRAuthTests
  298. @brief Tests for @c FIRAuth.
  299. */
  300. @interface FIRAuthTests : XCTestCase
  301. #if TARGET_OS_IOS
  302. /// A partial mock of `[FIRAuth auth].tokenManager`
  303. @property(nonatomic, strong) id mockTokenManager;
  304. /// A partial mock of `[FIRAuth auth].notificationManager`
  305. @property(nonatomic, strong) id mockNotificationManager;
  306. /// A partial mock of `[FIRAuth auth].authURLPresenter`
  307. @property(nonatomic, strong) id mockAuthURLPresenter;
  308. /// An application delegate instance returned by `self.mockApplication.delegate`
  309. @property(nonatomic, strong) FIRAuthAppDelegate *fakeApplicationDelegate;
  310. #endif // TARGET_OS_IOS
  311. @end
  312. @implementation FIRAuthTests {
  313. /** @var _mockBackend
  314. @brief The mock @c FIRAuthBackendImplementation .
  315. */
  316. id _mockBackend;
  317. /** @var _FIRAuthDispatcherCallback
  318. @brief Used to save a task from FIRAuthDispatcher to be executed later.
  319. */
  320. __block void (^_Nonnull _FIRAuthDispatcherCallback)(void);
  321. }
  322. /** @fn googleProfile
  323. @brief The fake user profile under additional user data in @c FIRVerifyAssertionResponse.
  324. */
  325. + (NSDictionary *)googleProfile {
  326. static NSDictionary *kGoogleProfile = nil;
  327. static dispatch_once_t onceToken;
  328. dispatch_once(&onceToken, ^{
  329. kGoogleProfile = @{
  330. @"iss" : @"https://accounts.google.com\\",
  331. @"email" : kGoogleEmail,
  332. @"given_name" : @"User",
  333. @"family_name" : @"Doe"
  334. };
  335. });
  336. return kGoogleProfile;
  337. }
  338. - (void)setUp {
  339. [super setUp];
  340. #if TARGET_OS_IOS
  341. // Make sure the `self.fakeApplicationDelegate` will be swizzled on FIRAuth init.
  342. [GULAppDelegateSwizzler resetProxyOriginalDelegateOnceToken];
  343. self.fakeApplicationDelegate = [[FIRAuthAppDelegate alloc] init];
  344. [[GULAppDelegateSwizzler sharedApplication]
  345. setDelegate:(id<UIApplicationDelegate>)self.fakeApplicationDelegate];
  346. #endif // TARGET_OS_IOS
  347. _mockBackend = OCMProtocolMock(@protocol(FIRAuthBackendImplementation));
  348. [FIRAuthBackend setBackendImplementation:_mockBackend];
  349. [FIRApp resetAppForAuthUnitTests];
  350. // Set FIRAuthDispatcher implementation in order to save the token refresh task for later
  351. // execution.
  352. [[FIRAuthDispatcher sharedInstance]
  353. setDispatchAfterImplementation:^(NSTimeInterval delay, dispatch_queue_t _Nonnull queue,
  354. void (^task)(void)) {
  355. XCTAssertNotNil(task);
  356. XCTAssert(delay > 0);
  357. XCTAssertEqualObjects(FIRAuthGlobalWorkQueue(), queue);
  358. self->_FIRAuthDispatcherCallback = task;
  359. }];
  360. #if TARGET_OS_IOS
  361. // Wait until FIRAuth initialization completes
  362. [self waitForAuthGlobalWorkQueueDrain];
  363. self.mockTokenManager = OCMPartialMock([FIRAuth auth].tokenManager);
  364. self.mockNotificationManager = OCMPartialMock([FIRAuth auth].notificationManager);
  365. self.mockAuthURLPresenter = OCMPartialMock([FIRAuth auth].authURLPresenter);
  366. #endif // TARGET_OS_IOS
  367. }
  368. - (void)tearDown {
  369. [FIRAuthBackend setDefaultBackendImplementationWithRPCIssuer:nil];
  370. [[FIRAuthDispatcher sharedInstance] setDispatchAfterImplementation:nil];
  371. #if TARGET_OS_IOS
  372. [self.mockAuthURLPresenter stopMocking];
  373. self.mockAuthURLPresenter = nil;
  374. [self.mockNotificationManager stopMocking];
  375. self.mockNotificationManager = nil;
  376. [self.mockTokenManager stopMocking];
  377. self.mockTokenManager = nil;
  378. self.fakeApplicationDelegate = nil;
  379. #endif // TARGET_OS_IOS
  380. [super tearDown];
  381. }
  382. #pragma mark - Server API Tests
  383. /** @fn testFetchSignInMethodsForEmailSuccess
  384. @brief Tests the flow of a successful @c fetchSignInMethodsForEmail:completion: call.
  385. */
  386. - (void)testFetchSignInMethodsForEmailSuccess {
  387. NSArray<NSString *> *allSignInMethods =
  388. @[ kFIREmailLinkAuthSignInMethod, kFIRFacebookAuthSignInMethod ];
  389. OCMExpect([_mockBackend createAuthURI:[OCMArg any] callback:[OCMArg any]])
  390. .andCallBlock2(
  391. ^(FIRCreateAuthURIRequest *_Nullable request, FIRCreateAuthURIResponseCallback callback) {
  392. XCTAssertEqualObjects(request.identifier, kEmail);
  393. XCTAssertNotNil(request.endpoint);
  394. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  395. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  396. id mockCreateAuthURIResponse = OCMClassMock([FIRCreateAuthURIResponse class]);
  397. OCMStub([mockCreateAuthURIResponse signinMethods]).andReturn(allSignInMethods);
  398. callback(mockCreateAuthURIResponse, nil);
  399. });
  400. });
  401. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  402. [[FIRAuth auth] fetchSignInMethodsForEmail:kEmail
  403. completion:^(NSArray<NSString *> *_Nullable signInMethods,
  404. NSError *_Nullable error) {
  405. XCTAssertTrue([NSThread isMainThread]);
  406. XCTAssertEqualObjects(signInMethods, allSignInMethods);
  407. XCTAssertTrue([allSignInMethods isKindOfClass:[NSArray class]]);
  408. XCTAssertNil(error);
  409. [expectation fulfill];
  410. }];
  411. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  412. OCMVerifyAll(_mockBackend);
  413. }
  414. /** @fn testFetchSignInMethodsForEmailFailure
  415. @brief Tests the flow of a failed @c fetchSignInMethodsForEmail:completion: call.
  416. */
  417. - (void)testFetchSignInMethodsForEmailFailure {
  418. OCMExpect([_mockBackend createAuthURI:[OCMArg any] callback:[OCMArg any]])
  419. .andDispatchError2([FIRAuthErrorUtils tooManyRequestsErrorWithMessage:nil]);
  420. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  421. [[FIRAuth auth] fetchSignInMethodsForEmail:kEmail
  422. completion:^(NSArray<NSString *> *_Nullable signInMethods,
  423. NSError *_Nullable error) {
  424. XCTAssertTrue([NSThread isMainThread]);
  425. XCTAssertNil(signInMethods);
  426. XCTAssertEqual(error.code, FIRAuthErrorCodeTooManyRequests);
  427. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  428. [expectation fulfill];
  429. }];
  430. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  431. OCMVerifyAll(_mockBackend);
  432. }
  433. #if TARGET_OS_IOS
  434. /** @fn testPhoneAuthSuccess
  435. @brief Tests the flow of a successful @c signInWithCredential:completion for phone auth.
  436. */
  437. - (void)testPhoneAuthSuccess {
  438. OCMExpect([_mockBackend verifyPhoneNumber:[OCMArg any] callback:[OCMArg any]])
  439. .andCallBlock2(^(FIRVerifyPhoneNumberRequest *_Nullable request,
  440. FIRVerifyPhoneNumberResponseCallback callback) {
  441. XCTAssertEqualObjects(request.verificationCode, kVerificationCode);
  442. XCTAssertEqualObjects(request.verificationID, kVerificationID);
  443. XCTAssertEqual(request.operation, FIRAuthOperationTypeSignUpOrSignIn);
  444. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  445. id mockVerifyPhoneResponse = OCMClassMock([FIRVerifyPhoneNumberResponse class]);
  446. [self stubTokensWithMockResponse:mockVerifyPhoneResponse];
  447. // Stub isNewUser flag in the response.
  448. OCMStub([mockVerifyPhoneResponse isNewUser]).andReturn(YES);
  449. callback(mockVerifyPhoneResponse, nil);
  450. });
  451. });
  452. [self expectGetAccountInfo];
  453. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  454. [[FIRAuth auth] signOut:NULL];
  455. FIRAuthCredential *credential =
  456. [[FIRPhoneAuthProvider provider] credentialWithVerificationID:kVerificationID
  457. verificationCode:kVerificationCode];
  458. [[FIRAuth auth] signInWithCredential:credential
  459. completion:^(FIRAuthDataResult *_Nullable authDataResult,
  460. NSError *_Nullable error) {
  461. XCTAssertTrue([NSThread isMainThread]);
  462. [self assertUser:authDataResult.user];
  463. XCTAssertTrue(authDataResult.additionalUserInfo.isNewUser);
  464. XCTAssertNil(error);
  465. [expectation fulfill];
  466. }];
  467. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  468. [self assertUser:[FIRAuth auth].currentUser];
  469. OCMVerifyAll(_mockBackend);
  470. }
  471. /** @fn testPhoneAuthMissingVerificationCode
  472. @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
  473. to an empty verification code
  474. */
  475. - (void)testPhoneAuthMissingVerificationCode {
  476. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  477. [[FIRAuth auth] signOut:NULL];
  478. FIRAuthCredential *credential =
  479. [[FIRPhoneAuthProvider provider] credentialWithVerificationID:kVerificationID
  480. verificationCode:@""];
  481. [[FIRAuth auth]
  482. signInWithCredential:credential
  483. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  484. XCTAssertTrue([NSThread isMainThread]);
  485. XCTAssertNil(result);
  486. XCTAssertEqual(error.code, FIRAuthErrorCodeMissingVerificationCode);
  487. [expectation fulfill];
  488. }];
  489. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  490. }
  491. /** @fn testPhoneAuthMissingVerificationID
  492. @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
  493. to an empty verification ID.
  494. */
  495. - (void)testPhoneAuthMissingVerificationID {
  496. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  497. [[FIRAuth auth] signOut:NULL];
  498. FIRAuthCredential *credential =
  499. [[FIRPhoneAuthProvider provider] credentialWithVerificationID:@""
  500. verificationCode:kVerificationCode];
  501. [[FIRAuth auth]
  502. signInWithCredential:credential
  503. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  504. XCTAssertTrue([NSThread isMainThread]);
  505. XCTAssertNil(result);
  506. XCTAssertEqual(error.code, FIRAuthErrorCodeMissingVerificationID);
  507. [expectation fulfill];
  508. }];
  509. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  510. }
  511. #endif
  512. /** @fn testSignInWithEmailLinkSuccess
  513. @brief Tests the flow of a successful @c signInWithEmail:link:completion: call.
  514. */
  515. - (void)testSignInWithEmailLinkSuccess {
  516. NSString *fakeCode = @"testoobcode";
  517. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  518. .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
  519. FIREmailLinkSigninResponseCallback callback) {
  520. XCTAssertEqualObjects(request.email, kEmail);
  521. XCTAssertEqualObjects(request.oobCode, fakeCode);
  522. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  523. id mockEmailLinkSignInResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
  524. [self stubTokensWithMockResponse:mockEmailLinkSignInResponse];
  525. callback(mockEmailLinkSignInResponse, nil);
  526. OCMStub([mockEmailLinkSignInResponse refreshToken]).andReturn(kRefreshToken);
  527. });
  528. });
  529. [self expectGetAccountInfo];
  530. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  531. [[FIRAuth auth] signOut:NULL];
  532. [[FIRAuth auth]
  533. signInWithEmail:kEmail
  534. link:kFakeEmailSignInlink
  535. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  536. XCTAssertTrue([NSThread isMainThread]);
  537. XCTAssertNotNil(authResult.user);
  538. XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
  539. XCTAssertFalse(authResult.user.anonymous);
  540. XCTAssertEqualObjects(authResult.user.email, kEmail);
  541. XCTAssertNil(error);
  542. [expectation fulfill];
  543. }];
  544. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  545. [self assertUser:[FIRAuth auth].currentUser];
  546. OCMVerifyAll(_mockBackend);
  547. }
  548. /** @fn testSignInWithEmailLinkSuccessDeeplink
  549. @brief Tests the flow of a successful @c signInWithEmail:link:completion: call using a deep
  550. link.
  551. */
  552. - (void)testSignInWithEmailLinkSuccessDeeplink {
  553. NSString *fakeCode = @"testoobcode";
  554. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  555. .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
  556. FIREmailLinkSigninResponseCallback callback) {
  557. XCTAssertEqualObjects(request.email, kEmail);
  558. XCTAssertEqualObjects(request.oobCode, fakeCode);
  559. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  560. id mockEmailLinkSignInResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
  561. [self stubTokensWithMockResponse:mockEmailLinkSignInResponse];
  562. callback(mockEmailLinkSignInResponse, nil);
  563. OCMStub([mockEmailLinkSignInResponse refreshToken]).andReturn(kRefreshToken);
  564. });
  565. });
  566. [self expectGetAccountInfo];
  567. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  568. [[FIRAuth auth] signOut:NULL];
  569. [[FIRAuth auth]
  570. signInWithEmail:kEmail
  571. link:kFakeEmailSignInDeeplink
  572. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  573. XCTAssertTrue([NSThread isMainThread]);
  574. XCTAssertNotNil(authResult.user);
  575. XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
  576. XCTAssertFalse(authResult.user.anonymous);
  577. XCTAssertEqualObjects(authResult.user.email, kEmail);
  578. XCTAssertNil(error);
  579. [expectation fulfill];
  580. }];
  581. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  582. [self assertUser:[FIRAuth auth].currentUser];
  583. OCMVerifyAll(_mockBackend);
  584. }
  585. /** @fn testSignInWithEmailLinkFailure
  586. @brief Tests the flow of a failed @c signInWithEmail:link:completion: call.
  587. */
  588. - (void)testSignInWithEmailLinkFailure {
  589. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  590. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  591. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  592. [[FIRAuth auth] signOut:NULL];
  593. [[FIRAuth auth]
  594. signInWithEmail:kEmail
  595. link:kFakeEmailSignInlink
  596. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  597. XCTAssertTrue([NSThread isMainThread]);
  598. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  599. [expectation fulfill];
  600. }];
  601. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  602. OCMVerifyAll(_mockBackend);
  603. }
  604. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  605. /** @fn testSignInWithEmailPasswordWithRecaptchaSuccess
  606. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  607. */
  608. - (void)testSignInWithEmailPasswordWithRecaptchaSuccess {
  609. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  610. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  611. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  612. .andReturn(YES);
  613. FIRVerifyPasswordRequest *constRequestWithRecaptchaToken =
  614. [[FIRVerifyPasswordRequest alloc] initWithEmail:kEmail
  615. password:kFakePassword
  616. requestConfiguration:[FIRAuth auth].requestConfiguration];
  617. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  618. recaptchaVersion:kFakeRecaptchaVersion];
  619. OCMStub([mockVerifier
  620. injectRecaptchaFields:[OCMArg any]
  621. provider:FIRAuthRecaptchaProviderPassword
  622. action:FIRAuthRecaptchaActionSignInWithPassword
  623. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  624. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  625. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  626. FIRVerifyPasswordResponseCallback callback) {
  627. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  628. XCTAssertEqualObjects(request.email, kEmail);
  629. XCTAssertEqualObjects(request.password, kFakePassword);
  630. XCTAssertTrue(request.returnSecureToken);
  631. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  632. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  633. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  634. callback(mockVerifyPasswordResponse, nil);
  635. });
  636. });
  637. [self expectGetAccountInfo];
  638. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  639. [[FIRAuth auth] signOut:NULL];
  640. [[FIRAuth auth] signInWithEmail:kEmail
  641. password:kFakePassword
  642. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  643. XCTAssertTrue([NSThread isMainThread]);
  644. [self assertUser:result.user];
  645. XCTAssertNil(error);
  646. [expectation fulfill];
  647. }];
  648. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  649. [self assertUser:[FIRAuth auth].currentUser];
  650. }
  651. /** @fn testSignInWithEmailPasswordWithRecaptchaFallbackSuccess
  652. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  653. */
  654. - (void)testSignInWithEmailPasswordWithRecaptchaFallbackSuccess {
  655. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  656. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  657. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  658. .andReturn(NO);
  659. FIRVerifyPasswordRequest *constRequestWithRecaptchaToken =
  660. [[FIRVerifyPasswordRequest alloc] initWithEmail:kEmail
  661. password:kFakePassword
  662. requestConfiguration:[FIRAuth auth].requestConfiguration];
  663. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  664. recaptchaVersion:kFakeRecaptchaVersion];
  665. OCMStub([mockVerifier
  666. injectRecaptchaFields:[OCMArg any]
  667. provider:FIRAuthRecaptchaProviderPassword
  668. action:FIRAuthRecaptchaActionSignInWithPassword
  669. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  670. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  671. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  672. FIRVerifyPasswordResponseCallback callback) {
  673. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  674. XCTAssertEqualObjects(request.email, kEmail);
  675. XCTAssertEqualObjects(request.password, kFakePassword);
  676. XCTAssertTrue(request.returnSecureToken);
  677. NSError *underlyingError =
  678. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  679. code:FIRAuthErrorCodeInternalError
  680. userInfo:@{
  681. FIRAuthErrorUserInfoDeserializedResponseKey :
  682. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  683. }];
  684. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  685. code:FIRAuthErrorCodeInternalError
  686. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  687. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  688. callback(nil, error);
  689. });
  690. });
  691. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  692. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  693. FIRVerifyPasswordResponseCallback callback) {
  694. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  695. XCTAssertEqualObjects(request.email, kEmail);
  696. XCTAssertEqualObjects(request.password, kFakePassword);
  697. XCTAssertTrue(request.returnSecureToken);
  698. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  699. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  700. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  701. callback(mockVerifyPasswordResponse, nil);
  702. });
  703. });
  704. [self expectGetAccountInfo];
  705. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  706. [[FIRAuth auth] signOut:NULL];
  707. [[FIRAuth auth] signInWithEmail:kEmail
  708. password:kFakePassword
  709. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  710. XCTAssertTrue([NSThread isMainThread]);
  711. [self assertUser:result.user];
  712. XCTAssertNil(error);
  713. [expectation fulfill];
  714. }];
  715. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  716. [self assertUser:[FIRAuth auth].currentUser];
  717. }
  718. #endif
  719. /** @fn testSignInWithEmailPasswordSuccess
  720. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  721. */
  722. - (void)testSignInWithEmailPasswordSuccess {
  723. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  724. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  725. FIRVerifyPasswordResponseCallback callback) {
  726. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  727. XCTAssertEqualObjects(request.email, kEmail);
  728. XCTAssertEqualObjects(request.password, kFakePassword);
  729. XCTAssertTrue(request.returnSecureToken);
  730. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  731. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  732. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  733. callback(mockVerifyPasswordResponse, nil);
  734. });
  735. });
  736. [self expectGetAccountInfo];
  737. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  738. [[FIRAuth auth] signOut:NULL];
  739. [[FIRAuth auth] signInWithEmail:kEmail
  740. password:kFakePassword
  741. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  742. XCTAssertTrue([NSThread isMainThread]);
  743. [self assertUser:result.user];
  744. XCTAssertNil(error);
  745. [expectation fulfill];
  746. }];
  747. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  748. [self assertUser:[FIRAuth auth].currentUser];
  749. OCMVerifyAll(_mockBackend);
  750. }
  751. /** @fn testSignInWithEmailPasswordFailure
  752. @brief Tests the flow of a failed @c signInWithEmail:password:completion: call.
  753. */
  754. - (void)testSignInWithEmailPasswordFailure {
  755. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  756. .andDispatchError2([FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  757. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  758. [[FIRAuth auth] signOut:NULL];
  759. [[FIRAuth auth] signInWithEmail:kEmail
  760. password:kFakePassword
  761. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  762. XCTAssertTrue([NSThread isMainThread]);
  763. XCTAssertNil(result.user);
  764. XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
  765. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  766. [expectation fulfill];
  767. }];
  768. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  769. XCTAssertNil([FIRAuth auth].currentUser);
  770. OCMVerifyAll(_mockBackend);
  771. }
  772. /** @fn testSignInAndRetrieveDataWithEmailPasswordSuccess
  773. @brief Tests the flow of a successful @c signInAndRetrieveDataWithEmail:password:completion:
  774. call.
  775. */
  776. - (void)testSignInAndRetrieveDataWithEmailPasswordSuccess {
  777. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  778. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  779. FIRVerifyPasswordResponseCallback callback) {
  780. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  781. XCTAssertEqualObjects(request.email, kEmail);
  782. XCTAssertEqualObjects(request.password, kFakePassword);
  783. XCTAssertTrue(request.returnSecureToken);
  784. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  785. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  786. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  787. callback(mockVerifyPasswordResponse, nil);
  788. });
  789. });
  790. [self expectGetAccountInfo];
  791. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  792. [[FIRAuth auth] signOut:NULL];
  793. [[FIRAuth auth]
  794. signInWithEmail:kEmail
  795. password:kFakePassword
  796. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  797. XCTAssertTrue([NSThread isMainThread]);
  798. [self assertUser:result.user];
  799. XCTAssertFalse(result.additionalUserInfo.isNewUser);
  800. XCTAssertEqualObjects(result.additionalUserInfo.providerID, FIREmailAuthProviderID);
  801. XCTAssertNil(error);
  802. [expectation fulfill];
  803. }];
  804. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  805. [self assertUser:[FIRAuth auth].currentUser];
  806. OCMVerifyAll(_mockBackend);
  807. }
  808. /** @fn testSignInAndRetrieveDataWithEmailPasswordFailure
  809. @brief Tests the flow of a failed @c signInAndRetrieveDataWithEmail:password:completion: call.
  810. */
  811. - (void)testSignInAndRetrieveDataWithEmailPasswordFailure {
  812. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  813. .andDispatchError2([FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  814. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  815. [[FIRAuth auth] signOut:NULL];
  816. [[FIRAuth auth] signInWithEmail:kEmail
  817. password:kFakePassword
  818. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  819. XCTAssertTrue([NSThread isMainThread]);
  820. XCTAssertNil(result);
  821. XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
  822. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  823. [expectation fulfill];
  824. }];
  825. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  826. XCTAssertNil([FIRAuth auth].currentUser);
  827. OCMVerifyAll(_mockBackend);
  828. }
  829. /** @fn testResetPasswordSuccess
  830. @brief Tests the flow of a successful @c confirmPasswordResetWithCode:newPassword:completion:
  831. call.
  832. */
  833. - (void)testResetPasswordSuccess {
  834. NSString *fakeEmail = @"fakeEmail";
  835. NSString *fakeCode = @"fakeCode";
  836. NSString *fakeNewPassword = @"fakeNewPassword";
  837. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  838. .andCallBlock2(
  839. ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
  840. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  841. XCTAssertEqualObjects(request.oobCode, fakeCode);
  842. XCTAssertEqualObjects(request.updatedPassword, fakeNewPassword);
  843. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  844. id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
  845. OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
  846. callback(mockResetPasswordResponse, nil);
  847. });
  848. });
  849. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  850. [[FIRAuth auth] signOut:NULL];
  851. [[FIRAuth auth] confirmPasswordResetWithCode:fakeCode
  852. newPassword:fakeNewPassword
  853. completion:^(NSError *_Nullable error) {
  854. XCTAssertTrue([NSThread isMainThread]);
  855. XCTAssertNil(error);
  856. [expectation fulfill];
  857. }];
  858. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  859. OCMVerifyAll(_mockBackend);
  860. }
  861. /** @fn testResetPasswordFailure
  862. @brief Tests the flow of a failed @c confirmPasswordResetWithCode:newPassword:completion:
  863. call.
  864. */
  865. - (void)testResetPasswordFailure {
  866. NSString *fakeCode = @"fakeCode";
  867. NSString *fakeNewPassword = @"fakeNewPassword";
  868. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  869. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  870. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  871. [[FIRAuth auth] signOut:NULL];
  872. [[FIRAuth auth] confirmPasswordResetWithCode:fakeCode
  873. newPassword:fakeNewPassword
  874. completion:^(NSError *_Nullable error) {
  875. XCTAssertTrue([NSThread isMainThread]);
  876. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  877. [expectation fulfill];
  878. }];
  879. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  880. OCMVerifyAll(_mockBackend);
  881. }
  882. /** @fn testCheckActionCodeSuccess
  883. @brief Tests the flow of a successful @c checkActionCode:completion call.
  884. */
  885. - (void)testCheckActionCodeSuccess {
  886. NSString *verifyEmailRequestType = @"VERIFY_EMAIL";
  887. NSString *fakeEmail = @"fakeEmail";
  888. NSString *fakeNewEmail = @"fakeNewEmail";
  889. NSString *fakeCode = @"fakeCode";
  890. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  891. .andCallBlock2(
  892. ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
  893. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  894. XCTAssertEqualObjects(request.oobCode, fakeCode);
  895. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  896. id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
  897. OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
  898. OCMStub([mockResetPasswordResponse verifiedEmail]).andReturn(fakeNewEmail);
  899. OCMStubRecorder *stub =
  900. OCMStub([(FIRResetPasswordResponse *)mockResetPasswordResponse requestType]);
  901. stub.andReturn(verifyEmailRequestType);
  902. callback(mockResetPasswordResponse, nil);
  903. });
  904. });
  905. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  906. [[FIRAuth auth] checkActionCode:fakeCode
  907. completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
  908. XCTAssertTrue([NSThread isMainThread]);
  909. XCTAssertNil(error);
  910. XCTAssertEqual(info.operation, FIRActionCodeOperationVerifyEmail);
  911. XCTAssert([fakeNewEmail isEqualToString:info.email]);
  912. [expectation fulfill];
  913. }];
  914. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  915. OCMVerifyAll(_mockBackend);
  916. }
  917. /** @fn testCheckActionCodeFailure
  918. @brief Tests the flow of a failed @c checkActionCode:completion call.
  919. */
  920. - (void)testCheckActionCodeFailure {
  921. NSString *fakeCode = @"fakeCode";
  922. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  923. ._andDispatchError2([FIRAuthErrorUtils expiredActionCodeErrorWithMessage:nil]);
  924. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  925. [[FIRAuth auth] signOut:NULL];
  926. [[FIRAuth auth] checkActionCode:fakeCode
  927. completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
  928. XCTAssertTrue([NSThread isMainThread]);
  929. XCTAssertNotNil(error);
  930. XCTAssertEqual(error.code, FIRAuthErrorCodeExpiredActionCode);
  931. [expectation fulfill];
  932. }];
  933. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  934. OCMVerifyAll(_mockBackend);
  935. }
  936. /** @fn testApplyActionCodeSuccess
  937. @brief Tests the flow of a successful @c applyActionCode:completion call.
  938. */
  939. - (void)testApplyActionCodeSuccess {
  940. NSString *fakeCode = @"fakeCode";
  941. OCMExpect([_mockBackend setAccountInfo:[OCMArg any] callback:[OCMArg any]])
  942. .andCallBlock2(^(FIRSetAccountInfoRequest *_Nullable request,
  943. FIRSetAccountInfoResponseCallback callback) {
  944. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  945. XCTAssertEqualObjects(request.OOBCode, fakeCode);
  946. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  947. id mockSetAccountInfoResponse = OCMClassMock([FIRSetAccountInfoResponse class]);
  948. callback(mockSetAccountInfoResponse, nil);
  949. });
  950. });
  951. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  952. [[FIRAuth auth] applyActionCode:fakeCode
  953. completion:^(NSError *_Nullable error) {
  954. XCTAssertTrue([NSThread isMainThread]);
  955. XCTAssertNil(error);
  956. [expectation fulfill];
  957. }];
  958. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  959. OCMVerifyAll(_mockBackend);
  960. }
  961. /** @fn testApplyActionCodeFailure
  962. @brief Tests the flow of a failed @c checkActionCode:completion call.
  963. */
  964. - (void)testApplyActionCodeFailure {
  965. NSString *fakeCode = @"fakeCode";
  966. OCMExpect([_mockBackend setAccountInfo:[OCMArg any] callback:[OCMArg any]])
  967. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  968. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  969. [[FIRAuth auth] signOut:NULL];
  970. [[FIRAuth auth] applyActionCode:fakeCode
  971. completion:^(NSError *_Nullable error) {
  972. XCTAssertTrue([NSThread isMainThread]);
  973. XCTAssertNotNil(error);
  974. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  975. [expectation fulfill];
  976. }];
  977. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  978. OCMVerifyAll(_mockBackend);
  979. }
  980. /** @fn testVerifyPasswordResetCodeSuccess
  981. @brief Tests the flow of a successful @c verifyPasswordResetCode:completion call.
  982. */
  983. - (void)testVerifyPasswordResetCodeSuccess {
  984. NSString *passwordResetRequestType = @"PASSWORD_RESET";
  985. NSString *fakeEmail = @"fakeEmail";
  986. NSString *fakeCode = @"fakeCode";
  987. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  988. .andCallBlock2(
  989. ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
  990. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  991. XCTAssertEqualObjects(request.oobCode, fakeCode);
  992. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  993. id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
  994. OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
  995. OCMStubRecorder *stub =
  996. OCMStub([(FIRResetPasswordResponse *)mockResetPasswordResponse requestType]);
  997. stub.andReturn(passwordResetRequestType);
  998. callback(mockResetPasswordResponse, nil);
  999. });
  1000. });
  1001. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1002. [[FIRAuth auth] verifyPasswordResetCode:fakeCode
  1003. completion:^(NSString *_Nullable email, NSError *_Nullable error) {
  1004. XCTAssertTrue([NSThread isMainThread]);
  1005. XCTAssertNil(error);
  1006. XCTAssertEqual(email, fakeEmail);
  1007. [expectation fulfill];
  1008. }];
  1009. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1010. OCMVerifyAll(_mockBackend);
  1011. }
  1012. /** @fn testVerifyPasswordResetCodeFailure
  1013. @brief Tests the flow of a failed @c verifyPasswordResetCode:completion call.
  1014. */
  1015. - (void)testVeridyPasswordResetCodeFailure {
  1016. NSString *fakeCode = @"fakeCode";
  1017. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  1018. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  1019. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1020. [[FIRAuth auth] signOut:NULL];
  1021. [[FIRAuth auth] verifyPasswordResetCode:fakeCode
  1022. completion:^(NSString *_Nullable email, NSError *_Nullable error) {
  1023. XCTAssertTrue([NSThread isMainThread]);
  1024. XCTAssertNotNil(error);
  1025. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  1026. [expectation fulfill];
  1027. }];
  1028. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1029. OCMVerifyAll(_mockBackend);
  1030. }
  1031. /** @fn testSignInWithEmailLinkCredentialSuccess
  1032. @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
  1033. email sign-in link credential using FIREmailAuthProvider.
  1034. */
  1035. - (void)testSignInWithEmailLinkCredentialSuccess {
  1036. NSString *fakeCode = @"testoobcode";
  1037. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  1038. .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
  1039. FIREmailLinkSigninResponseCallback callback) {
  1040. XCTAssertEqualObjects(request.email, kEmail);
  1041. XCTAssertEqualObjects(request.oobCode, fakeCode);
  1042. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1043. id mockEmailLinkSigninResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
  1044. [self stubTokensWithMockResponse:mockEmailLinkSigninResponse];
  1045. callback(mockEmailLinkSigninResponse, nil);
  1046. });
  1047. });
  1048. [self expectGetAccountInfo];
  1049. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1050. [[FIRAuth auth] signOut:NULL];
  1051. FIRAuthCredential *emailCredential =
  1052. [FIREmailAuthProvider credentialWithEmail:kEmail link:kFakeEmailSignInlink];
  1053. [[FIRAuth auth]
  1054. signInWithCredential:emailCredential
  1055. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1056. XCTAssertTrue([NSThread isMainThread]);
  1057. XCTAssertNotNil(authResult.user);
  1058. XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
  1059. XCTAssertFalse(authResult.user.anonymous);
  1060. XCTAssertEqualObjects(authResult.user.email, kEmail);
  1061. XCTAssertNil(error);
  1062. [expectation fulfill];
  1063. }];
  1064. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1065. [self assertUser:[FIRAuth auth].currentUser];
  1066. OCMVerifyAll(_mockBackend);
  1067. }
  1068. /** @fn testSignInWithEmailLinkCredentialFailure
  1069. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1070. email-email sign-in link credential using FIREmailAuthProvider.
  1071. */
  1072. - (void)testSignInWithEmailLinkCredentialFailure {
  1073. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  1074. .andDispatchError2([FIRAuthErrorUtils userDisabledErrorWithMessage:nil]);
  1075. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1076. [[FIRAuth auth] signOut:NULL];
  1077. FIRAuthCredential *emailCredential =
  1078. [FIREmailAuthProvider credentialWithEmail:kEmail link:kFakeEmailSignInlink];
  1079. [[FIRAuth auth]
  1080. signInWithCredential:emailCredential
  1081. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1082. XCTAssertTrue([NSThread isMainThread]);
  1083. XCTAssertNil(result);
  1084. XCTAssertEqual(error.code, FIRAuthErrorCodeUserDisabled);
  1085. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1086. [expectation fulfill];
  1087. }];
  1088. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1089. XCTAssertNil([FIRAuth auth].currentUser);
  1090. OCMVerifyAll(_mockBackend);
  1091. }
  1092. /** @fn testSignInWithEmailCredentialSuccess
  1093. @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
  1094. email-password credential.
  1095. */
  1096. - (void)testSignInWithEmailCredentialSuccess {
  1097. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  1098. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  1099. FIRVerifyPasswordResponseCallback callback) {
  1100. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1101. XCTAssertEqualObjects(request.email, kEmail);
  1102. XCTAssertEqualObjects(request.password, kFakePassword);
  1103. XCTAssertTrue(request.returnSecureToken);
  1104. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1105. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  1106. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  1107. callback(mockVerifyPasswordResponse, nil);
  1108. });
  1109. });
  1110. [self expectGetAccountInfo];
  1111. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1112. [[FIRAuth auth] signOut:NULL];
  1113. FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
  1114. password:kFakePassword];
  1115. [[FIRAuth auth]
  1116. signInWithCredential:emailCredential
  1117. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1118. XCTAssertTrue([NSThread isMainThread]);
  1119. [self assertUser:result.user];
  1120. XCTAssertNil(error);
  1121. [expectation fulfill];
  1122. }];
  1123. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1124. [self assertUser:[FIRAuth auth].currentUser];
  1125. OCMVerifyAll(_mockBackend);
  1126. }
  1127. /** @fn testSignInWithEmailCredentialFailure
  1128. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1129. email-password credential.
  1130. */
  1131. - (void)testSignInWithEmailCredentialFailure {
  1132. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  1133. .andDispatchError2([FIRAuthErrorUtils userDisabledErrorWithMessage:nil]);
  1134. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1135. [[FIRAuth auth] signOut:NULL];
  1136. FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
  1137. password:kFakePassword];
  1138. [[FIRAuth auth]
  1139. signInWithCredential:emailCredential
  1140. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1141. XCTAssertTrue([NSThread isMainThread]);
  1142. XCTAssertNil(result);
  1143. XCTAssertEqual(error.code, FIRAuthErrorCodeUserDisabled);
  1144. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1145. [expectation fulfill];
  1146. }];
  1147. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1148. XCTAssertNil([FIRAuth auth].currentUser);
  1149. OCMVerifyAll(_mockBackend);
  1150. }
  1151. /** @fn testSignInWithEmailCredentialEmptyPassword
  1152. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1153. email-password credential using an empty password. This error occurs on the client side,
  1154. so there is no need to fake an RPC response.
  1155. */
  1156. - (void)testSignInWithEmailCredentialEmptyPassword {
  1157. NSString *emptyString = @"";
  1158. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1159. [[FIRAuth auth] signOut:NULL];
  1160. FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
  1161. password:emptyString];
  1162. [[FIRAuth auth]
  1163. signInWithCredential:emailCredential
  1164. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1165. XCTAssertTrue([NSThread isMainThread]);
  1166. XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
  1167. [expectation fulfill];
  1168. }];
  1169. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1170. }
  1171. #if TARGET_OS_IOS
  1172. /** @fn testSignInWithProviderSuccess
  1173. @brief Tests a successful @c signInWithProvider:UIDelegate:completion: call with an OAuth
  1174. provider configured for Google.
  1175. */
  1176. - (void)testSignInWithProviderSuccess {
  1177. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1178. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1179. FIRVerifyAssertionResponseCallback callback) {
  1180. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1181. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1182. XCTAssertTrue(request.returnSecureToken);
  1183. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1184. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1185. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1186. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1187. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1188. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1189. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1190. callback(mockVerifyAssertionResponse, nil);
  1191. });
  1192. });
  1193. [self expectGetAccountInfoGoogle];
  1194. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1195. [[FIRAuth auth] signOut:NULL];
  1196. id mockProvider = OCMClassMock([FIROAuthProvider class]);
  1197. OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
  1198. .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
  1199. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1200. FIROAuthCredential *credential =
  1201. [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
  1202. sessionID:kOAuthSessionID
  1203. OAuthResponseURLString:kOAuthRequestURI];
  1204. callback(credential, nil);
  1205. });
  1206. });
  1207. [[FIRAuth auth]
  1208. signInWithProvider:mockProvider
  1209. UIDelegate:nil
  1210. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1211. XCTAssertTrue([NSThread isMainThread]);
  1212. [self assertUserGoogle:authResult.user];
  1213. XCTAssertNil(error);
  1214. [expectation fulfill];
  1215. }];
  1216. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1217. OCMVerifyAll(_mockBackend);
  1218. }
  1219. /** @fn testSignInWithProviderFailure
  1220. @brief Tests a failed @c signInWithProvider:UIDelegate:completion: call with the error code
  1221. FIRAuthErrorCodeWebSignInUserInteractionFailure.
  1222. */
  1223. - (void)testSignInWithProviderFailure {
  1224. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1225. .andDispatchError2([FIRAuthErrorUtils
  1226. webSignInUserInteractionFailureWithReason:kFakeWebSignInUserInteractionFailureReason]);
  1227. [[FIRAuth auth] signOut:NULL];
  1228. id mockProvider = OCMClassMock([FIROAuthProvider class]);
  1229. OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
  1230. .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
  1231. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1232. FIROAuthCredential *credential =
  1233. [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
  1234. sessionID:kOAuthSessionID
  1235. OAuthResponseURLString:kOAuthRequestURI];
  1236. callback(credential, nil);
  1237. });
  1238. });
  1239. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1240. [[FIRAuth auth]
  1241. signInWithProvider:mockProvider
  1242. UIDelegate:nil
  1243. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1244. XCTAssertTrue([NSThread isMainThread]);
  1245. XCTAssertNil(authResult);
  1246. XCTAssertEqual(error.code, FIRAuthErrorCodeWebSignInUserInteractionFailure);
  1247. XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey],
  1248. kFakeWebSignInUserInteractionFailureReason);
  1249. [expectation fulfill];
  1250. }];
  1251. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1252. OCMVerifyAll(_mockBackend);
  1253. }
  1254. /** @fn testSignInWithGoogleAccountExistsError
  1255. @brief Tests the flow of a failed @c signInWithCredential:completion: with a Google credential
  1256. where the backend returns a needs @needConfirmation equal to true. An
  1257. FIRAuthErrorCodeAccountExistsWithDifferentCredential error should be thrown.
  1258. */
  1259. - (void)testSignInWithGoogleAccountExistsError {
  1260. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1261. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1262. FIRVerifyAssertionResponseCallback callback) {
  1263. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1264. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1265. XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
  1266. XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
  1267. XCTAssertTrue(request.returnSecureToken);
  1268. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1269. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1270. OCMStub([mockVerifyAssertionResponse needConfirmation]).andReturn(YES);
  1271. OCMStub([mockVerifyAssertionResponse email]).andReturn(kEmail);
  1272. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1273. callback(mockVerifyAssertionResponse, nil);
  1274. });
  1275. });
  1276. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1277. [[FIRAuth auth] signOut:NULL];
  1278. FIRAuthCredential *googleCredential =
  1279. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1280. [[FIRAuth auth]
  1281. signInWithCredential:googleCredential
  1282. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1283. XCTAssertTrue([NSThread isMainThread]);
  1284. XCTAssertEqual(error.code, FIRAuthErrorCodeAccountExistsWithDifferentCredential);
  1285. XCTAssertEqualObjects(error.userInfo[FIRAuthErrorUserInfoEmailKey], kEmail);
  1286. [expectation fulfill];
  1287. }];
  1288. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1289. OCMVerifyAll(_mockBackend);
  1290. }
  1291. /** @fn testSignInWithGoogleCredentialSuccess
  1292. @brief Tests the flow of a successful @c signInWithCredential:completion: call with an
  1293. Google Sign-In credential.
  1294. */
  1295. - (void)testSignInWithGoogleCredentialSuccess {
  1296. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1297. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1298. FIRVerifyAssertionResponseCallback callback) {
  1299. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1300. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1301. XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
  1302. XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
  1303. XCTAssertTrue(request.returnSecureToken);
  1304. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1305. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1306. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1307. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1308. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1309. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1310. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1311. callback(mockVerifyAssertionResponse, nil);
  1312. });
  1313. });
  1314. [self expectGetAccountInfoGoogle];
  1315. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1316. [[FIRAuth auth] signOut:NULL];
  1317. FIRAuthCredential *googleCredential =
  1318. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1319. [[FIRAuth auth]
  1320. signInWithCredential:googleCredential
  1321. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1322. XCTAssertTrue([NSThread isMainThread]);
  1323. [self assertUserGoogle:result.user];
  1324. XCTAssertNil(error);
  1325. [expectation fulfill];
  1326. }];
  1327. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1328. [self assertUserGoogle:[FIRAuth auth].currentUser];
  1329. OCMVerifyAll(_mockBackend);
  1330. }
  1331. /** @fn testSignInWithOAuthCredentialSuccess
  1332. @brief Tests the flow of a successful @c signInWithCredential:completion: call with a generic
  1333. OAuth credential (In this case, configured for the Google IDP).
  1334. */
  1335. - (void)testSignInWithOAuthCredentialSuccess {
  1336. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1337. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1338. FIRVerifyAssertionResponseCallback callback) {
  1339. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1340. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1341. XCTAssertEqualObjects(request.requestURI, kOAuthRequestURI);
  1342. XCTAssertEqualObjects(request.sessionID, kOAuthSessionID);
  1343. XCTAssertTrue(request.returnSecureToken);
  1344. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1345. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1346. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1347. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1348. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1349. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1350. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1351. callback(mockVerifyAssertionResponse, nil);
  1352. });
  1353. });
  1354. [self expectGetAccountInfoGoogle];
  1355. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1356. [[FIRAuth auth] signOut:NULL];
  1357. id mockProvider = OCMClassMock([FIROAuthProvider class]);
  1358. OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
  1359. .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
  1360. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1361. FIROAuthCredential *credential =
  1362. [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
  1363. sessionID:kOAuthSessionID
  1364. OAuthResponseURLString:kOAuthRequestURI];
  1365. callback(credential, nil);
  1366. });
  1367. });
  1368. [mockProvider
  1369. getCredentialWithUIDelegate:nil
  1370. completion:^(FIRAuthCredential *_Nullable credential,
  1371. NSError *_Nullable error) {
  1372. XCTAssertTrue([credential isKindOfClass:[FIROAuthCredential class]]);
  1373. FIROAuthCredential *OAuthCredential = (FIROAuthCredential *)credential;
  1374. XCTAssertEqualObjects(OAuthCredential.OAuthResponseURLString,
  1375. kOAuthRequestURI);
  1376. XCTAssertEqualObjects(OAuthCredential.sessionID, kOAuthSessionID);
  1377. [[FIRAuth auth] signInWithCredential:OAuthCredential
  1378. completion:^(FIRAuthDataResult *_Nullable result,
  1379. NSError *_Nullable error) {
  1380. XCTAssertTrue([NSThread isMainThread]);
  1381. [self assertUserGoogle:result.user];
  1382. XCTAssertNil(error);
  1383. [expectation fulfill];
  1384. }];
  1385. }];
  1386. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1387. [self assertUserGoogle:[FIRAuth auth].currentUser];
  1388. OCMVerifyAll(_mockBackend);
  1389. }
  1390. #endif // TARGET_OS_IOS
  1391. /** @fn testSignInWithCredentialSuccess
  1392. @brief Tests the flow of a successful @c signInWithCredential:completion: call
  1393. with an Google Sign-In credential.
  1394. */
  1395. - (void)testSignInWithCredentialSuccess {
  1396. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1397. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1398. FIRVerifyAssertionResponseCallback callback) {
  1399. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1400. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1401. XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
  1402. XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
  1403. XCTAssertTrue(request.returnSecureToken);
  1404. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1405. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1406. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1407. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1408. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1409. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1410. OCMStub([mockVerifyAssertionResponse profile]).andReturn([[self class] googleProfile]);
  1411. OCMStub([mockVerifyAssertionResponse username]).andReturn(kDisplayName);
  1412. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1413. callback(mockVerifyAssertionResponse, nil);
  1414. });
  1415. });
  1416. [self expectGetAccountInfoGoogle];
  1417. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1418. [[FIRAuth auth] signOut:NULL];
  1419. FIRAuthCredential *googleCredential =
  1420. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1421. [[FIRAuth auth]
  1422. signInWithCredential:googleCredential
  1423. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1424. XCTAssertTrue([NSThread isMainThread]);
  1425. [self assertUserGoogle:authResult.user];
  1426. XCTAssertEqualObjects(authResult.additionalUserInfo.profile,
  1427. [[self class] googleProfile]);
  1428. XCTAssertEqualObjects(authResult.additionalUserInfo.username, kDisplayName);
  1429. XCTAssertEqualObjects(authResult.additionalUserInfo.providerID,
  1430. FIRGoogleAuthProviderID);
  1431. XCTAssertNil(error);
  1432. [expectation fulfill];
  1433. }];
  1434. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1435. [self assertUserGoogle:[FIRAuth auth].currentUser];
  1436. OCMVerifyAll(_mockBackend);
  1437. }
  1438. /** @fn testSignInWithGoogleCredentialFailure
  1439. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1440. Google Sign-In credential.
  1441. */
  1442. - (void)testSignInWithGoogleCredentialFailure {
  1443. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1444. .andDispatchError2([FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:kGoogleEmail]);
  1445. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1446. [[FIRAuth auth] signOut:NULL];
  1447. FIRAuthCredential *googleCredential =
  1448. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1449. [[FIRAuth auth]
  1450. signInWithCredential:googleCredential
  1451. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1452. XCTAssertTrue([NSThread isMainThread]);
  1453. XCTAssertNil(result.user);
  1454. XCTAssertEqual(error.code, FIRAuthErrorCodeEmailAlreadyInUse);
  1455. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1456. [expectation fulfill];
  1457. }];
  1458. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1459. XCTAssertNil([FIRAuth auth].currentUser);
  1460. OCMVerifyAll(_mockBackend);
  1461. }
  1462. /** @fn testSignInWithAppleCredentialFullNameInRequest
  1463. @brief Tests the flow of a successful @c signInWithCredential:completion: call
  1464. with an Apple Sign-In credential with a full name. This test differentiates from
  1465. @c testSignInWithCredentialSuccess only in verifying the full name.
  1466. */
  1467. - (void)testSignInWithAppleCredentialFullNameInRequestSuccess {
  1468. NSPersonNameComponents *fullName = [[NSPersonNameComponents alloc] init];
  1469. fullName.givenName = kFakeGivenName;
  1470. fullName.familyName = kFakeFamilyName;
  1471. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1472. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1473. FIRVerifyAssertionResponseCallback callback) {
  1474. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1475. XCTAssertEqualObjects(request.providerID, kAppleAuthProviderID);
  1476. XCTAssertEqualObjects(request.providerIDToken, kAppleIDToken);
  1477. // Verify that the full name is passed to the backend request.
  1478. XCTAssertEqualObjects(request.fullName, fullName);
  1479. XCTAssertTrue(request.returnSecureToken);
  1480. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1481. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1482. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(kAppleAuthProviderID);
  1483. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1484. callback(mockVerifyAssertionResponse, nil);
  1485. });
  1486. });
  1487. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  1488. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  1489. FIRGetAccountInfoResponseCallback callback) {
  1490. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1491. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  1492. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1493. id mockAppleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
  1494. OCMStub([mockAppleUserInfo providerID]).andReturn(kAppleAuthProviderID);
  1495. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  1496. OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
  1497. .andReturn((@[ mockAppleUserInfo ]));
  1498. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  1499. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  1500. mockGetAccountInfoResponseUser
  1501. ]);
  1502. callback(mockGetAccountInfoResponse, nil);
  1503. });
  1504. });
  1505. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1506. [[FIRAuth auth] signOut:NULL];
  1507. FIRAuthCredential *appleCredential = [FIROAuthProvider appleCredentialWithIDToken:kAppleIDToken
  1508. rawNonce:nil
  1509. fullName:fullName];
  1510. [[FIRAuth auth]
  1511. signInWithCredential:appleCredential
  1512. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1513. XCTAssertTrue([NSThread isMainThread]);
  1514. XCTAssertNil(error);
  1515. [expectation fulfill];
  1516. }];
  1517. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1518. XCTAssertNotNil([FIRAuth auth].currentUser);
  1519. OCMVerifyAll(_mockBackend);
  1520. }
  1521. /** @fn testSignInAnonymouslySuccess
  1522. @brief Tests the flow of a successful @c signInAnonymouslyWithCompletion: call.
  1523. */
  1524. - (void)testSignInAnonymouslySuccess {
  1525. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1526. .andCallBlock2(
  1527. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1528. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1529. XCTAssertNil(request.email);
  1530. XCTAssertNil(request.password);
  1531. XCTAssertTrue(request.returnSecureToken);
  1532. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1533. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1534. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1535. callback(mockSignUpNewUserResponse, nil);
  1536. });
  1537. });
  1538. [self expectGetAccountInfoAnonymous];
  1539. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1540. [[FIRAuth auth] signOut:NULL];
  1541. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1542. NSError *_Nullable error) {
  1543. XCTAssertTrue([NSThread isMainThread]);
  1544. [self assertUserAnonymous:result.user];
  1545. XCTAssertNil(error);
  1546. FIRAdditionalUserInfo *userInfo = result.additionalUserInfo;
  1547. XCTAssertNotNil(userInfo);
  1548. XCTAssertTrue(userInfo.isNewUser);
  1549. XCTAssertNil(userInfo.username);
  1550. XCTAssertNil(userInfo.profile);
  1551. XCTAssertNil(userInfo.providerID);
  1552. [expectation fulfill];
  1553. }];
  1554. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1555. [self assertUserAnonymous:[FIRAuth auth].currentUser];
  1556. OCMVerifyAll(_mockBackend);
  1557. }
  1558. /** @fn testSignInAnonymouslyFailure
  1559. @brief Tests the flow of a failed @c signInAnonymouslyWithCompletion: call.
  1560. */
  1561. - (void)testSignInAnonymouslyFailure {
  1562. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1563. .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
  1564. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1565. [[FIRAuth auth] signOut:NULL];
  1566. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1567. NSError *_Nullable error) {
  1568. XCTAssertTrue([NSThread isMainThread]);
  1569. XCTAssertNil(result.user);
  1570. XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
  1571. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1572. [expectation fulfill];
  1573. }];
  1574. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1575. XCTAssertNil([FIRAuth auth].currentUser);
  1576. OCMVerifyAll(_mockBackend);
  1577. }
  1578. /** @fn testSignInAnonymouslyAndRetrieveDataSuccess
  1579. @brief Tests the flow of a successful @c signInAnonymouslyAndRetrieveDataWithCompletion: call.
  1580. */
  1581. - (void)testSignInAnonymouslyAndRetrieveDataSuccess {
  1582. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1583. .andCallBlock2(
  1584. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1585. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1586. XCTAssertNil(request.email);
  1587. XCTAssertNil(request.password);
  1588. XCTAssertTrue(request.returnSecureToken);
  1589. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1590. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1591. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1592. callback(mockSignUpNewUserResponse, nil);
  1593. });
  1594. });
  1595. [self expectGetAccountInfoAnonymous];
  1596. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1597. [[FIRAuth auth] signOut:NULL];
  1598. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1599. NSError *_Nullable error) {
  1600. XCTAssertTrue([NSThread isMainThread]);
  1601. [self assertUserAnonymous:result.user];
  1602. XCTAssertNil(error);
  1603. [expectation fulfill];
  1604. }];
  1605. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1606. [self assertUserAnonymous:[FIRAuth auth].currentUser];
  1607. OCMVerifyAll(_mockBackend);
  1608. }
  1609. /** @fn testSignInAnonymouslyAndRetrieveDataFailure
  1610. @brief Tests the flow of a failed @c signInAnonymouslyAndRetrieveDataWithCompletion: call.
  1611. */
  1612. - (void)testSignInAnonymouslyAndRetrieveDataFailure {
  1613. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1614. .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
  1615. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1616. [[FIRAuth auth] signOut:NULL];
  1617. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1618. NSError *_Nullable error) {
  1619. XCTAssertTrue([NSThread isMainThread]);
  1620. XCTAssertNil(result);
  1621. XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
  1622. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1623. [expectation fulfill];
  1624. }];
  1625. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1626. XCTAssertNil([FIRAuth auth].currentUser);
  1627. OCMVerifyAll(_mockBackend);
  1628. }
  1629. /** @fn testSignInWithCustomTokenSuccess
  1630. @brief Tests the flow of a successful @c signInWithCustomToken:completion: call.
  1631. */
  1632. - (void)testSignInWithCustomTokenSuccess {
  1633. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1634. .andCallBlock2(^(FIRVerifyCustomTokenRequest *_Nullable request,
  1635. FIRVerifyCustomTokenResponseCallback callback) {
  1636. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1637. XCTAssertEqualObjects(request.token, kCustomToken);
  1638. XCTAssertTrue(request.returnSecureToken);
  1639. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1640. id mockVerifyCustomTokenResponse = OCMClassMock([FIRVerifyCustomTokenResponse class]);
  1641. [self stubTokensWithMockResponse:mockVerifyCustomTokenResponse];
  1642. callback(mockVerifyCustomTokenResponse, nil);
  1643. });
  1644. });
  1645. [self expectGetAccountInfo];
  1646. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1647. [[FIRAuth auth] signOut:NULL];
  1648. [[FIRAuth auth]
  1649. signInWithCustomToken:kCustomToken
  1650. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1651. XCTAssertTrue([NSThread isMainThread]);
  1652. [self assertUser:result.user];
  1653. XCTAssertNil(error);
  1654. [expectation fulfill];
  1655. }];
  1656. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1657. [self assertUser:[FIRAuth auth].currentUser];
  1658. OCMVerifyAll(_mockBackend);
  1659. }
  1660. /** @fn testSignInWithCustomTokenFailure
  1661. @brief Tests the flow of a failed @c signInWithCustomToken:completion: call.
  1662. */
  1663. - (void)testSignInWithCustomTokenFailure {
  1664. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1665. .andDispatchError2([FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:nil]);
  1666. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1667. [[FIRAuth auth] signOut:NULL];
  1668. [[FIRAuth auth]
  1669. signInWithCustomToken:kCustomToken
  1670. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1671. XCTAssertTrue([NSThread isMainThread]);
  1672. XCTAssertNil(result.user);
  1673. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidCustomToken);
  1674. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1675. [expectation fulfill];
  1676. }];
  1677. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1678. XCTAssertNil([FIRAuth auth].currentUser);
  1679. OCMVerifyAll(_mockBackend);
  1680. }
  1681. /** @fn testSignInAndRetrieveDataWithCustomTokenSuccess
  1682. @brief Tests the flow of a successful @c signInAndRetrieveDataWithCustomToken:completion: call.
  1683. */
  1684. - (void)testSignInAndRetrieveDataWithCustomTokenSuccess {
  1685. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1686. .andCallBlock2(^(FIRVerifyCustomTokenRequest *_Nullable request,
  1687. FIRVerifyCustomTokenResponseCallback callback) {
  1688. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1689. XCTAssertEqualObjects(request.token, kCustomToken);
  1690. XCTAssertTrue(request.returnSecureToken);
  1691. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1692. id mockVerifyCustomTokenResponse = OCMClassMock([FIRVerifyCustomTokenResponse class]);
  1693. [self stubTokensWithMockResponse:mockVerifyCustomTokenResponse];
  1694. callback(mockVerifyCustomTokenResponse, nil);
  1695. });
  1696. });
  1697. [self expectGetAccountInfo];
  1698. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1699. [[FIRAuth auth] signOut:NULL];
  1700. [[FIRAuth auth]
  1701. signInWithCustomToken:kCustomToken
  1702. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1703. XCTAssertTrue([NSThread isMainThread]);
  1704. [self assertUser:result.user];
  1705. XCTAssertFalse(result.additionalUserInfo.isNewUser);
  1706. XCTAssertNil(error);
  1707. [expectation fulfill];
  1708. }];
  1709. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1710. [self assertUser:[FIRAuth auth].currentUser];
  1711. OCMVerifyAll(_mockBackend);
  1712. }
  1713. /** @fn testSignInAndRetrieveDataWithCustomTokenFailure
  1714. @brief Tests the flow of a failed @c signInAndRetrieveDataWithCustomToken:completion: call.
  1715. */
  1716. - (void)testSignInAndRetrieveDataWithCustomTokenFailure {
  1717. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1718. .andDispatchError2([FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:nil]);
  1719. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1720. [[FIRAuth auth] signOut:NULL];
  1721. [[FIRAuth auth]
  1722. signInWithCustomToken:kCustomToken
  1723. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1724. XCTAssertTrue([NSThread isMainThread]);
  1725. XCTAssertNil(result);
  1726. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidCustomToken);
  1727. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1728. [expectation fulfill];
  1729. }];
  1730. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1731. XCTAssertNil([FIRAuth auth].currentUser);
  1732. OCMVerifyAll(_mockBackend);
  1733. }
  1734. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  1735. /** @fn testStartPasskeySignInSuccess
  1736. @brief Tests the flow of a successful @c startPasskeySignInWithCompletion: call.
  1737. */
  1738. - (void)testStartPasskeySignInSuccess {
  1739. if (@available(iOS 15.0, tvOS 16.0, macOS 12.0, *)) {
  1740. OCMExpect([_mockBackend startPasskeySignIn:[OCMArg any] callback:[OCMArg any]])
  1741. .andCallBlock2(^(FIRStartPasskeySignInRequest *_Nullable request,
  1742. FIRStartPasskeySignInResponseCallback callback) {
  1743. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1744. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1745. id mockStartPasskeySignInResponse = OCMClassMock([FIRStartPasskeySignInResponse class]);
  1746. OCMStub([mockStartPasskeySignInResponse rpID]).andReturn(kRpId);
  1747. OCMStub([mockStartPasskeySignInResponse challenge]).andReturn(kChallenge);
  1748. callback(mockStartPasskeySignInResponse, nil);
  1749. });
  1750. });
  1751. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1752. [[FIRAuth auth] signOut:NULL];
  1753. [[FIRAuth auth]
  1754. startPasskeySignInWithCompletion:^(
  1755. ASAuthorizationPlatformPublicKeyCredentialAssertionRequest *_Nullable request,
  1756. NSError *_Nullable error) {
  1757. XCTAssertNil(error);
  1758. XCTAssertEqualObjects([[request challenge] base64EncodedStringWithOptions:0], kChallenge);
  1759. ASAuthorizationPlatformPublicKeyCredentialProvider *provider =
  1760. (ASAuthorizationPlatformPublicKeyCredentialProvider *)[request provider];
  1761. XCTAssertEqualObjects([provider relyingPartyIdentifier], kRpId);
  1762. [expectation fulfill];
  1763. }];
  1764. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1765. OCMVerifyAll(_mockBackend);
  1766. }
  1767. }
  1768. /** @fn testStartPasskeySignInFailure
  1769. @brief Tests the flow of a failed @c startPasskeySignInWithCompletion: call.
  1770. */
  1771. - (void)testStartPasskeySignInFailure {
  1772. if (@available(iOS 15.0, tvOS 16.0, macOS 12.0, *)) {
  1773. OCMExpect([_mockBackend startPasskeySignIn:[OCMArg any] callback:[OCMArg any]])
  1774. .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
  1775. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1776. [[FIRAuth auth] signOut:NULL];
  1777. [[FIRAuth auth]
  1778. startPasskeySignInWithCompletion:^(
  1779. ASAuthorizationPlatformPublicKeyCredentialAssertionRequest *_Nullable request,
  1780. NSError *_Nullable error) {
  1781. XCTAssertNil(request);
  1782. XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
  1783. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1784. [expectation fulfill];
  1785. }];
  1786. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1787. OCMVerifyAll(_mockBackend);
  1788. }
  1789. }
  1790. /** @fn testFinalizePasskeySignInFailure
  1791. @brief Tests the flow of a failed @c finalizePasskeySignInWithCompletion: call.
  1792. */
  1793. - (void)testFinalizePasskeySignInFailure {
  1794. if (@available(iOS 15.0, tvOS 16.0, macOS 12.0, *)) {
  1795. OCMExpect([_mockBackend finalizePasskeySignIn:[OCMArg any] callback:[OCMArg any]])
  1796. .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
  1797. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1798. id mockPlatfromCredential =
  1799. OCMClassMock([ASAuthorizationPlatformPublicKeyCredentialAssertion class]);
  1800. OCMStub([mockPlatfromCredential credentialID])
  1801. .andReturn([[NSData alloc] initWithBase64EncodedString:kCredentialID options:0]);
  1802. OCMStub([mockPlatfromCredential rawClientDataJSON])
  1803. .andReturn([[NSData alloc] initWithBase64EncodedString:kClientDataJson options:0]);
  1804. OCMStub([mockPlatfromCredential signature])
  1805. .andReturn([[NSData alloc] initWithBase64EncodedString:kSignature options:0]);
  1806. OCMStub([mockPlatfromCredential userID])
  1807. .andReturn([[NSData alloc] initWithBase64EncodedString:kUserID options:0]);
  1808. OCMStub([mockPlatfromCredential rawAuthenticatorData])
  1809. .andReturn([[NSData alloc] initWithBase64EncodedString:kAuthenticatorData options:0]);
  1810. [[FIRAuth auth] signOut:NULL];
  1811. [[FIRAuth auth]
  1812. finalizePasskeySignInWithPlatformCredential:mockPlatfromCredential
  1813. completion:^(FIRAuthDataResult *_Nullable authResult,
  1814. NSError *_Nullable error) {
  1815. XCTAssertTrue([NSThread isMainThread]);
  1816. XCTAssertNil(authResult.user);
  1817. XCTAssertEqual(error.code,
  1818. FIRAuthErrorCodeOperationNotAllowed);
  1819. XCTAssertNotNil(
  1820. error.userInfo[NSLocalizedDescriptionKey]);
  1821. [expectation fulfill];
  1822. }];
  1823. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1824. OCMVerifyAll(_mockBackend);
  1825. }
  1826. }
  1827. #endif // #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  1828. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1829. /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess
  1830. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1831. */
  1832. - (void)testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess {
  1833. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  1834. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  1835. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  1836. .andReturn(YES);
  1837. FIRSignUpNewUserRequest *constRequestWithRecaptchaToken =
  1838. [[FIRSignUpNewUserRequest alloc] initWithEmail:kEmail
  1839. password:kFakePassword
  1840. displayName:kDisplayName
  1841. requestConfiguration:[FIRAuth auth].requestConfiguration];
  1842. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  1843. recaptchaVersion:kFakeRecaptchaVersion];
  1844. OCMStub([mockVerifier
  1845. injectRecaptchaFields:[OCMArg any]
  1846. provider:FIRAuthRecaptchaProviderPassword
  1847. action:FIRAuthRecaptchaActionSignUpPassword
  1848. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  1849. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1850. .andCallBlock2(
  1851. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1852. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1853. XCTAssertEqualObjects(request.email, kEmail);
  1854. XCTAssertEqualObjects(request.password, kFakePassword);
  1855. XCTAssertTrue(request.returnSecureToken);
  1856. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1857. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1858. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1859. callback(mockSignUpNewUserResponse, nil);
  1860. });
  1861. });
  1862. [self expectGetAccountInfo];
  1863. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1864. [[FIRAuth auth] signOut:NULL];
  1865. [[FIRAuth auth]
  1866. createUserWithEmail:kEmail
  1867. password:kFakePassword
  1868. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1869. XCTAssertTrue([NSThread isMainThread]);
  1870. [self assertUser:result.user];
  1871. XCTAssertNil(error);
  1872. [expectation fulfill];
  1873. }];
  1874. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1875. [self assertUser:[FIRAuth auth].currentUser];
  1876. }
  1877. /** @fn testCreateUserWithEmailPasswordWithRecaptchaFallbackSuccess
  1878. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1879. */
  1880. - (void)testCreateUserWithEmailPasswordWithRecaptchaFallbackSuccess {
  1881. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  1882. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  1883. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  1884. .andReturn(NO);
  1885. FIRSignUpNewUserRequest *constRequestWithRecaptchaToken =
  1886. [[FIRSignUpNewUserRequest alloc] initWithEmail:kEmail
  1887. password:kFakePassword
  1888. displayName:kDisplayName
  1889. requestConfiguration:[FIRAuth auth].requestConfiguration];
  1890. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  1891. recaptchaVersion:kFakeRecaptchaVersion];
  1892. OCMStub([mockVerifier
  1893. injectRecaptchaFields:[OCMArg any]
  1894. provider:FIRAuthRecaptchaProviderPassword
  1895. action:FIRAuthRecaptchaActionSignUpPassword
  1896. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  1897. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1898. .andCallBlock2(^(FIRSignUpNewUserRequest *_Nullable request,
  1899. FIRSignupNewUserCallback callback) {
  1900. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1901. XCTAssertEqualObjects(request.email, kEmail);
  1902. XCTAssertEqualObjects(request.password, kFakePassword);
  1903. XCTAssertTrue(request.returnSecureToken);
  1904. NSError *underlyingError =
  1905. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  1906. code:FIRAuthErrorCodeInternalError
  1907. userInfo:@{
  1908. FIRAuthErrorUserInfoDeserializedResponseKey :
  1909. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  1910. }];
  1911. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  1912. code:FIRAuthErrorCodeInternalError
  1913. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  1914. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1915. callback(nil, error);
  1916. });
  1917. });
  1918. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1919. .andCallBlock2(
  1920. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1921. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1922. XCTAssertEqualObjects(request.email, kEmail);
  1923. XCTAssertEqualObjects(request.password, kFakePassword);
  1924. XCTAssertTrue(request.returnSecureToken);
  1925. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1926. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1927. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1928. callback(mockSignUpNewUserResponse, nil);
  1929. });
  1930. });
  1931. [self expectGetAccountInfo];
  1932. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1933. [[FIRAuth auth] signOut:NULL];
  1934. [[FIRAuth auth]
  1935. createUserWithEmail:kEmail
  1936. password:kFakePassword
  1937. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1938. XCTAssertTrue([NSThread isMainThread]);
  1939. [self assertUser:result.user];
  1940. XCTAssertNil(error);
  1941. [expectation fulfill];
  1942. }];
  1943. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1944. [self assertUser:[FIRAuth auth].currentUser];
  1945. }
  1946. #endif
  1947. /** @fn testCreateUserWithEmailPasswordSuccess
  1948. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1949. */
  1950. - (void)testCreateUserWithEmailPasswordSuccess {
  1951. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1952. .andCallBlock2(
  1953. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1954. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1955. XCTAssertEqualObjects(request.email, kEmail);
  1956. XCTAssertEqualObjects(request.password, kFakePassword);
  1957. XCTAssertTrue(request.returnSecureToken);
  1958. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1959. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1960. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1961. callback(mockSignUpNewUserResponse, nil);
  1962. });
  1963. });
  1964. [self expectGetAccountInfo];
  1965. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1966. [[FIRAuth auth] signOut:NULL];
  1967. [[FIRAuth auth]
  1968. createUserWithEmail:kEmail
  1969. password:kFakePassword
  1970. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1971. XCTAssertTrue([NSThread isMainThread]);
  1972. [self assertUser:result.user];
  1973. XCTAssertNil(error);
  1974. [expectation fulfill];
  1975. }];
  1976. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1977. [self assertUser:[FIRAuth auth].currentUser];
  1978. OCMVerifyAll(_mockBackend);
  1979. }
  1980. /** @fn testCreateUserWithEmailPasswordFailure
  1981. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call.
  1982. */
  1983. - (void)testCreateUserWithEmailPasswordFailure {
  1984. NSString *reason = @"Password shouldn't be a common word.";
  1985. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1986. .andDispatchError2([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:reason]);
  1987. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1988. [[FIRAuth auth] signOut:NULL];
  1989. [[FIRAuth auth]
  1990. createUserWithEmail:kEmail
  1991. password:kFakePassword
  1992. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1993. XCTAssertTrue([NSThread isMainThread]);
  1994. XCTAssertNil(result.user);
  1995. XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
  1996. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1997. XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey], reason);
  1998. [expectation fulfill];
  1999. }];
  2000. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2001. XCTAssertNil([FIRAuth auth].currentUser);
  2002. OCMVerifyAll(_mockBackend);
  2003. }
  2004. /** @fn testCreateUserAndRetrieveDataWithEmailPasswordSuccess
  2005. @brief Tests the flow of a successful @c createUserAndRetrieveDataWithEmail:password:completion:
  2006. call.
  2007. */
  2008. - (void)testCreateUserAndRetrieveDataWithEmailPasswordSuccess {
  2009. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  2010. .andCallBlock2(
  2011. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  2012. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2013. XCTAssertEqualObjects(request.email, kEmail);
  2014. XCTAssertEqualObjects(request.password, kFakePassword);
  2015. XCTAssertTrue(request.returnSecureToken);
  2016. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2017. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  2018. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  2019. callback(mockSignUpNewUserResponse, nil);
  2020. });
  2021. });
  2022. [self expectGetAccountInfo];
  2023. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2024. [[FIRAuth auth] signOut:NULL];
  2025. [[FIRAuth auth]
  2026. createUserWithEmail:kEmail
  2027. password:kFakePassword
  2028. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  2029. XCTAssertTrue([NSThread isMainThread]);
  2030. [self assertUser:result.user];
  2031. XCTAssertTrue(result.additionalUserInfo.isNewUser);
  2032. XCTAssertNil(error);
  2033. [expectation fulfill];
  2034. }];
  2035. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2036. [self assertUser:[FIRAuth auth].currentUser];
  2037. OCMVerifyAll(_mockBackend);
  2038. }
  2039. /** @fn testCreateUserAndRetrieveDataWithEmailPasswordFailure
  2040. @brief Tests the flow of a failed @c createUserAndRetrieveDataWithEmail:password:completion:
  2041. call.
  2042. */
  2043. - (void)testCreateUserAndRetrieveDataWithEmailPasswordFailure {
  2044. NSString *reason = @"Password shouldn't be a common word.";
  2045. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  2046. .andDispatchError2([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:reason]);
  2047. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2048. [[FIRAuth auth] signOut:NULL];
  2049. [[FIRAuth auth]
  2050. createUserWithEmail:kEmail
  2051. password:kFakePassword
  2052. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  2053. XCTAssertTrue([NSThread isMainThread]);
  2054. XCTAssertNil(result);
  2055. XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
  2056. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  2057. XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey], reason);
  2058. [expectation fulfill];
  2059. }];
  2060. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2061. XCTAssertNil([FIRAuth auth].currentUser);
  2062. OCMVerifyAll(_mockBackend);
  2063. }
  2064. /** @fn testCreateUserEmptyPasswordFailure
  2065. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
  2066. empty password. This error occurs on the client side, so there is no need to fake an RPC
  2067. response.
  2068. */
  2069. - (void)testCreateUserEmptyPasswordFailure {
  2070. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2071. [[FIRAuth auth] signOut:NULL];
  2072. [[FIRAuth auth]
  2073. createUserWithEmail:kEmail
  2074. password:@""
  2075. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  2076. XCTAssertTrue([NSThread isMainThread]);
  2077. XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
  2078. [expectation fulfill];
  2079. }];
  2080. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2081. }
  2082. /** @fn testCreateUserEmptyEmailFailure
  2083. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
  2084. empty email adress. This error occurs on the client side, so there is no need to fake an RPC
  2085. response.
  2086. */
  2087. - (void)testCreateUserEmptyEmailFailure {
  2088. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2089. [[FIRAuth auth] signOut:NULL];
  2090. [[FIRAuth auth]
  2091. createUserWithEmail:@""
  2092. password:kFakePassword
  2093. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  2094. XCTAssertTrue([NSThread isMainThread]);
  2095. XCTAssertEqual(error.code, FIRAuthErrorCodeMissingEmail);
  2096. [expectation fulfill];
  2097. }];
  2098. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2099. }
  2100. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  2101. /** @fn testSendPasswordResetEmailWithRecaptchaSuccess
  2102. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  2103. */
  2104. - (void)testSendPasswordResetEmailWithRecaptchaSuccess {
  2105. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2106. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2107. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2108. .andReturn(YES);
  2109. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2110. [FIRGetOOBConfirmationCodeRequest
  2111. passwordResetRequestWithEmail:kEmail
  2112. actionCodeSettings:nil
  2113. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2114. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2115. recaptchaVersion:kFakeRecaptchaVersion];
  2116. OCMStub([mockVerifier
  2117. injectRecaptchaFields:[OCMArg any]
  2118. provider:FIRAuthRecaptchaProviderPassword
  2119. action:FIRAuthRecaptchaActionGetOobCode
  2120. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2121. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2122. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2123. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2124. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2125. XCTAssertEqualObjects(request.email, kEmail);
  2126. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2127. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2128. });
  2129. });
  2130. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2131. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2132. completion:^(NSError *_Nullable error) {
  2133. XCTAssertTrue([NSThread isMainThread]);
  2134. XCTAssertNil(error);
  2135. [expectation fulfill];
  2136. }];
  2137. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2138. }
  2139. /** @fn testSendPasswordResetEmailWithRecaptchaFallbackSuccess
  2140. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  2141. */
  2142. - (void)testSendPasswordResetEmailWithRecaptchaFallbackSuccess {
  2143. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2144. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2145. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2146. .andReturn(NO);
  2147. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2148. [FIRGetOOBConfirmationCodeRequest
  2149. passwordResetRequestWithEmail:kEmail
  2150. actionCodeSettings:nil
  2151. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2152. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2153. recaptchaVersion:kFakeRecaptchaVersion];
  2154. OCMStub([mockVerifier
  2155. injectRecaptchaFields:[OCMArg any]
  2156. provider:FIRAuthRecaptchaProviderPassword
  2157. action:FIRAuthRecaptchaActionGetOobCode
  2158. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2159. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2160. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2161. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2162. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2163. XCTAssertEqualObjects(request.email, kEmail);
  2164. NSError *underlyingError =
  2165. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2166. code:FIRAuthErrorCodeInternalError
  2167. userInfo:@{
  2168. FIRAuthErrorUserInfoDeserializedResponseKey :
  2169. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  2170. }];
  2171. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2172. code:FIRAuthErrorCodeInternalError
  2173. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  2174. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2175. callback(nil, error);
  2176. });
  2177. });
  2178. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2179. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2180. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2181. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2182. XCTAssertEqualObjects(request.email, kEmail);
  2183. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2184. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2185. });
  2186. });
  2187. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2188. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2189. completion:^(NSError *_Nullable error) {
  2190. XCTAssertTrue([NSThread isMainThread]);
  2191. XCTAssertNil(error);
  2192. [expectation fulfill];
  2193. }];
  2194. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2195. }
  2196. #endif
  2197. /** @fn testSendPasswordResetEmailSuccess
  2198. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  2199. */
  2200. - (void)testSendPasswordResetEmailSuccess {
  2201. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2202. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2203. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2204. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2205. XCTAssertEqualObjects(request.email, kEmail);
  2206. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2207. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2208. });
  2209. });
  2210. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2211. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2212. completion:^(NSError *_Nullable error) {
  2213. XCTAssertTrue([NSThread isMainThread]);
  2214. XCTAssertNil(error);
  2215. [expectation fulfill];
  2216. }];
  2217. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2218. OCMVerifyAll(_mockBackend);
  2219. }
  2220. /** @fn testSendPasswordResetEmailFailure
  2221. @brief Tests the flow of a failed @c sendPasswordResetWithEmail:completion: call.
  2222. */
  2223. - (void)testSendPasswordResetEmailFailure {
  2224. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2225. .andDispatchError2([FIRAuthErrorUtils appNotAuthorizedError]);
  2226. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2227. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2228. completion:^(NSError *_Nullable error) {
  2229. XCTAssertTrue([NSThread isMainThread]);
  2230. XCTAssertEqual(error.code, FIRAuthErrorCodeAppNotAuthorized);
  2231. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  2232. [expectation fulfill];
  2233. }];
  2234. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2235. OCMVerifyAll(_mockBackend);
  2236. }
  2237. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  2238. /** @fn testSendSignInLinkToEmailWithRecaptchaSuccess
  2239. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2240. call.
  2241. */
  2242. - (void)testSendSignInLinkToEmailWithRecaptchaSuccess {
  2243. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2244. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2245. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2246. .andReturn(YES);
  2247. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2248. [FIRGetOOBConfirmationCodeRequest
  2249. signInWithEmailLinkRequest:kEmail
  2250. actionCodeSettings:[self fakeActionCodeSettings]
  2251. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2252. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2253. recaptchaVersion:kFakeRecaptchaVersion];
  2254. OCMStub([mockVerifier
  2255. injectRecaptchaFields:[OCMArg any]
  2256. provider:FIRAuthRecaptchaProviderPassword
  2257. action:FIRAuthRecaptchaActionGetOobCode
  2258. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2259. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2260. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2261. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2262. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2263. XCTAssertEqualObjects(request.email, kEmail);
  2264. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2265. XCTAssertTrue(request.handleCodeInApp);
  2266. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2267. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2268. });
  2269. });
  2270. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2271. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2272. actionCodeSettings:[self fakeActionCodeSettings]
  2273. completion:^(NSError *_Nullable error) {
  2274. XCTAssertTrue([NSThread isMainThread]);
  2275. XCTAssertNil(error);
  2276. [expectation fulfill];
  2277. }];
  2278. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2279. }
  2280. /** @fn testSendSignInLinkToEmailWithRecaptchaFallbackSuccess
  2281. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2282. call.
  2283. */
  2284. - (void)testSendSignInLinkToEmailWithRecaptchaFallbackSuccess {
  2285. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2286. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2287. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2288. .andReturn(NO);
  2289. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2290. [FIRGetOOBConfirmationCodeRequest
  2291. signInWithEmailLinkRequest:kEmail
  2292. actionCodeSettings:[self fakeActionCodeSettings]
  2293. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2294. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2295. recaptchaVersion:kFakeRecaptchaVersion];
  2296. OCMStub([mockVerifier
  2297. injectRecaptchaFields:[OCMArg any]
  2298. provider:FIRAuthRecaptchaProviderPassword
  2299. action:FIRAuthRecaptchaActionGetOobCode
  2300. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2301. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2302. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2303. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2304. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2305. XCTAssertEqualObjects(request.email, kEmail);
  2306. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2307. XCTAssertTrue(request.handleCodeInApp);
  2308. NSError *underlyingError =
  2309. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2310. code:FIRAuthErrorCodeInternalError
  2311. userInfo:@{
  2312. FIRAuthErrorUserInfoDeserializedResponseKey :
  2313. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  2314. }];
  2315. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2316. code:FIRAuthErrorCodeInternalError
  2317. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  2318. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2319. callback(nil, error);
  2320. });
  2321. });
  2322. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2323. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2324. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2325. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2326. XCTAssertEqualObjects(request.email, kEmail);
  2327. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2328. XCTAssertTrue(request.handleCodeInApp);
  2329. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2330. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2331. });
  2332. });
  2333. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2334. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2335. actionCodeSettings:[self fakeActionCodeSettings]
  2336. completion:^(NSError *_Nullable error) {
  2337. XCTAssertTrue([NSThread isMainThread]);
  2338. XCTAssertNil(error);
  2339. [expectation fulfill];
  2340. }];
  2341. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2342. }
  2343. #endif
  2344. /** @fn testSendSignInLinkToEmailSuccess
  2345. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2346. call.
  2347. */
  2348. - (void)testSendSignInLinkToEmailSuccess {
  2349. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2350. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2351. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2352. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2353. XCTAssertEqualObjects(request.email, kEmail);
  2354. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2355. XCTAssertTrue(request.handleCodeInApp);
  2356. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2357. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2358. });
  2359. });
  2360. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2361. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2362. actionCodeSettings:[self fakeActionCodeSettings]
  2363. completion:^(NSError *_Nullable error) {
  2364. XCTAssertTrue([NSThread isMainThread]);
  2365. XCTAssertNil(error);
  2366. [expectation fulfill];
  2367. }];
  2368. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2369. OCMVerifyAll(_mockBackend);
  2370. }
  2371. /** @fn testSendSignInLinkToEmailFailure
  2372. @brief Tests the flow of a failed @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2373. call.
  2374. */
  2375. - (void)testSendSignInLinkToEmailFailure {
  2376. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2377. .andDispatchError2([FIRAuthErrorUtils appNotAuthorizedError]);
  2378. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2379. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2380. actionCodeSettings:[self fakeActionCodeSettings]
  2381. completion:^(NSError *_Nullable error) {
  2382. XCTAssertTrue([NSThread isMainThread]);
  2383. XCTAssertEqual(error.code, FIRAuthErrorCodeAppNotAuthorized);
  2384. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  2385. [expectation fulfill];
  2386. }];
  2387. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2388. OCMVerifyAll(_mockBackend);
  2389. }
  2390. /** @fn fakeActionCodeSettings
  2391. @brief Constructs and returns a fake instance of @c FIRActionCodeSettings for testing.
  2392. @return An instance of @c FIRActionCodeSettings for testing.
  2393. */
  2394. - (FIRActionCodeSettings *)fakeActionCodeSettings {
  2395. FIRActionCodeSettings *actionCodeSettings = [[FIRActionCodeSettings alloc] init];
  2396. actionCodeSettings.URL = [NSURL URLWithString:kContinueURL];
  2397. actionCodeSettings.handleCodeInApp = YES;
  2398. return actionCodeSettings;
  2399. }
  2400. /** @fn testUpdateCurrentUserFailure
  2401. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2402. call.
  2403. */
  2404. - (void)testUpdateCurrentUserFailure {
  2405. NSString *kTestAccessToken = @"fakeAccessToken";
  2406. NSString *kTestAPIKey = @"fakeAPIKey";
  2407. [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
  2408. NSString *kTestAPIKey2 = @"fakeAPIKey2";
  2409. FIRUser *user2 = [FIRAuth auth].currentUser;
  2410. user2.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey2
  2411. appID:kFirebaseAppID];
  2412. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2413. .andDispatchError2([FIRAuthErrorUtils invalidAPIKeyError]);
  2414. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2415. [[FIRAuth auth] updateCurrentUser:user2
  2416. completion:^(NSError *_Nullable error) {
  2417. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidAPIKey);
  2418. [expectation fulfill];
  2419. }];
  2420. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2421. OCMVerifyAll(_mockBackend);
  2422. }
  2423. /** @fn testUpdateCurrentUserFailureNetworkError
  2424. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2425. call with a network error.
  2426. */
  2427. - (void)testUpdateCurrentUserFailureNetworkError {
  2428. NSString *kTestAPIKey = @"fakeAPIKey";
  2429. NSString *kTestAccessToken = @"fakeAccessToken";
  2430. [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
  2431. NSString *kTestAPIKey2 = @"fakeAPIKey2";
  2432. FIRUser *user2 = [FIRAuth auth].currentUser;
  2433. user2.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey2
  2434. appID:kFirebaseAppID];
  2435. NSError *underlyingError = [NSError errorWithDomain:@"Test Error" code:1 userInfo:nil];
  2436. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2437. .andDispatchError2([FIRAuthErrorUtils networkErrorWithUnderlyingError:underlyingError]);
  2438. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2439. [[FIRAuth auth] updateCurrentUser:user2
  2440. completion:^(NSError *_Nullable error) {
  2441. XCTAssertEqual(error.code, FIRAuthErrorCodeNetworkError);
  2442. [expectation fulfill];
  2443. }];
  2444. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2445. OCMVerifyAll(_mockBackend);
  2446. }
  2447. /** @fn testUpdateCurrentUserFailureNUllUser
  2448. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2449. call with FIRAuthErrorCodeNullUser.
  2450. */
  2451. - (void)testUpdateCurrentUserFailureNUllUser {
  2452. NSString *kTestAccessToken = @"fakeAccessToken";
  2453. NSString *kTestAPIKey = @"fakeAPIKey";
  2454. [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
  2455. FIRUser *fakeNilUser = nil;
  2456. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2457. [[FIRAuth auth] updateCurrentUser:fakeNilUser
  2458. completion:^(NSError *_Nullable error) {
  2459. XCTAssertEqual(error.code, FIRAuthErrorCodeNullUser);
  2460. [expectation fulfill];
  2461. }];
  2462. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2463. OCMVerifyAll(_mockBackend);
  2464. }
  2465. /** @fn testUpdateCurrentUserFailureTenantIDMismatch
  2466. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2467. call with FIRAuthErrorCodeTenantIDMismatch.
  2468. */
  2469. - (void)testUpdateCurrentUserFailureTenantIDMismatch {
  2470. // User without tenant id
  2471. [self waitForSignInWithAccessToken:kAccessToken APIKey:kAPIKey completion:nil];
  2472. FIRUser *user1 = [FIRAuth auth].currentUser;
  2473. [[FIRAuth auth] signOut:nil];
  2474. // User with tenant id "tenant-id"
  2475. [FIRAuth auth].tenantID = @"tenant-id-1";
  2476. NSString *kTestAccessToken2 = @"fakeAccessToken2";
  2477. [self waitForSignInWithAccessToken:kTestAccessToken2 APIKey:kAPIKey completion:nil];
  2478. FIRUser *user2 = [FIRAuth auth].currentUser;
  2479. [[FIRAuth auth] signOut:nil];
  2480. [FIRAuth auth].tenantID = @"tenant-id-2";
  2481. XCTestExpectation *expectation1 = [self expectationWithDescription:@"callback"];
  2482. [[FIRAuth auth] updateCurrentUser:user1
  2483. completion:^(NSError *_Nullable error) {
  2484. XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
  2485. [expectation1 fulfill];
  2486. }];
  2487. [[FIRAuth auth] signOut:nil];
  2488. [FIRAuth auth].tenantID = @"tenant-id-2";
  2489. XCTestExpectation *expectation2 = [self expectationWithDescription:@"callback"];
  2490. [[FIRAuth auth] updateCurrentUser:user2
  2491. completion:^(NSError *_Nullable error) {
  2492. XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
  2493. [expectation2 fulfill];
  2494. }];
  2495. [[FIRAuth auth] signOut:nil];
  2496. [FIRAuth auth].tenantID = nil;
  2497. XCTestExpectation *expectation3 = [self expectationWithDescription:@"callback"];
  2498. [[FIRAuth auth] updateCurrentUser:user2
  2499. completion:^(NSError *_Nullable error) {
  2500. XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
  2501. [expectation3 fulfill];
  2502. }];
  2503. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2504. OCMVerifyAll(_mockBackend);
  2505. }
  2506. /** @fn testUpdateCurrentUserSuccess
  2507. @brief Tests the flow of a successful @c updateCurrentUser:completion:
  2508. call with a network error.
  2509. */
  2510. - (void)testUpdateCurrentUserSuccess {
  2511. // Sign in with the first user.
  2512. [self waitForSignInWithAccessToken:kAccessToken APIKey:kAPIKey completion:nil];
  2513. FIRUser *user1 = [FIRAuth auth].currentUser;
  2514. NSString *kTestAPIKey = @"fakeAPIKey";
  2515. user1.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey
  2516. appID:kFirebaseAppID];
  2517. [[FIRAuth auth] signOut:nil];
  2518. NSString *kTestAccessToken2 = @"fakeAccessToken2";
  2519. [self waitForSignInWithAccessToken:kTestAccessToken2 APIKey:kAPIKey completion:nil];
  2520. FIRUser *user2 = [FIRAuth auth].currentUser;
  2521. [self expectGetAccountInfoWithAccessToken:kAccessToken];
  2522. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2523. // Current user should now be user2.
  2524. XCTAssertEqualObjects([FIRAuth auth].currentUser, user2);
  2525. [[FIRAuth auth] updateCurrentUser:user1
  2526. completion:^(NSError *_Nullable error) {
  2527. XCTAssertNil(error);
  2528. // Current user should now be user1.
  2529. XCTAssertEqualObjects([FIRAuth auth].currentUser, user1);
  2530. XCTAssertNotEqualObjects([FIRAuth auth].currentUser, user2);
  2531. [expectation fulfill];
  2532. }];
  2533. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2534. OCMVerifyAll(_mockBackend);
  2535. }
  2536. /** @fn testSignOut
  2537. @brief Tests the @c signOut: method.
  2538. */
  2539. - (void)testSignOut {
  2540. [self waitForSignIn];
  2541. // Verify signing out succeeds and clears the current user.
  2542. NSError *error;
  2543. XCTAssertTrue([[FIRAuth auth] signOut:&error]);
  2544. XCTAssertNil([FIRAuth auth].currentUser);
  2545. }
  2546. /** @fn testIsSignInWithEmailLink
  2547. @brief Tests the @c isSignInWithEmailLink: method.
  2548. */
  2549. - (void)testIsSignInWithEmailLink {
  2550. XCTAssertTrue([[FIRAuth auth] isSignInWithEmailLink:kFakeEmailSignInlink]);
  2551. XCTAssertTrue([[FIRAuth auth] isSignInWithEmailLink:kFakeEmailSignInDeeplink]);
  2552. XCTAssertFalse([[FIRAuth auth] isSignInWithEmailLink:kBadSignInEmailLink]);
  2553. XCTAssertFalse([[FIRAuth auth] isSignInWithEmailLink:@""]);
  2554. }
  2555. /** @fn testAuthStateChanges
  2556. @brief Tests @c addAuthStateDidChangeListener: and @c removeAuthStateDidChangeListener: methods.
  2557. */
  2558. - (void)testAuthStateChanges {
  2559. // Set up listener.
  2560. __block XCTestExpectation *expectation;
  2561. __block BOOL shouldHaveUser;
  2562. FIRAuthStateDidChangeListenerBlock listener = ^(FIRAuth *auth, FIRUser *_Nullable user) {
  2563. XCTAssertTrue([NSThread isMainThread]);
  2564. XCTAssertEqual(auth, [FIRAuth auth]);
  2565. XCTAssertEqual(user, [FIRAuth auth].currentUser);
  2566. if (shouldHaveUser) {
  2567. XCTAssertNotNil(user);
  2568. } else {
  2569. XCTAssertNil(user);
  2570. }
  2571. // `expectation` being nil means the listener is not expected to be fired at this moment.
  2572. XCTAssertNotNil(expectation);
  2573. [expectation fulfill];
  2574. };
  2575. [[FIRAuth auth] signOut:NULL];
  2576. [self waitForTimeIntervel:kWaitInterval]; // Wait until dust settled from previous tests.
  2577. // Listener should fire immediately when attached.
  2578. expectation = [self expectationWithDescription:@"initial"];
  2579. shouldHaveUser = NO;
  2580. FIRAuthStateDidChangeListenerHandle handle =
  2581. [[FIRAuth auth] addAuthStateDidChangeListener:listener];
  2582. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2583. // Listener should fire for signing in.
  2584. expectation = [self expectationWithDescription:@"sign-in"];
  2585. shouldHaveUser = YES;
  2586. [self waitForSignIn];
  2587. // Listener should not fire for signing in again.
  2588. shouldHaveUser = YES;
  2589. [self waitForSignIn];
  2590. [self waitForTimeIntervel:kWaitInterval]; // make sure listener is not called
  2591. // Listener should fire for signing out.
  2592. expectation = [self expectationWithDescription:@"sign-out"];
  2593. shouldHaveUser = NO;
  2594. [[FIRAuth auth] signOut:NULL];
  2595. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2596. // Listener should no longer fire once detached.
  2597. expectation = nil;
  2598. [[FIRAuth auth] removeAuthStateDidChangeListener:handle];
  2599. [self waitForSignIn];
  2600. [self waitForTimeIntervel:kWaitInterval]; // make sure listener is no longer called
  2601. }
  2602. /** @fn testIDTokenChanges
  2603. @brief Tests @c addIDTokenDidChangeListener: and @c removeIDTokenDidChangeListener: methods.
  2604. */
  2605. - (void)testIDTokenChanges {
  2606. // Set up listener.
  2607. __block XCTestExpectation *expectation;
  2608. __block BOOL shouldHaveUser;
  2609. FIRIDTokenDidChangeListenerBlock listener = ^(FIRAuth *auth, FIRUser *_Nullable user) {
  2610. XCTAssertTrue([NSThread isMainThread]);
  2611. XCTAssertEqual(auth, [FIRAuth auth]);
  2612. XCTAssertEqual(user, [FIRAuth auth].currentUser);
  2613. if (shouldHaveUser) {
  2614. XCTAssertNotNil(user);
  2615. } else {
  2616. XCTAssertNil(user);
  2617. }
  2618. // `expectation` being nil means the listener is not expected to be fired at this moment.
  2619. XCTAssertNotNil(expectation);
  2620. [expectation fulfill];
  2621. };
  2622. [[FIRAuth auth] signOut:NULL];
  2623. [self waitForTimeIntervel:kWaitInterval]; // Wait until dust settled from previous tests.
  2624. // Listener should fire immediately when attached.
  2625. expectation = [self expectationWithDescription:@"initial"];
  2626. shouldHaveUser = NO;
  2627. FIRIDTokenDidChangeListenerHandle handle = [[FIRAuth auth] addIDTokenDidChangeListener:listener];
  2628. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2629. // Listener should fire for signing in.
  2630. expectation = [self expectationWithDescription:@"sign-in"];
  2631. shouldHaveUser = YES;
  2632. [self waitForSignIn];
  2633. // Listener should fire for signing in again as the same user with another access token.
  2634. expectation = [self expectationWithDescription:@"sign-in again"];
  2635. shouldHaveUser = YES;
  2636. [self waitForSignInWithAccessToken:kNewAccessToken APIKey:nil completion:nil];
  2637. // Listener should fire for signing out.
  2638. expectation = [self expectationWithDescription:@"sign-out"];
  2639. shouldHaveUser = NO;
  2640. [[FIRAuth auth] signOut:NULL];
  2641. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2642. // Listener should no longer fire once detached.
  2643. expectation = nil;
  2644. [[FIRAuth auth] removeIDTokenDidChangeListener:handle];
  2645. [self waitForSignIn];
  2646. [self waitForTimeIntervel:kWaitInterval]; // make sure listener is no longer called
  2647. }
  2648. /** @fn testUseEmulator
  2649. @brief Tests the @c useEmulatorWithHost:port: method.
  2650. */
  2651. - (void)testUseEmulator {
  2652. [[FIRAuth auth] useEmulatorWithHost:@"host" port:12345];
  2653. XCTAssertEqualObjects(@"host:12345", [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
  2654. #if TARGET_OS_IOS
  2655. XCTAssertTrue([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
  2656. #endif
  2657. }
  2658. /** @fn testUseEmulatorNeverCalled
  2659. @brief Tests that the emulatorHostAndPort stored in @c FIRAuthRequestConfiguration is nil if the
  2660. @c useEmulatorWithHost:port: is not called.
  2661. */
  2662. - (void)testUseEmulatorNeverCalled {
  2663. XCTAssertEqualObjects(nil, [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
  2664. #if TARGET_OS_IOS
  2665. XCTAssertFalse([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
  2666. #endif
  2667. }
  2668. /** @fn testUseEmulatorIPv6Address
  2669. @brief Tests the @c useEmulatorWithHost:port: method with an IPv6 host address.
  2670. */
  2671. - (void)testUseEmulatorIPv6Address {
  2672. [[FIRAuth auth] useEmulatorWithHost:@"::1" port:12345];
  2673. XCTAssertEqualObjects(@"[::1]:12345", [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
  2674. #if TARGET_OS_IOS
  2675. XCTAssertTrue([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
  2676. #endif
  2677. }
  2678. #pragma mark - Automatic Token Refresh Tests.
  2679. /** @fn testAutomaticTokenRefresh
  2680. @brief Tests a successful flow to automatically refresh tokens for a signed in user.
  2681. */
  2682. - (void)testAutomaticTokenRefresh {
  2683. [[FIRAuth auth] signOut:NULL];
  2684. // Enable auto refresh
  2685. [self enableAutoTokenRefresh];
  2686. // Sign in a user.
  2687. [self waitForSignIn];
  2688. // Set up expectation for secureToken RPC made by token refresh task. We call this twice, because
  2689. // we retry once if the access token is already expired.
  2690. [self mockSecureTokenResponseWithError:nil];
  2691. [self mockSecureTokenResponseWithError:nil];
  2692. // Verify that the current user's access token is the "old" access token before automatic token
  2693. // refresh.
  2694. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2695. // Execute saved token refresh task.
  2696. XCTestExpectation *dispatchAfterExpectation =
  2697. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2698. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2699. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2700. self->_FIRAuthDispatcherCallback();
  2701. [dispatchAfterExpectation fulfill];
  2702. });
  2703. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2704. // Verify that current user's access token is the "new" access token provided in the mock secure
  2705. // token response during automatic token refresh.
  2706. XCTAssertEqualObjects(kNewAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2707. OCMVerifyAll(_mockBackend);
  2708. }
  2709. /** @fn testAutomaticTokenRefreshInvalidTokenFailure
  2710. @brief Tests an unsuccessful flow to auto refresh tokens with an "invalid token" error.
  2711. This error should cause the user to be signed out.
  2712. */
  2713. - (void)testAutomaticTokenRefreshInvalidTokenFailure {
  2714. [[FIRAuth auth] signOut:NULL];
  2715. // Enable auto refresh
  2716. [self enableAutoTokenRefresh];
  2717. // Sign in a user.
  2718. [self waitForSignIn];
  2719. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  2720. [self mockSecureTokenResponseWithError:[FIRAuthErrorUtils invalidUserTokenErrorWithMessage:nil]];
  2721. // Verify that current user is still valid.
  2722. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2723. // Execute saved token refresh task.
  2724. XCTestExpectation *dispatchAfterExpectation =
  2725. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2726. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2727. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2728. self->_FIRAuthDispatcherCallback();
  2729. [dispatchAfterExpectation fulfill];
  2730. });
  2731. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2732. // Verify that the user is nil after failed attempt to refresh tokens caused signed out.
  2733. XCTAssertNil([FIRAuth auth].currentUser);
  2734. OCMVerifyAll(_mockBackend);
  2735. }
  2736. /** @fn testAutomaticTokenRefreshRetry
  2737. @brief Tests that a retry is attempted for a automatic token refresh task (which is not due to
  2738. invalid tokens). The initial attempt to refresh the access token fails, but the second
  2739. attempt is successful.
  2740. */
  2741. - (void)testAutomaticTokenRefreshRetry {
  2742. [[FIRAuth auth] signOut:NULL];
  2743. // Enable auto refresh
  2744. [self enableAutoTokenRefresh];
  2745. // Sign in a user.
  2746. [self waitForSignIn];
  2747. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  2748. [self mockSecureTokenResponseWithError:[NSError errorWithDomain:@"ERROR" code:-1 userInfo:nil]];
  2749. // Execute saved token refresh task.
  2750. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2751. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2752. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2753. self->_FIRAuthDispatcherCallback();
  2754. self->_FIRAuthDispatcherCallback = nil;
  2755. [expectation fulfill];
  2756. });
  2757. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2758. // The old access token should still be the current user's access token and not the new access
  2759. // token (kNewAccessToken).
  2760. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2761. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens. We call
  2762. // this twice, because we retry once if the access token is already expired.
  2763. [self mockSecureTokenResponseWithError:nil];
  2764. [self mockSecureTokenResponseWithError:nil];
  2765. // Execute saved token refresh task.
  2766. XCTestExpectation *dispatchAfterExpectation =
  2767. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2768. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2769. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2770. self->_FIRAuthDispatcherCallback();
  2771. [dispatchAfterExpectation fulfill];
  2772. });
  2773. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2774. // Verify that current user's access token is the "new" access token provided in the mock secure
  2775. // token response during automatic token refresh.
  2776. XCTAssertEqualObjects([FIRAuth auth].currentUser.rawAccessToken, kNewAccessToken);
  2777. OCMVerifyAll(_mockBackend);
  2778. }
  2779. #if TARGET_OS_IOS
  2780. /** @fn testAutomaticTokenRefreshInvalidTokenFailure
  2781. @brief Tests that app foreground notification triggers the scheduling of an automatic token
  2782. refresh task.
  2783. */
  2784. - (void)testAutoRefreshAppForegroundedNotification {
  2785. [[FIRAuth auth] signOut:NULL];
  2786. // Enable auto refresh
  2787. [self enableAutoTokenRefresh];
  2788. // Sign in a user.
  2789. [self waitForSignIn];
  2790. // Post "UIApplicationDidBecomeActiveNotification" to trigger scheduling token refresh task.
  2791. [[NSNotificationCenter defaultCenter]
  2792. postNotificationName:UIApplicationDidBecomeActiveNotification
  2793. object:nil];
  2794. // Verify that current user is still valid with old access token.
  2795. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2796. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens. We call
  2797. // this twice, because we retry once if the access token is already expired.
  2798. [self mockSecureTokenResponseWithError:nil];
  2799. [self mockSecureTokenResponseWithError:nil];
  2800. // Execute saved token refresh task.
  2801. XCTestExpectation *dispatchAfterExpectation =
  2802. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2803. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2804. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2805. self->_FIRAuthDispatcherCallback();
  2806. [dispatchAfterExpectation fulfill];
  2807. });
  2808. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2809. // Verify that current user is still valid with new access token.
  2810. XCTAssertEqualObjects(kNewAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2811. OCMVerifyAll(_mockBackend);
  2812. }
  2813. #endif
  2814. #if TARGET_OS_IOS
  2815. #pragma mark - Application Delegate tests
  2816. - (void)testAppDidRegisterForRemoteNotifications_APNSTokenUpdated {
  2817. NSData *apnsToken = [NSData data];
  2818. OCMExpect([self.mockTokenManager setToken:[OCMArg checkWithBlock:^BOOL(FIRAuthAPNSToken *token) {
  2819. XCTAssertEqual(token.data, apnsToken);
  2820. XCTAssertEqual(token.type, FIRAuthAPNSTokenTypeUnknown);
  2821. return YES;
  2822. }]]);
  2823. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2824. didRegisterForRemoteNotificationsWithDeviceToken:apnsToken];
  2825. [self.mockTokenManager verify];
  2826. }
  2827. - (void)testAppDidFailToRegisterForRemoteNotifications_TokenManagerCancels {
  2828. NSError *error = [NSError errorWithDomain:@"FIRAuthTests" code:-1 userInfo:nil];
  2829. OCMExpect([self.mockTokenManager cancelWithError:error]);
  2830. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2831. didFailToRegisterForRemoteNotificationsWithError:error];
  2832. [self.mockTokenManager verify];
  2833. }
  2834. - (void)testAppDidReceiveRemoteNotification_NotificationManagerHandleCanNotification {
  2835. NSDictionary *notification = @{@"test" : @""};
  2836. OCMExpect([self.mockNotificationManager canHandleNotification:notification]);
  2837. #pragma clang diagnostic push
  2838. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2839. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2840. didReceiveRemoteNotification:notification];
  2841. #pragma clang diagnostic pop
  2842. [self.mockNotificationManager verify];
  2843. }
  2844. - (void)testAppDidReceiveRemoteNotificationWithCompletion_NotificationManagerHandleCanNotification {
  2845. NSDictionary *notification = @{@"test" : @""};
  2846. OCMExpect([self.mockNotificationManager canHandleNotification:notification]);
  2847. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2848. didReceiveRemoteNotification:notification
  2849. fetchCompletionHandler:^(UIBackgroundFetchResult result){
  2850. }];
  2851. [self.mockNotificationManager verify];
  2852. }
  2853. - (void)testAppOpenURL_AuthPresenterCanHandleURL {
  2854. if (@available(iOS 9.0, *)) {
  2855. // 'application:openURL:options:' is only available on iOS 9.0 or newer.
  2856. NSURL *url = [NSURL URLWithString:@"https://localhost"];
  2857. OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
  2858. XCTAssertTrue([self.fakeApplicationDelegate
  2859. application:[GULAppDelegateSwizzler sharedApplication]
  2860. openURL:url
  2861. options:@{}]);
  2862. [self.mockAuthURLPresenter verify];
  2863. }
  2864. }
  2865. - (void)testAppOpenURLWithSourceApplication_AuthPresenterCanHandleURL {
  2866. NSURL *url = [NSURL URLWithString:@"https://localhost"];
  2867. OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
  2868. #pragma clang diagnostic push
  2869. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2870. XCTAssertTrue([self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2871. openURL:url
  2872. sourceApplication:@""
  2873. annotation:[[NSObject alloc] init]]);
  2874. #pragma clang diagnostic pop
  2875. [self.mockAuthURLPresenter verify];
  2876. }
  2877. #endif // TARGET_OS_IOS
  2878. #pragma mark - Interoperability Tests
  2879. /** @fn testComponentsBeingRegistered
  2880. @brief Tests that Auth provides the necessary components for interoperability with other SDKs.
  2881. */
  2882. - (void)testComponentsBeingRegistered {
  2883. // Verify that the components are registered properly. Check the count, because any time a new
  2884. // component is added it should be added to the test suite as well.
  2885. NSArray<FIRComponent *> *components = [FIRAuth componentsToRegister];
  2886. XCTAssertTrue(components.count == 1);
  2887. FIRComponent *component = [components firstObject];
  2888. XCTAssert(component.protocol == @protocol(FIRAuthInterop));
  2889. }
  2890. #pragma mark - Helpers
  2891. /** @fn mockSecureTokenResponseWithError:
  2892. @brief Set up expectation for secureToken RPC.
  2893. @param error The error that the mock should return if any.
  2894. */
  2895. - (void)mockSecureTokenResponseWithError:(nullable NSError *)error {
  2896. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens.
  2897. XCTestExpectation *secureTokenResponseExpectation =
  2898. [self expectationWithDescription:@"secureTokenResponseExpectation"];
  2899. OCMExpect([_mockBackend secureToken:[OCMArg any] callback:[OCMArg any]])
  2900. .andCallBlock2(
  2901. ^(FIRSecureTokenRequest *_Nullable request, FIRSecureTokenResponseCallback callback) {
  2902. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2903. XCTAssertEqualObjects(request.refreshToken, kRefreshToken);
  2904. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2905. if (error) {
  2906. callback(nil, error);
  2907. [secureTokenResponseExpectation fulfill];
  2908. return;
  2909. }
  2910. id mockSecureTokenResponse = OCMClassMock([FIRSecureTokenResponse class]);
  2911. OCMStub([mockSecureTokenResponse accessToken]).andReturn(kNewAccessToken);
  2912. NSDate *futureDate =
  2913. [[NSDate date] dateByAddingTimeInterval:kTestTokenExpirationTimeInterval];
  2914. OCMStub([mockSecureTokenResponse approximateExpirationDate]).andReturn(futureDate);
  2915. callback(mockSecureTokenResponse, nil);
  2916. [secureTokenResponseExpectation fulfill];
  2917. });
  2918. });
  2919. }
  2920. /** @fn enableAutoTokenRefresh
  2921. @brief Enables automatic token refresh by invoking FIRAuth's implementation of FIRApp's
  2922. |getTokenWithImplementation|.
  2923. */
  2924. - (void)enableAutoTokenRefresh {
  2925. XCTestExpectation *expectation = [self expectationWithDescription:@"autoTokenRefreshcallback"];
  2926. [[FIRAuth auth] getTokenForcingRefresh:NO
  2927. withCallback:^(NSString *_Nullable token, NSError *_Nullable error) {
  2928. [expectation fulfill];
  2929. }];
  2930. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2931. }
  2932. /** @fn stubSecureTokensWithMockResponse
  2933. @brief Creates stubs on the mock response object with access and refresh tokens
  2934. @param mockResponse The mock response object.
  2935. */
  2936. - (void)stubTokensWithMockResponse:(id)mockResponse {
  2937. OCMStub([mockResponse IDToken]).andReturn(kAccessToken);
  2938. OCMStub([mockResponse approximateExpirationDate])
  2939. .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
  2940. OCMStub([mockResponse refreshToken]).andReturn(kRefreshToken);
  2941. }
  2942. /** @fn expectGetAccountInfo
  2943. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2944. data.
  2945. */
  2946. - (void)expectGetAccountInfo {
  2947. [self expectGetAccountInfoWithAccessToken:kAccessToken];
  2948. }
  2949. /** @fn expectGetAccountInfoWithAccessToken
  2950. @param accessToken The access token for the user to check against.
  2951. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2952. data.
  2953. */
  2954. - (void)expectGetAccountInfoWithAccessToken:(NSString *)accessToken {
  2955. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2956. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2957. FIRGetAccountInfoResponseCallback callback) {
  2958. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2959. XCTAssertEqualObjects(request.accessToken, accessToken);
  2960. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2961. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2962. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2963. OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
  2964. OCMStub([mockGetAccountInfoResponseUser email]).andReturn(kEmail);
  2965. OCMStub([mockGetAccountInfoResponseUser passwordHash]).andReturn(kPasswordHash);
  2966. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2967. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2968. mockGetAccountInfoResponseUser
  2969. ]);
  2970. callback(mockGetAccountInfoResponse, nil);
  2971. });
  2972. });
  2973. }
  2974. /** @fn assertUser
  2975. @brief Asserts the given FIRUser matching the fake data returned by @c expectGetAccountInfo.
  2976. @param user The user object to be verified.
  2977. */
  2978. - (void)assertUser:(FIRUser *)user {
  2979. XCTAssertNotNil(user);
  2980. XCTAssertEqualObjects(user.uid, kLocalID);
  2981. XCTAssertEqualObjects(user.displayName, kDisplayName);
  2982. XCTAssertEqualObjects(user.email, kEmail);
  2983. XCTAssertFalse(user.anonymous);
  2984. XCTAssertEqual(user.providerData.count, 0u);
  2985. }
  2986. /** @fn expectGetAccountInfoGoogle
  2987. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2988. data for a Google Sign-In user.
  2989. */
  2990. - (void)expectGetAccountInfoGoogle {
  2991. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2992. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2993. FIRGetAccountInfoResponseCallback callback) {
  2994. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2995. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  2996. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2997. id mockGoogleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
  2998. OCMStub([mockGoogleUserInfo providerID]).andReturn(FIRGoogleAuthProviderID);
  2999. OCMStub([mockGoogleUserInfo displayName]).andReturn(kGoogleDisplayName);
  3000. OCMStub([mockGoogleUserInfo federatedID]).andReturn(kGoogleID);
  3001. OCMStub([mockGoogleUserInfo email]).andReturn(kGoogleEmail);
  3002. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  3003. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  3004. OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
  3005. OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
  3006. .andReturn((@[ mockGoogleUserInfo ]));
  3007. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  3008. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  3009. mockGetAccountInfoResponseUser
  3010. ]);
  3011. callback(mockGetAccountInfoResponse, nil);
  3012. });
  3013. });
  3014. }
  3015. /** @fn assertUserGoogle
  3016. @brief Asserts the given FIRUser matching the fake data returned by
  3017. @c expectGetAccountInfoGoogle.
  3018. @param user The user object to be verified.
  3019. */
  3020. - (void)assertUserGoogle:(FIRUser *)user {
  3021. XCTAssertNotNil(user);
  3022. XCTAssertEqualObjects(user.uid, kLocalID);
  3023. XCTAssertEqualObjects(user.displayName, kDisplayName);
  3024. XCTAssertEqual(user.providerData.count, 1u);
  3025. id<FIRUserInfo> googleUserInfo = user.providerData[0];
  3026. XCTAssertEqualObjects(googleUserInfo.providerID, FIRGoogleAuthProviderID);
  3027. XCTAssertEqualObjects(googleUserInfo.uid, kGoogleID);
  3028. XCTAssertEqualObjects(googleUserInfo.displayName, kGoogleDisplayName);
  3029. XCTAssertEqualObjects(googleUserInfo.email, kGoogleEmail);
  3030. }
  3031. /** @fn expectGetAccountInfoAnonymous
  3032. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake anonymous
  3033. account data.
  3034. */
  3035. - (void)expectGetAccountInfoAnonymous {
  3036. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  3037. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  3038. FIRGetAccountInfoResponseCallback callback) {
  3039. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3040. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  3041. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3042. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  3043. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  3044. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  3045. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  3046. mockGetAccountInfoResponseUser
  3047. ]);
  3048. callback(mockGetAccountInfoResponse, nil);
  3049. });
  3050. });
  3051. }
  3052. /** @fn assertUserAnonymous
  3053. @brief Asserts the given FIRUser matching the fake data returned by
  3054. @c expectGetAccountInfoAnonymous.
  3055. @param user The user object to be verified.
  3056. */
  3057. - (void)assertUserAnonymous:(FIRUser *)user {
  3058. XCTAssertNotNil(user);
  3059. XCTAssertEqualObjects(user.uid, kLocalID);
  3060. XCTAssertNil(user.displayName);
  3061. XCTAssertTrue(user.anonymous);
  3062. XCTAssertEqual(user.providerData.count, 0u);
  3063. }
  3064. /** @fn waitForSignIn
  3065. @brief Signs in a user to prepare for tests.
  3066. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  3067. */
  3068. - (void)waitForSignIn {
  3069. [self waitForSignInWithAccessToken:kAccessToken APIKey:nil completion:nil];
  3070. }
  3071. /** @fn waitForSignInWithAccessToken:
  3072. @brief Signs in a user to prepare for tests.
  3073. @param accessToken The access token for the user to have.
  3074. @param APIKey Optionally, The API key associated with the user.
  3075. @param completion Optionally, The completion invoked at the end of the flow.
  3076. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  3077. */
  3078. - (void)waitForSignInWithAccessToken:(NSString *)accessToken
  3079. APIKey:(nullable NSString *)APIKey
  3080. completion:(nullable FIRAuthResultCallback)completion {
  3081. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3082. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3083. FIRVerifyPasswordResponseCallback callback) {
  3084. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3085. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3086. OCMStub([mockVerifyPasswordResponse IDToken]).andReturn(accessToken);
  3087. OCMStub([mockVerifyPasswordResponse approximateExpirationDate])
  3088. .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
  3089. OCMStub([mockVerifyPasswordResponse refreshToken]).andReturn(kRefreshToken);
  3090. callback(mockVerifyPasswordResponse, nil);
  3091. });
  3092. });
  3093. [self expectGetAccountInfoWithAccessToken:accessToken];
  3094. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  3095. [[FIRAuth auth] signInWithEmail:kEmail
  3096. password:kFakePassword
  3097. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3098. result.user.requestConfiguration =
  3099. [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey
  3100. appID:kFirebaseAppID];
  3101. [expectation fulfill];
  3102. if (completion) {
  3103. completion(result.user, error);
  3104. }
  3105. }];
  3106. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3107. OCMVerifyAll(_mockBackend);
  3108. XCTAssertNotNil([FIRAuth auth].currentUser);
  3109. }
  3110. /** @fn waitForTimeInterval:
  3111. @brief Wait for a particular time interval.
  3112. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  3113. */
  3114. - (void)waitForTimeIntervel:(NSTimeInterval)timeInterval {
  3115. static dispatch_queue_t queue;
  3116. static dispatch_once_t onceToken;
  3117. XCTestExpectation *expectation = [self expectationWithDescription:@"waitForTimeIntervel:"];
  3118. dispatch_once(&onceToken, ^{
  3119. queue = dispatch_queue_create("com.google.FIRAuthUnitTests.waitForTimeIntervel", NULL);
  3120. });
  3121. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeInterval * NSEC_PER_SEC), queue, ^() {
  3122. [expectation fulfill];
  3123. });
  3124. [self waitForExpectationsWithTimeout:timeInterval + kExpectationTimeout handler:nil];
  3125. }
  3126. - (void)waitForAuthGlobalWorkQueueDrain {
  3127. dispatch_semaphore_t workerSemaphore = dispatch_semaphore_create(0);
  3128. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  3129. dispatch_semaphore_signal(workerSemaphore);
  3130. });
  3131. dispatch_semaphore_wait(workerSemaphore,
  3132. DISPATCH_TIME_FOREVER /*DISPATCH_TIME_NOW + 10 * NSEC_PER_SEC*/);
  3133. }
  3134. /** @fn testRevokeTokenSuccess
  3135. @brief Tests the flow of a successful @c revokeToken:completion.
  3136. */
  3137. - (void)testRevokeTokenSuccess {
  3138. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3139. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3140. FIRVerifyPasswordResponseCallback callback) {
  3141. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3142. XCTAssertEqualObjects(request.email, kEmail);
  3143. XCTAssertEqualObjects(request.password, kFakePassword);
  3144. XCTAssertTrue(request.returnSecureToken);
  3145. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3146. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3147. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  3148. callback(mockVerifyPasswordResponse, nil);
  3149. });
  3150. });
  3151. [self expectGetAccountInfo];
  3152. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  3153. [[FIRAuth auth] signOut:NULL];
  3154. [[FIRAuth auth] signInWithEmail:kEmail
  3155. password:kFakePassword
  3156. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3157. [self assertUser:result.user];
  3158. XCTAssertNil(error);
  3159. [signInExpectation fulfill];
  3160. }];
  3161. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3162. [self assertUser:[FIRAuth auth].currentUser];
  3163. OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
  3164. .andCallBlock2(
  3165. ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
  3166. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3167. id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
  3168. callback(mockRevokeTokenResponse, nil);
  3169. });
  3170. });
  3171. XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"callback"];
  3172. NSString *code = @"code";
  3173. [[FIRAuth auth] revokeTokenWithAuthorizationCode:code
  3174. completion:^(NSError *_Nullable error) {
  3175. XCTAssertNil(error);
  3176. [revokeExpectation fulfill];
  3177. }];
  3178. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3179. }
  3180. /** @fn testRevokeTokenMissingCallback
  3181. @brief Tests the flow of @c revokeToken:completion with a nil callback.
  3182. */
  3183. - (void)testRevokeTokenMissingCallback {
  3184. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3185. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3186. FIRVerifyPasswordResponseCallback callback) {
  3187. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3188. XCTAssertEqualObjects(request.email, kEmail);
  3189. XCTAssertEqualObjects(request.password, kFakePassword);
  3190. XCTAssertTrue(request.returnSecureToken);
  3191. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3192. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3193. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  3194. callback(mockVerifyPasswordResponse, nil);
  3195. });
  3196. });
  3197. [self expectGetAccountInfo];
  3198. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  3199. [[FIRAuth auth] signOut:NULL];
  3200. [[FIRAuth auth] signInWithEmail:kEmail
  3201. password:kFakePassword
  3202. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3203. [self assertUser:result.user];
  3204. XCTAssertNil(error);
  3205. [signInExpectation fulfill];
  3206. }];
  3207. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3208. [self assertUser:[FIRAuth auth].currentUser];
  3209. XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"revoke"];
  3210. OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
  3211. .andCallBlock2(
  3212. ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
  3213. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3214. id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
  3215. callback(mockRevokeTokenResponse, nil);
  3216. [revokeExpectation fulfill];
  3217. });
  3218. });
  3219. NSString *code = @"code";
  3220. [[FIRAuth auth] revokeTokenWithAuthorizationCode:code completion:nil];
  3221. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3222. }
  3223. @end