MainViewController.m 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456
  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 "MainViewController.h"
  17. #import <objc/runtime.h>
  18. #import <FirebaseCore/FIRApp.h>
  19. #import <FirebaseCore/FIRAppInternal.h>
  20. #import <FirebaseCore/FIRAppAssociationRegistration.h>
  21. #import "AppManager.h"
  22. #import "AuthCredentials.h"
  23. #import "FIRAdditionalUserInfo.h"
  24. #import "FIROAuthProvider.h"
  25. #import "FIRPhoneAuthCredential.h"
  26. #import "FIRPhoneAuthProvider.h"
  27. #import "FIRAuthTokenResult.h"
  28. #import "FirebaseAuth.h"
  29. #import "CustomTokenDataEntryViewController.h"
  30. #import "FacebookAuthProvider.h"
  31. #import "GoogleAuthProvider.h"
  32. #import "SettingsViewController.h"
  33. #import "StaticContentTableViewManager.h"
  34. #import "UIViewController+Alerts.h"
  35. #import "UserInfoViewController.h"
  36. #import "UserTableViewCell.h"
  37. #import "FIRAuth_Internal.h"
  38. #import "FIRAuthAPNSToken.h"
  39. #import "FIRAuthAPNSTokenManager.h"
  40. #import "FIRAuthAppCredential.h"
  41. #import "FIRAuthAppCredentialManager.h"
  42. #import "FIRAuthBackend.h"
  43. #import "FIRVerifyClientRequest.h"
  44. #import "FIRVerifyClientResponse.h"
  45. #import "FIRSendVerificationCodeRequest.h"
  46. NS_ASSUME_NONNULL_BEGIN
  47. /** @typedef textInputCompletionBlock
  48. @brief The type of callback used to report text input prompt results.
  49. */
  50. typedef void (^textInputCompletionBlock)(NSString *_Nullable userInput);
  51. /** @typedef testAutomationCallback
  52. @brief The type of callback used when automatically testing an API.
  53. */
  54. typedef void (^testAutomationCallback)(NSError *_Nullable error);
  55. /** @var kTokenGetButtonText
  56. @brief The text of the "Get Token" button.
  57. */
  58. static NSString *const kTokenGetButtonText = @"Get Token";
  59. /** @var kGetTokenResultButtonText
  60. @brief The text of the "Get Token Result" button.
  61. */
  62. static NSString *const kGetTokenResultButtonText = @"Get Token Result";
  63. /** @var kGetTokenResultForceButtonText
  64. @brief The text of the "Force Token Result" button.
  65. */
  66. static NSString *const kGetTokenResultForceButtonText = @"Force Token Result";
  67. /** @var kTokenRefreshButtonText
  68. @brief The text of the "Refresh Token" button.
  69. */
  70. static NSString *const kTokenRefreshButtonText = @"Force Refresh Token";
  71. /** @var kTokenRefreshedAlertTitle
  72. @brief The title of the "Token Refreshed" alert.
  73. */
  74. static NSString *const kTokenRefreshedAlertTitle = @"Token";
  75. /** @var kTokenRefreshErrorAlertTitle
  76. @brief The title of the "Token Refresh error" alert.
  77. */
  78. static NSString *const kTokenRefreshErrorAlertTitle = @"Get Token Error";
  79. /** @var kSettingsButtonTextDesription
  80. @brief The description for the text of the "Settings" button.
  81. */
  82. static NSString *const kSettingsButtonTextDesription =
  83. @"The button text to open sample app settings";
  84. /** @var kUserInfoButtonText
  85. @brief The text of the "Show User Info" button.
  86. */
  87. static NSString *const kUserInfoButtonText = @"[Show User Info]";
  88. /** @var kSetImageURLText
  89. @brief The text of the "Set Photo url" button.
  90. */
  91. static NSString *const kSetPhotoURLText = @"Set Photo url";
  92. /** @var kSignInGoogleButtonText
  93. @brief The text of the "Google SignIn" button.
  94. */
  95. static NSString *const kSignInGoogleButtonText = @"Sign in with Google";
  96. /** @var kSignInWithEmailLink
  97. @brief The text of the "Sign in with Email Link" button.
  98. */
  99. static NSString *const kSignInWithEmailLink = @"Sign in with Email Link";
  100. /** @var kVerifyEmailLinkAccount
  101. @brief The text of the "Verify Email-link Account" button.
  102. */
  103. static NSString *const kVerifyEmailLinkAccount = @"Verify Email-link Account";
  104. /** @var kSendEmailSignInLink
  105. @brief The text of the "Send Email SignIn link" button
  106. */
  107. static NSString *const kSendEmailSignInLink = @"Send Email Sign in Link";
  108. /** @var kSignInAndRetrieveGoogleButtonText
  109. @brief The text of the "Sign in with Google and retrieve data" button.
  110. */
  111. static NSString *const kSignInGoogleAndRetrieveDataButtonText =
  112. @"Sign in with Google and retrieve data";
  113. /** @var kSignInFacebookButtonText
  114. @brief The text of the "Facebook SignIn" button.
  115. */
  116. static NSString *const kSignInFacebookButtonText = @"Sign in with Facebook";
  117. /** @var kSignInFacebookAndRetrieveDataButtonText
  118. @brief The text of the "Facebook SignIn and retrieve data" button.
  119. */
  120. static NSString *const kSignInFacebookAndRetrieveDataButtonText =
  121. @"Sign in with Facebook and retrieve data";
  122. /** @var kSignInEmailPasswordButtonText
  123. @brief The text of the "Email/Password SignIn" button.
  124. */
  125. static NSString *const kSignInEmailPasswordButtonText = @"Sign in with Email/Password";
  126. /** @var kSignInEmailPasswordAuthDataResultButtonText
  127. @brief The text of the "Email/Password SignIn (AuthDataResult)" button.
  128. */
  129. static NSString *const kSignInEmailPasswordAuthDataResultButtonText =
  130. @"Sign in with Email/Password (Deprecated)";
  131. /** @var kSignInWithCustomTokenButtonText
  132. @brief The text of the "Sign In (BYOAuth)" button.
  133. */
  134. static NSString *const kSignInWithCustomTokenButtonText = @"Sign In (BYOAuth)";
  135. /** @var kSignInWithCustomAuthResultTokenButtonText
  136. @brief The text of the "Sign In with Custom Token (Auth Result)" button.
  137. */
  138. static NSString *const kSignInWithCustomAuthResultTokenButtonText = @"Sign In with Custom Token"
  139. " (Deprecated)";
  140. /** @var kSignInAnonymouslyButtonText
  141. @brief The text of the "Sign In Anonymously" button.
  142. */
  143. static NSString *const kSignInAnonymouslyButtonText = @"Sign In Anonymously";
  144. /** @var kSignInAnonymouslyWithAuthResultButtonText
  145. @brief The text of the "Sign In Anonymously (AuthDataResult)" button.
  146. */
  147. static NSString *const kSignInAnonymouslyWithAuthResultButtonText =
  148. @"Sign In Anonymously (Deprecated)";
  149. /** @var kSignedInAlertTitle
  150. @brief The text of the "Sign In Succeeded" alert.
  151. */
  152. static NSString *const kSignedInAlertTitle = @"Signed In";
  153. /** @var kSignInErrorAlertTitle
  154. @brief The text of the "Sign In Encountered an Error" alert.
  155. */
  156. static NSString *const kSignInErrorAlertTitle = @"Sign-In Error";
  157. /** @var kSignOutButtonText
  158. @brief The text of the "Sign Out" button.
  159. */
  160. static NSString *const kSignOutButtonText = @"Sign Out";
  161. /** @var kDeleteAccountText
  162. @brief The text of the "Delete Account" button.
  163. */
  164. static NSString *const kDeleteUserText = @"Delete Account";
  165. /** @var kReauthenticateGoogleText
  166. @brief The text of the "Reathenticate Google" button.
  167. */
  168. static NSString *const kReauthenticateGoogleText = @"Reauthenticate Google";
  169. /** @var kReauthenticateGoogleAndRetrieveDataText
  170. @brief The text of the "Reathenticate Google and retrieve data" button.
  171. */
  172. static NSString *const kReauthenticateGoogleAndRetrieveDataText =
  173. @"Reauthenticate Google and retrieve data";
  174. /** @var kReauthenticateFBText
  175. @brief The text of the "Reathenticate Facebook" button.
  176. */
  177. static NSString *const kReauthenticateFBText = @"Reauthenticate FB";
  178. /** @var kReauthenticateFBAndRetrieveDataText
  179. @brief The text of the "Reathenticate Facebook and retrieve data" button.
  180. */
  181. static NSString *const kReauthenticateFBAndRetrieveDataText =
  182. @"Reauthenticate FB and retrieve data";
  183. /** @var kReAuthenticateEmail
  184. @brief The text of the "Reathenticate Email" button.
  185. */
  186. static NSString *const kReauthenticateEmailText = @"Reauthenticate Email/Password";
  187. /** @var kOKButtonText
  188. @brief The text of the "OK" button for the Sign In result dialogs.
  189. */
  190. static NSString *const kOKButtonText = @"OK";
  191. /** @var kSetDisplayNameTitle
  192. @brief The title of the "Set Display Name" error dialog.
  193. */
  194. static NSString *const kSetDisplayNameTitle = @"Set Display Name";
  195. /** @var kUpdateEmailText
  196. @brief The title of the "Update Email" button.
  197. */
  198. static NSString *const kUpdateEmailText = @"Update Email";
  199. /** @var kUpdatePasswordText
  200. @brief The title of the "Update Password" button.
  201. */
  202. static NSString *const kUpdatePasswordText = @"Update Password";
  203. /** @var kUpdatePhoneNumber
  204. @brief The title of the "Update Photo" button.
  205. */
  206. static NSString *const kUpdatePhoneNumber = @"Update Phone Number";
  207. /** @var kLinkPhoneNumber
  208. @brief The title of the "Link phone" button.
  209. */
  210. static NSString *const kLinkPhoneNumber = @"Link Phone Number";
  211. /** @var kUnlinkPhone
  212. @brief The title of the "Unlink Phone" button for unlinking phone auth provider.
  213. */
  214. static NSString *const kUnlinkPhoneNumber = @"Unlink Phone Number";
  215. /** @var kReloadText
  216. @brief The title of the "Reload User" button.
  217. */
  218. static NSString *const kReloadText = @"Reload User";
  219. /** @var kLinkWithGoogleText
  220. @brief The title of the "Link with Google" button.
  221. */
  222. static NSString *const kLinkWithGoogleText = @"Link with Google";
  223. /** @var kLinkWithGoogleAndRetrieveDataText
  224. @brief The title of the "Link with Google and retrieve data" button.
  225. */
  226. static NSString *const kLinkWithGoogleAndRetrieveDataText = @"Link with Google and retrieve data";
  227. /** @var kLinkWithFacebookText
  228. @brief The title of the "Link with Facebook Account" button.
  229. */
  230. static NSString *const kLinkWithFacebookText = @"Link with Facebook";
  231. /** @var kLinkWithFacebookAndRetrieveDataText
  232. @brief The title of the "Link with Facebook and retrieve data" button.
  233. */
  234. static NSString *const kLinkWithFacebookAndRetrieveDataText =
  235. @"Link with Facebook and retrieve data";
  236. /** @var kLinkWithEmailPasswordText
  237. @brief The title of the "Link with Email/Password Account" button.
  238. */
  239. static NSString *const kLinkWithEmailPasswordText = @"Link with Email/Password";
  240. /** @var kUnlinkTitle
  241. @brief The text of the "Unlink from Provider" error Dialog.
  242. */
  243. static NSString *const kUnlinkTitle = @"Unlink from Provider";
  244. /** @var kUnlinkFromGoogle
  245. @brief The text of the "Unlink from Google" button.
  246. */
  247. static NSString *const kUnlinkFromGoogle = @"Unlink from Google";
  248. /** @var kUnlinkFromFacebook
  249. @brief The text of the "Unlink from Facebook" button.
  250. */
  251. static NSString *const kUnlinkFromFacebook = @"Unlink from Facebook";
  252. /** @var kUnlinkFromEmailPassword
  253. @brief The text of the "Unlink from Google" button.
  254. */
  255. static NSString *const kUnlinkFromEmailPassword = @"Unlink from Email/Password";
  256. /** @var kGetProvidersForEmail
  257. @brief The text of the "Get Provider IDs for Email" button.
  258. */
  259. static NSString *const kGetProvidersForEmail = @"Get Provider IDs for Email";
  260. /** @var kGetAllSignInMethodsForEmail
  261. @brief The text of the "Get sign-in methods for Email" button.
  262. */
  263. static NSString *const kGetAllSignInMethodsForEmail = @"Get Sign-in methods for Email";
  264. /** @var kActionCodeTypeDescription
  265. @brief The description of the "Action Type" entry.
  266. */
  267. static NSString *const kActionCodeTypeDescription = @"Action Type";
  268. /** @var kContinueURLDescription
  269. @brief The description of the "Continue URL" entry.
  270. */
  271. static NSString *const kContinueURLDescription = @"Continue URL";
  272. /** @var kRequestVerifyEmail
  273. @brief The text of the "Request Verify Email Link" button.
  274. */
  275. static NSString *const kRequestVerifyEmail = @"Request Verify Email Link";
  276. /** @var kRequestPasswordReset
  277. @brief The text of the "Email Password Reset" button.
  278. */
  279. static NSString *const kRequestPasswordReset = @"Send Password Reset Email";
  280. /** @var kResetPassword
  281. @brief The text of the "Password Reset" button.
  282. */
  283. static NSString *const kResetPassword = @"Reset Password";
  284. /** @var kCheckActionCode
  285. @brief The text of the "Check action code" button.
  286. */
  287. static NSString *const kCheckActionCode = @"Check action code";
  288. /** @var kApplyActionCode
  289. @brief The text of the "Apply action code" button.
  290. */
  291. static NSString *const kApplyActionCode = @"Apply action code";
  292. /** @var kVerifyPasswordResetCode
  293. @brief The text of the "Verify password reset code" button.
  294. */
  295. static NSString *const kVerifyPasswordResetCode = @"Verify password reset code";
  296. /** @var kSectionTitleSettings
  297. @brief The text for the title of the "Settings" section.
  298. */
  299. static NSString *const kSectionTitleSettings = @"SETTINGS";
  300. /** @var kSectionTitleSignIn
  301. @brief The text for the title of the "Sign-In" section.
  302. */
  303. static NSString *const kSectionTitleSignIn = @"SIGN-IN";
  304. /** @var kSectionTitleReauthenticate
  305. @brief The text for the title of the "Reauthenticate" section.
  306. */
  307. static NSString *const kSectionTitleReauthenticate = @"REAUTHENTICATE";
  308. /** @var kSectionTitleTokenActions
  309. @brief The text for the title of the "Token Actions" section.
  310. */
  311. static NSString *const kSectionTitleTokenActions = @"TOKEN ACTIONS";
  312. /** @var kSectionTitleEditUser
  313. @brief The text for the title of the "Edit User" section.
  314. */
  315. static NSString *const kSectionTitleEditUser = @"EDIT USER";
  316. /** @var kSectionTitleLinkUnlinkAccount
  317. @brief The text for the title of the "Link/Unlink account" section.
  318. */
  319. static NSString *const kSectionTitleLinkUnlinkAccounts = @"LINK/UNLINK ACCOUNT";
  320. /** @var kSectionTitleUserActions
  321. @brief The text for the title of the "User Actions" section.
  322. */
  323. static NSString *const kSectionTitleUserActions = @"USER ACTIONS";
  324. /** @var kSectionTitleOOBAction
  325. @brief The text for the title of the "OOB Actions" section.
  326. */
  327. static NSString *const kSectionTitleOOBActions = @"OOB ACTIONS";
  328. /** @var kSectionTitleUserDetails
  329. @brief The text for the title of the "User Details" section.
  330. */
  331. static NSString *const kSectionTitleUserDetails = @"SIGNED-IN USER DETAILS";
  332. /** @var kSectionTitleListeners
  333. @brief The title for the table view section dedicated to auth state did change listeners.
  334. */
  335. static NSString *const kSectionTitleListeners = @"Listeners";
  336. /** @var kAddAuthStateListenerTitle
  337. @brief The title for the table view row which adds a block to the auth state did change
  338. listeners.
  339. */
  340. static NSString *const kAddAuthStateListenerTitle = @"Add Auth State Change Listener";
  341. /** @var kRemoveAuthStateListenerTitle
  342. @brief The title for the table view row which removes a block to the auth state did change
  343. listeners.
  344. */
  345. static NSString *const kRemoveAuthStateListenerTitle = @"Remove Last Auth State Change Listener";
  346. /** @var kAddIDTokenListenerTitle
  347. @brief The title for the table view row which adds a block to the ID token did change
  348. listeners.
  349. */
  350. static NSString *const kAddIDTokenListenerTitle = @"Add ID Token Change Listener";
  351. /** @var kRemoveIDTokenListenerTitle
  352. @brief The title for the table view row which removes a block to the ID token did change
  353. listeners.
  354. */
  355. static NSString *const kRemoveIDTokenListenerTitle = @"Remove Last ID Token Change Listener";
  356. /** @var kSectionTitleApp
  357. @brief The text for the title of the "App" section.
  358. */
  359. static NSString *const kSectionTitleApp = @"APP";
  360. /** @var kSwitchToInMemoryUserTitle
  361. @brief The text of the "Switch to in memory user" button.
  362. */
  363. static NSString *const kSwitchToInMemoryUserTitle = @"Switch to in memory user";
  364. /** @var kCreateUserTitle
  365. @brief The text of the "Create User" button.
  366. */
  367. static NSString *const kCreateUserTitle = @"Create User";
  368. /** @var kCreateUserAuthDataResultTitle
  369. @brief The text of the "Create User (AuthDataResult)" button.
  370. */
  371. static NSString *const kCreateUserAuthDataResultTitle = @"Create User (AuthDataResult)";
  372. /** @var kDeleteAppTitle
  373. @brief The text of the "Delete App" button.
  374. */
  375. static NSString *const kDeleteAppTitle = @"Delete App";
  376. /** @var kTimeAuthInitTitle
  377. @brief The text of the "Time Auth Initialization" button.
  378. */
  379. static NSString *const kTimeAuthInitTitle = @"Time Auth Initialization";
  380. /** @var kSectionTitleManualTests
  381. @brief The section title for automated manual tests.
  382. */
  383. static NSString *const kSectionTitleManualTests = @"Automated (Manual) Tests";
  384. /** @var kAutoBYOAuthTitle
  385. @brief The button title for automated BYOAuth operation.
  386. */
  387. static NSString *const kAutoBYOAuthTitle = @"BYOAuth";
  388. /** @var kAutoSignInGoogle
  389. @brief The button title for automated Google sign-in operation.
  390. */
  391. static NSString *const kAutoSignInGoogle = @"Sign In With Google";
  392. /** @var kAutoSignInFacebook
  393. @brief The button title for automated Facebook sign-in operation.
  394. */
  395. static NSString *const kAutoSignInFacebook = @"Sign In With Facebook";
  396. /** @var kAutoSignUpEmailPassword
  397. @brief The button title for automated sign-up with email/password.
  398. */
  399. static NSString *const kAutoSignUpEmailPassword = @"Sign Up With Email/Password";
  400. /** @var kAutoSignInAnonymously
  401. @brief The button title for automated sign-in anonymously.
  402. */
  403. static NSString *const kAutoSignInAnonymously = @"Sign In Anonymously";
  404. /** @var kAutoAccountLinking
  405. @brief The button title for automated account linking.
  406. */
  407. static NSString *const kAutoAccountLinking = @"Link with Google";
  408. /** @var kAutoPhoneNumberSignIn
  409. @brief The button title for automated Phone Number sign-in.
  410. */
  411. static NSString *const kAutoPhoneNumberSignIn = @"Sign in With Phone Number";
  412. /** @var kGitHubSignInButtonText
  413. @brief The button title for signing in with github.
  414. */
  415. static NSString *const kGitHubSignInButtonText = @"Sign In with GitHub";
  416. /** @var kExpiredCustomTokenUrl
  417. @brief The url for obtaining a valid custom token string used to test BYOAuth.
  418. */
  419. static NSString *const kCustomTokenUrl = @"https://fb-sa-1211.appspot.com/token";
  420. /** @var kCustomTokenUrl
  421. @brief The url for obtaining an expired custom token string used to test BYOAuth.
  422. */
  423. static NSString *const kExpiredCustomTokenUrl = @"https://fb-sa-1211.appspot.com/expired_token";
  424. /** @var kFakeDisplayPhotoUrl
  425. @brief The url for obtaining a display displayPhoto used for testing.
  426. */
  427. static NSString *const kFakeDisplayPhotoUrl =
  428. @"https://www.gstatic.com/images/branding/product/1x/play_apps_48dp.png";
  429. /** @var kFakeDisplayName
  430. @brief Fake display name for testing.
  431. */
  432. static NSString *const kFakeDisplayName = @"John GoogleSpeed";
  433. /** @var kFakeEmail
  434. @brief Fake email for testing.
  435. */
  436. static NSString *const kFakeEmail =@"firemail@example.com";
  437. /** @var kFakePassword
  438. @brief Fake password for testing.
  439. */
  440. static NSString *const kFakePassword =@"fakePassword";
  441. /** @var kInvalidCustomToken
  442. @brief The custom token string for testing BYOAuth.
  443. */
  444. static NSString *const kInvalidCustomToken = @"invalid custom token.";
  445. /** @var kSafariGoogleSignOutMessagePrompt
  446. @brief The message text informing user to sign-out from Google on safari before continuing.
  447. */
  448. static NSString *const kSafariGoogleSignOutMessagePrompt = @"This automated test assumes that no "
  449. "Google account is signed in on Safari, if your are not prompted for a password, sign out on "
  450. "Safari and rerun the test.";
  451. /** @var kSafariFacebookSignOutMessagePrompt
  452. @brief The message text informing user to sign-out from Facebook on safari before continuing.
  453. */
  454. static NSString *const kSafariFacebookSignOutMessagePrompt = @"This automated test assumes that no "
  455. "Facebook account is signed in on Safari, if your are not prompted for a password, sign out on "
  456. "Safari and rerun the test.";
  457. /** @var kUnlinkAccountMessagePrompt
  458. @brief The message text informing user to use an unlinked account for account linking.
  459. */
  460. static NSString *const kUnlinkAccountMessagePrompt = @"Sign into gmail with an email address "
  461. "that has not been linked to this sample application before. Delete account if necessary.";
  462. /** @var kPasswordResetAction
  463. @brief The value for password reset mode in the action code URL.
  464. */
  465. static NSString *const kPasswordResetAction = @"resetPassword";
  466. /** @var kVerifyEmailAction
  467. @brief The value for verify email mode in the action code URL.
  468. */
  469. static NSString *const kVerifyEmailAction = @"verifyEmail";
  470. // Declared extern in .h file.
  471. NSString *const kCreateUserAccessibilityID = @"CreateUserAccessibilityID";
  472. /** @var kPhoneAuthSectionTitle
  473. @brief The title for the phone auth section of the test app.
  474. */
  475. static NSString *const kPhoneAuthSectionTitle = @"Phone Auth";
  476. /** @var kPhoneNumberSignInTitle
  477. @brief The title for button to sign in with phone number using reCAPTCHA.
  478. */
  479. static NSString *const kPhoneNumberSignInReCaptchaTitle = @"Sign in With Phone Number";
  480. /** @var kVerifyIOSClientTitle
  481. @brief The title for button to verify iOS client.
  482. */
  483. static NSString *const kVerifyIOSClientTitle = @"Verify iOS client";
  484. /** @var kIsNewUserToggleTitle
  485. @brief The title for button to enable new or existing user toggle.
  486. */
  487. static NSString *const kNewOrExistingUserToggleTitle = @"New or Existing User Toggle";
  488. /** @typedef showEmailPasswordDialogCompletion
  489. @brief The type of block which gets called to complete the Email/Password dialog flow.
  490. */
  491. typedef void (^ShowEmailPasswordDialogCompletion)(FIRAuthCredential *credential);
  492. /** @typedef FIRTokenCallback
  493. @brief The type of block which gets called when a token is ready.
  494. */
  495. typedef void (^FIRTokenCallback)(NSString *_Nullable token, NSError *_Nullable error);
  496. /** @brief The request type for OOB action codes.
  497. */
  498. typedef enum {
  499. /** No action code settings. */
  500. ActionCodeRequestTypeEmail,
  501. /** With continue URL but not handled in-app. */
  502. ActionCodeRequestTypeContinue,
  503. /** Handled in-app. */
  504. ActionCodeRequestTypeInApp,
  505. } ActionCodeRequestType;
  506. /** @category FIRAppAssociationRegistration(Deregistration)
  507. @brief The category for the deregistration method.
  508. */
  509. @interface FIRAppAssociationRegistration (Deregistration)
  510. /** @fn deregisteredObjectWithHost:key:
  511. @brief Removes the object that was registered with a particular host and key, if one exists.
  512. @param host The host object.
  513. @param key The key to specify the registered object on the host.
  514. */
  515. + (void)deregisterObjectWithHost:(id)host key:(NSString *)key;
  516. @end
  517. @implementation FIRAppAssociationRegistration (Deregistration)
  518. + (void)deregisterObjectWithHost:(id)host key:(NSString *)key {
  519. @synchronized(self) {
  520. SEL dictKey = @selector(registeredObjectWithHost:key:creationBlock:);
  521. NSMutableDictionary<NSString *, id> *objectsByKey = objc_getAssociatedObject(host, dictKey);
  522. [objectsByKey removeObjectForKey:key];
  523. }
  524. }
  525. @end
  526. @implementation MainViewController {
  527. NSMutableString *_consoleString;
  528. /** @var _authStateDidChangeListeners
  529. @brief An array of handles created during calls to @c FIRAuth.addAuthStateDidChangeListener:
  530. */
  531. NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_authStateDidChangeListeners;
  532. /** @var _IDTokenDidChangeListeners
  533. @brief An array of handles created during calls to @c FIRAuth.addIDTokenDidChangeListener:
  534. */
  535. NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_IDTokenDidChangeListeners;
  536. /** @var _userInMemory
  537. @brief Acts like the "memory" function of a calculator. An operation allows sample app users
  538. to assign this value based on @c FIRAuth.currentUser or clear this value.
  539. */
  540. FIRUser *_userInMemory;
  541. /** @var _useUserInMemory
  542. @brief Instructs the application to use _userInMemory instead of @c FIRAuth.currentUser for
  543. testing operations. This allows us to test if things still work with a user who is not
  544. the @c FIRAuth.currentUser, and also allows us to test those things while
  545. @c FIRAuth.currentUser remains nil (after a sign-out) and also when @c FIRAuth.currentUser
  546. is non-nil (do to a subsequent sign-in.)
  547. */
  548. BOOL _useUserInMemory;
  549. /** @var _newUserToggle
  550. @brief When enabled allows login popup alert determining new or existing user.
  551. */
  552. BOOL _isNewUserToggleOn;
  553. /** @var _actionCodeRequestType
  554. @brief The type for the next action code request.
  555. */
  556. ActionCodeRequestType _actionCodeRequestType;
  557. /** @var _actionCodeContinueURL
  558. @brief The continue URL to be used in the next action code request.
  559. */
  560. NSURL *_actionCodeContinueURL;
  561. }
  562. /** @fn initWithNibName:bundle:
  563. @brief Overridden default initializer.
  564. */
  565. - (id)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil {
  566. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  567. if (self) {
  568. _actionCodeRequestType = ActionCodeRequestTypeInApp;
  569. _actionCodeContinueURL = [NSURL URLWithString:KCONTINUE_URL];
  570. _authStateDidChangeListeners = [NSMutableArray array];
  571. _IDTokenDidChangeListeners = [NSMutableArray array];
  572. [[NSNotificationCenter defaultCenter] addObserver:self
  573. selector:@selector(authStateChangedForAuth:)
  574. name:FIRAuthStateDidChangeNotification
  575. object:nil];
  576. self.useStatusBarSpinner = YES;
  577. }
  578. return self;
  579. }
  580. - (void)viewDidLoad {
  581. // Give us a circle for the image view:
  582. _userInfoTableViewCell.userInfoProfileURLImageView.layer.cornerRadius =
  583. _userInfoTableViewCell.userInfoProfileURLImageView.frame.size.width / 2.0f;
  584. _userInfoTableViewCell.userInfoProfileURLImageView.layer.masksToBounds = YES;
  585. _userInMemoryInfoTableViewCell.userInfoProfileURLImageView.layer.cornerRadius =
  586. _userInMemoryInfoTableViewCell.userInfoProfileURLImageView.frame.size.width / 2.0f;
  587. _userInMemoryInfoTableViewCell.userInfoProfileURLImageView.layer.masksToBounds = YES;
  588. }
  589. - (void)viewWillAppear:(BOOL)animated {
  590. [super viewWillAppear:animated];
  591. [self updateTable];
  592. [self updateUserInfo];
  593. }
  594. - (void)updateTable {
  595. __weak typeof(self) weakSelf = self;
  596. _tableViewManager.contents =
  597. [StaticContentTableViewContent contentWithSections:@[
  598. [StaticContentTableViewSection sectionWithTitle:kSectionTitleUserDetails cells:@[
  599. [StaticContentTableViewCell cellWithCustomCell:_userInfoTableViewCell action:^{
  600. [weakSelf presentUserInfo];
  601. }],
  602. [StaticContentTableViewCell cellWithCustomCell:_userToUseCell],
  603. [StaticContentTableViewCell cellWithCustomCell:_userInMemoryInfoTableViewCell action:^{
  604. [weakSelf presentUserInMemoryInfo];
  605. }],
  606. ]],
  607. [StaticContentTableViewSection sectionWithTitle:kSectionTitleSettings cells:@[
  608. [StaticContentTableViewCell cellWithTitle:NSLocalizedString(@"SETTINGSKEY",
  609. kSettingsButtonTextDesription)
  610. action:^{ [weakSelf presentSettings]; }],
  611. [StaticContentTableViewCell cellWithTitle:kNewOrExistingUserToggleTitle
  612. value:_isNewUserToggleOn ? @"Enabled" : @"Disabled"
  613. action:^{
  614. _isNewUserToggleOn = !_isNewUserToggleOn;
  615. [self updateTable]; }],
  616. ]],
  617. [StaticContentTableViewSection sectionWithTitle:kPhoneAuthSectionTitle cells:@[
  618. [StaticContentTableViewCell cellWithTitle:kPhoneNumberSignInReCaptchaTitle
  619. action:^{ [weakSelf signInWithPhoneNumberWithPrompt]; }],
  620. [StaticContentTableViewCell cellWithTitle:kUpdatePhoneNumber
  621. action:^{ [weakSelf updatePhoneNumberWithPrompt]; }],
  622. [StaticContentTableViewCell cellWithTitle:kLinkPhoneNumber
  623. action:^{ [weakSelf linkPhoneNumberWithPrompt]; }],
  624. [StaticContentTableViewCell cellWithTitle:kUnlinkPhoneNumber
  625. action:^{
  626. [weakSelf unlinkFromProvider:FIRPhoneAuthProviderID completion:nil];
  627. }],
  628. [StaticContentTableViewCell cellWithTitle:kVerifyIOSClientTitle
  629. action:^{ [weakSelf verifyIOSClient]; }],
  630. ]],
  631. [StaticContentTableViewSection sectionWithTitle:kSectionTitleSignIn cells:@[
  632. [StaticContentTableViewCell cellWithTitle:kSwitchToInMemoryUserTitle
  633. value:nil
  634. action:^{ [weakSelf updateToSavedUser]; }],
  635. [StaticContentTableViewCell cellWithTitle:kCreateUserTitle
  636. value:nil
  637. action:^{ [weakSelf createUser]; }
  638. accessibilityID:kCreateUserAccessibilityID],
  639. [StaticContentTableViewCell cellWithTitle:kCreateUserAuthDataResultTitle
  640. action:^{ [weakSelf createUserAuthDataResult]; }],
  641. [StaticContentTableViewCell cellWithTitle:kSignInGoogleButtonText
  642. action:^{ [weakSelf signInGoogle]; }],
  643. [StaticContentTableViewCell cellWithTitle:kSignInWithEmailLink
  644. action:^{ [weakSelf signInWithEmailLink]; }],
  645. [StaticContentTableViewCell cellWithTitle:kVerifyEmailLinkAccount
  646. action:^{ [weakSelf verifyEmailLinkAccount]; }],
  647. [StaticContentTableViewCell cellWithTitle:kSendEmailSignInLink
  648. action:^{ [weakSelf sendEmailSignInLink]; }],
  649. [StaticContentTableViewCell cellWithTitle:kSignInGoogleAndRetrieveDataButtonText
  650. action:^{ [weakSelf signInGoogleAndRetrieveData]; }],
  651. [StaticContentTableViewCell cellWithTitle:kSignInFacebookButtonText
  652. action:^{ [weakSelf signInFacebook]; }],
  653. [StaticContentTableViewCell cellWithTitle:kSignInFacebookAndRetrieveDataButtonText
  654. action:^{ [weakSelf signInFacebookAndRetrieveData]; }],
  655. [StaticContentTableViewCell cellWithTitle:kSignInEmailPasswordButtonText
  656. action:^{ [weakSelf signInEmailPassword]; }],
  657. [StaticContentTableViewCell cellWithTitle:kSignInEmailPasswordAuthDataResultButtonText
  658. action:^{ [weakSelf signInEmailPasswordAuthDataResult]; }],
  659. [StaticContentTableViewCell cellWithTitle:kSignInWithCustomTokenButtonText
  660. action:^{ [weakSelf signInWithCustomToken]; }],
  661. [StaticContentTableViewCell cellWithTitle:kSignInWithCustomAuthResultTokenButtonText
  662. action:^{ [weakSelf signInWithCustomTokenAuthResult]; }],
  663. [StaticContentTableViewCell cellWithTitle:kSignInAnonymouslyButtonText
  664. action:^{ [weakSelf signInAnonymously]; }],
  665. [StaticContentTableViewCell cellWithTitle:kSignInAnonymouslyWithAuthResultButtonText
  666. action:^{ [weakSelf signInAnonymouslyAuthDataResult]; }],
  667. [StaticContentTableViewCell cellWithTitle:kGitHubSignInButtonText
  668. action:^{ [weakSelf signInWithGitHub]; }],
  669. [StaticContentTableViewCell cellWithTitle:kSignOutButtonText
  670. action:^{ [weakSelf signOut]; }]
  671. ]],
  672. [StaticContentTableViewSection sectionWithTitle:kSectionTitleUserActions cells:@[
  673. [StaticContentTableViewCell cellWithTitle:kSetDisplayNameTitle
  674. action:^{ [weakSelf setDisplayName]; }],
  675. [StaticContentTableViewCell cellWithTitle:kSetPhotoURLText
  676. action:^{ [weakSelf setPhotoURL]; }],
  677. [StaticContentTableViewCell cellWithTitle:kReloadText
  678. action:^{ [weakSelf reloadUser]; }],
  679. [StaticContentTableViewCell cellWithTitle:kGetProvidersForEmail
  680. action:^{ [weakSelf getProvidersForEmail]; }],
  681. [StaticContentTableViewCell cellWithTitle:kGetAllSignInMethodsForEmail
  682. action:^{ [weakSelf getAllSignInMethodsForEmail]; }],
  683. [StaticContentTableViewCell cellWithTitle:kUpdateEmailText
  684. action:^{ [weakSelf updateEmail]; }],
  685. [StaticContentTableViewCell cellWithTitle:kUpdatePasswordText
  686. action:^{ [weakSelf updatePassword]; }],
  687. [StaticContentTableViewCell cellWithTitle:kDeleteUserText
  688. action:^{ [weakSelf deleteAccount]; }],
  689. ]],
  690. [StaticContentTableViewSection sectionWithTitle:kSectionTitleOOBActions cells:@[
  691. [StaticContentTableViewCell cellWithTitle:kActionCodeTypeDescription
  692. value:[self actionCodeRequestTypeString]
  693. action:^{ [weakSelf toggleActionCodeRequestType]; }],
  694. [StaticContentTableViewCell cellWithTitle:kContinueURLDescription
  695. value:_actionCodeContinueURL.absoluteString ?: @"(nil)"
  696. action:^{ [weakSelf changeActionCodeContinueURL]; }],
  697. [StaticContentTableViewCell cellWithTitle:kRequestVerifyEmail
  698. action:^{ [weakSelf requestVerifyEmail]; }],
  699. [StaticContentTableViewCell cellWithTitle:kRequestPasswordReset
  700. action:^{ [weakSelf requestPasswordReset]; }],
  701. [StaticContentTableViewCell cellWithTitle:kResetPassword
  702. action:^{ [weakSelf resetPassword]; }],
  703. [StaticContentTableViewCell cellWithTitle:kCheckActionCode
  704. action:^{ [weakSelf checkActionCode]; }],
  705. [StaticContentTableViewCell cellWithTitle:kApplyActionCode
  706. action:^{ [weakSelf applyActionCode]; }],
  707. [StaticContentTableViewCell cellWithTitle:kVerifyPasswordResetCode
  708. action:^{ [weakSelf verifyPasswordResetCode]; }],
  709. ]],
  710. [StaticContentTableViewSection sectionWithTitle:kSectionTitleReauthenticate cells:@[
  711. [StaticContentTableViewCell cellWithTitle:kReauthenticateGoogleText
  712. action:^{ [weakSelf reauthenticateGoogle]; }],
  713. [StaticContentTableViewCell
  714. cellWithTitle:kReauthenticateGoogleAndRetrieveDataText
  715. action:^{ [weakSelf reauthenticateGoogleAndRetrieveData]; }],
  716. [StaticContentTableViewCell cellWithTitle:kReauthenticateFBText
  717. action:^{ [weakSelf reauthenticateFB]; }],
  718. [StaticContentTableViewCell cellWithTitle:kReauthenticateFBAndRetrieveDataText
  719. action:^{ [weakSelf reauthenticateFBAndRetrieveData]; }],
  720. [StaticContentTableViewCell cellWithTitle:kReauthenticateEmailText
  721. action:^{ [weakSelf reauthenticateEmailPassword]; }]
  722. ]],
  723. [StaticContentTableViewSection sectionWithTitle:kSectionTitleTokenActions cells:@[
  724. [StaticContentTableViewCell cellWithTitle:kTokenGetButtonText
  725. action:^{ [weakSelf getUserTokenWithForce:NO]; }],
  726. [StaticContentTableViewCell cellWithTitle:kTokenRefreshButtonText
  727. action:^{ [weakSelf getUserTokenWithForce:YES]; }],
  728. [StaticContentTableViewCell cellWithTitle:kGetTokenResultButtonText
  729. action:^{ [weakSelf getUserTokenResultWithForce:NO]; }],
  730. [StaticContentTableViewCell cellWithTitle:kGetTokenResultForceButtonText
  731. action:^{ [weakSelf getUserTokenResultWithForce:YES]; }],
  732. ]],
  733. [StaticContentTableViewSection sectionWithTitle:kSectionTitleLinkUnlinkAccounts cells:@[
  734. [StaticContentTableViewCell cellWithTitle:kLinkWithGoogleText
  735. action:^{ [weakSelf linkWithGoogle]; }],
  736. [StaticContentTableViewCell cellWithTitle:kLinkWithGoogleAndRetrieveDataText
  737. action:^{ [weakSelf linkWithGoogleAndRetrieveData]; }],
  738. [StaticContentTableViewCell cellWithTitle:kLinkWithFacebookText
  739. action:^{ [weakSelf linkWithFacebook]; }],
  740. [StaticContentTableViewCell cellWithTitle:kLinkWithFacebookAndRetrieveDataText
  741. action:^{ [weakSelf linkWithFacebookAndRetrieveData]; }],
  742. [StaticContentTableViewCell cellWithTitle:kLinkWithEmailPasswordText
  743. action:^{ [weakSelf linkWithEmailPassword]; }],
  744. [StaticContentTableViewCell cellWithTitle:kUnlinkFromGoogle
  745. action:^{
  746. [weakSelf unlinkFromProvider:FIRGoogleAuthProviderID completion:nil];
  747. }],
  748. [StaticContentTableViewCell cellWithTitle:kUnlinkFromFacebook
  749. action:^{
  750. [weakSelf unlinkFromProvider:FIRFacebookAuthProviderID completion:nil];
  751. }],
  752. [StaticContentTableViewCell cellWithTitle:kUnlinkFromEmailPassword
  753. action:^{
  754. [weakSelf unlinkFromProvider:FIREmailAuthProviderID completion:nil];
  755. }]
  756. ]],
  757. [StaticContentTableViewSection sectionWithTitle:kSectionTitleApp cells:@[
  758. [StaticContentTableViewCell cellWithTitle:kDeleteAppTitle
  759. action:^{ [weakSelf deleteApp]; }],
  760. [StaticContentTableViewCell cellWithTitle:kTokenGetButtonText
  761. action:^{ [weakSelf getAppTokenWithForce:NO]; }],
  762. [StaticContentTableViewCell cellWithTitle:kTokenRefreshButtonText
  763. action:^{ [weakSelf getAppTokenWithForce:YES]; }],
  764. [StaticContentTableViewCell cellWithTitle:kTimeAuthInitTitle
  765. action:^{ [weakSelf timeAuthInitialization]; }]
  766. ]],
  767. [StaticContentTableViewSection sectionWithTitle:kSectionTitleListeners cells:@[
  768. [StaticContentTableViewCell cellWithTitle:kAddAuthStateListenerTitle
  769. action:^{ [weakSelf addAuthStateListener]; }],
  770. [StaticContentTableViewCell cellWithTitle:kRemoveAuthStateListenerTitle
  771. action:^{ [weakSelf removeAuthStateListener]; }],
  772. [StaticContentTableViewCell cellWithTitle:kAddIDTokenListenerTitle
  773. action:^{ [weakSelf addIDTokenListener]; }],
  774. [StaticContentTableViewCell cellWithTitle:kRemoveIDTokenListenerTitle
  775. action:^{ [weakSelf removeIDTokenListener]; }],
  776. ]],
  777. [StaticContentTableViewSection sectionWithTitle:kSectionTitleManualTests cells:@[
  778. [StaticContentTableViewCell cellWithTitle:kAutoBYOAuthTitle
  779. action:^{ [weakSelf automatedBYOAuth]; }],
  780. [StaticContentTableViewCell cellWithTitle:kAutoSignInGoogle
  781. action:^{ [weakSelf automatedSignInGoogle]; }],
  782. [StaticContentTableViewCell cellWithTitle:kAutoSignInFacebook
  783. action:^{ [weakSelf automatedSignInFacebook]; }],
  784. [StaticContentTableViewCell cellWithTitle:kAutoSignUpEmailPassword
  785. action:^{ [weakSelf automatedEmailSignUp]; }],
  786. [StaticContentTableViewCell cellWithTitle:kAutoSignInAnonymously
  787. action:^{ [weakSelf automatedAnonymousSignIn]; }],
  788. [StaticContentTableViewCell cellWithTitle:kAutoAccountLinking
  789. action:^{ [weakSelf automatedAccountLinking]; }],
  790. [StaticContentTableViewCell cellWithTitle:kAutoPhoneNumberSignIn
  791. action:^{ [weakSelf automatedPhoneNumberSignIn]; }]
  792. ]]
  793. ]];
  794. }
  795. #pragma mark - Interface Builder Actions
  796. - (IBAction)userToUseDidChange:(UISegmentedControl *)sender {
  797. _useUserInMemory = (sender.selectedSegmentIndex == 1);
  798. }
  799. - (IBAction)memoryPlus {
  800. _userInMemory = [AppManager auth].currentUser;
  801. [self updateUserInfo];
  802. }
  803. - (IBAction)memoryClear {
  804. _userInMemory = nil;
  805. [self updateUserInfo];
  806. }
  807. /** @fn parseURL
  808. @brief Parses an incoming URL into all available query items.
  809. @param urlString The url to be parsed.
  810. @return A dictionary of available query items in the target URL.
  811. */
  812. static NSDictionary<NSString *, NSString *> *parseURL(NSString *urlString) {
  813. NSString *linkURL = [NSURLComponents componentsWithString:urlString].query;
  814. NSArray<NSString *> *URLComponents = [linkURL componentsSeparatedByString:@"&"];
  815. NSMutableDictionary<NSString *, NSString *> *queryItems =
  816. [[NSMutableDictionary alloc] initWithCapacity:URLComponents.count];
  817. for (NSString *component in URLComponents) {
  818. NSRange equalRange = [component rangeOfString:@"="];
  819. if (equalRange.location != NSNotFound) {
  820. NSString *queryItemKey =
  821. [[component substringToIndex:equalRange.location] stringByRemovingPercentEncoding];
  822. NSString *queryItemValue =
  823. [[component substringFromIndex:equalRange.location + 1] stringByRemovingPercentEncoding];
  824. if (queryItemKey && queryItemValue) {
  825. queryItems[queryItemKey] = queryItemValue;
  826. }
  827. }
  828. }
  829. return queryItems;
  830. }
  831. #pragma mark public methods
  832. - (BOOL)handleIncomingLinkWithURL:(NSURL *)URL {
  833. // Parse the query portion of the incoming URL.
  834. NSDictionary<NSString *, NSString *> *queryItems =
  835. parseURL([NSURLComponents componentsWithString:URL.absoluteString].query);
  836. // Check that all necessary query items are available.
  837. NSString *actionCode = queryItems[@"oobCode"];
  838. NSString *mode = queryItems[@"mode"];
  839. if (!actionCode || !mode) {
  840. return NO;
  841. }
  842. // Handle Password Reset action.
  843. if ([mode isEqualToString:kPasswordResetAction]) {
  844. [self showTextInputPromptWithMessage:@"New Password:"
  845. completionBlock:^(BOOL userPressedOK, NSString *_Nullable newPassword) {
  846. if (!userPressedOK || !newPassword.length) {
  847. [UIPasteboard generalPasteboard].string = actionCode;
  848. return;
  849. }
  850. [self showSpinner:^() {
  851. [[AppManager auth] confirmPasswordResetWithCode:actionCode
  852. newPassword:newPassword
  853. completion:^(NSError *_Nullable error) {
  854. [self hideSpinner:^{
  855. if (error) {
  856. [self logFailure:@"Password reset in app failed" error:error];
  857. [self showMessagePrompt:error.localizedDescription];
  858. return;
  859. }
  860. [self logSuccess:@"Password reset in app succeeded."];
  861. [self showMessagePrompt:@"Password reset in app succeeded."];
  862. }];
  863. }];
  864. }];
  865. }];
  866. return YES;
  867. }
  868. if ([mode isEqualToString:kVerifyEmailAction]) {
  869. [self showMessagePromptWithTitle:@"Tap OK to verify email"
  870. message:actionCode
  871. showCancelButton:YES
  872. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  873. if (!userPressedOK) {
  874. return;
  875. }
  876. [self showSpinner:^() {
  877. [[AppManager auth] applyActionCode:actionCode completion:^(NSError *_Nullable error) {
  878. [self hideSpinner:^{
  879. if (error) {
  880. [self logFailure:@"Verify email in app failed" error:error];
  881. [self showMessagePrompt:error.localizedDescription];
  882. return;
  883. }
  884. [self logSuccess:@"Verify email in app succeeded."];
  885. [self showMessagePrompt:@"Verify email in app succeeded."];
  886. }];
  887. }];
  888. }];
  889. }];
  890. return YES;
  891. }
  892. return NO;
  893. }
  894. #pragma mark - Actions
  895. /** @fn signInWithProvider:provider:
  896. @brief Perform sign in with credential operataion, for given auth provider.
  897. @param provider The auth provider.
  898. @param callback The callback to continue the flow which executed this sign-in.
  899. */
  900. - (void)signInWithProvider:(nonnull id<AuthProvider>)provider callback:(void(^)(void))callback {
  901. if (!provider) {
  902. [self logFailedTest:@"A valid auth provider was not provided to the signInWithProvider."];
  903. return;
  904. }
  905. [provider getAuthCredentialWithPresentingViewController:self
  906. callback:^(FIRAuthCredential *credential,
  907. NSError *error) {
  908. if (!credential) {
  909. [self logFailedTest:@"The test needs a valid credential to continue."];
  910. return;
  911. }
  912. [[AppManager auth] signInWithCredential:credential completion:^(FIRUser *_Nullable user,
  913. NSError *_Nullable error) {
  914. if (error) {
  915. [self logFailure:@"sign-in with provider failed" error:error];
  916. [self logFailedTest:@"Sign-in should succeed"];
  917. return;
  918. } else {
  919. [self logSuccess:@"sign-in with provider succeeded."];
  920. callback();
  921. }
  922. }];
  923. }];
  924. }
  925. /** @fn automatedSignInGoogle
  926. @brief Automatically executes the manual test for sign-in with Google.
  927. */
  928. - (void)automatedSignInGoogle {
  929. [self showMessagePromptWithTitle:kAutoSignInGoogle
  930. message:kSafariGoogleSignOutMessagePrompt
  931. showCancelButton:NO
  932. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  933. FIRAuth *auth = [AppManager auth];
  934. if (!auth) {
  935. [self logFailedTest:@"Could not obtain auth object."];
  936. return;
  937. }
  938. [auth signOut:NULL];
  939. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR GOOGLE SIGN IN:"];
  940. [self signInWithProvider:[AuthProviders google] callback:^{
  941. [self logSuccess:@"sign-in with Google provider succeeded."];
  942. [auth signOut:NULL];
  943. [self signInWithProvider:[AuthProviders google] callback:^{
  944. [self logSuccess:@"sign-in with Google provider succeeded."];
  945. [self updateEmailPasswordWithCompletion:^{
  946. [self automatedSignInGoogleDisplayNamePhotoURL];
  947. }];
  948. }];
  949. }];
  950. }];
  951. }
  952. /** @fn automatedSignInGoogleDisplayNamePhotoURL
  953. @brief Automatically executes the manual test for setting email and password for sign in with
  954. Google.
  955. */
  956. - (void)automatedSignInGoogleDisplayNamePhotoURL {
  957. [self signInWithProvider:[AuthProviders google] callback:^{
  958. [self updateDisplayNameAndPhotoURlWithCompletion:^{
  959. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR SIGN-IN WITH GOOGlE."];
  960. [self reloadUser];
  961. }];
  962. }];
  963. }
  964. /** @fn automatedSignInFacebook
  965. @brief Automatically executes the manual test for sign-in with Facebook.
  966. */
  967. - (void)automatedSignInFacebook {
  968. [self showMessagePromptWithTitle:kAutoSignInFacebook
  969. message:kSafariFacebookSignOutMessagePrompt
  970. showCancelButton:NO
  971. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  972. FIRAuth *auth = [AppManager auth];
  973. if (!auth) {
  974. [self logFailedTest:@"Could not obtain auth object."];
  975. return;
  976. }
  977. [auth signOut:NULL];
  978. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR FACEBOOK SIGN IN:"];
  979. [self signInWithProvider:[AuthProviders facebook] callback:^{
  980. [self logSuccess:@"sign-in with Facebook provider succeeded."];
  981. [auth signOut:NULL];
  982. [self signInWithProvider:[AuthProviders facebook] callback:^{
  983. [self logSuccess:@"sign-in with Facebook provider succeeded."];
  984. [self updateEmailPasswordWithCompletion:^{
  985. [self automatedSignInFacebookDisplayNamePhotoURL];
  986. }];
  987. }];
  988. }];
  989. }];
  990. }
  991. /** @fn automatedPhoneNumberSignIn
  992. @brief Automatically executes the manual test for sign-in with phone number.
  993. */
  994. - (void)automatedPhoneNumberSignIn {
  995. [self log:@"Automated phone number sign in"];
  996. FIRAuth *auth = [AppManager auth];
  997. if (!auth) {
  998. [self logFailedTest:@"Could not obtain auth object."];
  999. return;
  1000. }
  1001. [auth signOut:NULL];
  1002. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR PHONE NUMBER SIGN IN:"];
  1003. [self commonPhoneNumberInputWithTitle:@"Phone for automation"
  1004. Completion:^(NSString *_Nullable phone) {
  1005. [self signInWithPhoneNumber:phone completion:^(NSError *error) {
  1006. if (error) {
  1007. [self logFailedTest:@"Could not sign in with phone number reCAPTCHA."];
  1008. }
  1009. [self logSuccess:@"sign-in with phone number reCAPTCHA test succeeded."];
  1010. [auth signOut:NULL];
  1011. [self signInWithPhoneNumber:phone completion:^(NSError *error) {
  1012. if (error) {
  1013. [self logFailedTest:@"Could not sign in with phone number reCAPTCHA."];
  1014. }
  1015. [self logSuccess:@"second sign-in with phone number reCAPTCHA test succeeded."];
  1016. [self updatePhoneNumber:phone completion:^(NSError *error) {
  1017. if (error) {
  1018. [self logFailedTest:@"Could not update phone number."];
  1019. }
  1020. [self logSuccess:@"update phone number test succeeded."];
  1021. [self unlinkFromProvider:FIRPhoneAuthProviderID completion:^(NSError *error) {
  1022. if (error) {
  1023. [self logFailedTest:@"Could not unlink phone number."];
  1024. }
  1025. [self logSuccess:@"unlink phone number test succeeded."];
  1026. [self linkPhoneNumber:phone completion:^(NSError *error) {
  1027. if (error) {
  1028. [self logFailedTest:@"Could not link phone number."];
  1029. }
  1030. [self logSuccess:@"link phone number test succeeded."];
  1031. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR PHONE NUMBER SIGN IN."];
  1032. }];
  1033. }];
  1034. }];
  1035. }];
  1036. }];
  1037. }];
  1038. }
  1039. /** @fn automatedEmailSignUp
  1040. @brief Automatically executes the manual test for sign-up with email/password.
  1041. */
  1042. - (void)automatedEmailSignUp {
  1043. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR FACEBOOK SIGN IN:"];
  1044. FIRAuth *auth = [AppManager auth];
  1045. if (!auth) {
  1046. [self logFailedTest:@"Could not obtain auth object."];
  1047. return;
  1048. }
  1049. [self signUpNewEmail:kFakeEmail password:kFakePassword callback:^(FIRUser *_Nullable user,
  1050. NSError *_Nullable error) {
  1051. if (error) {
  1052. [self logFailedTest: @" Email/Password Account account creation failed"];
  1053. return;
  1054. }
  1055. [auth signOut:NULL];
  1056. FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:kFakeEmail
  1057. password:kFakePassword];
  1058. [auth signInWithCredential:credential
  1059. completion:^(FIRUser *_Nullable user,
  1060. NSError *_Nullable error) {
  1061. if (error) {
  1062. [self logFailure:@"sign-in with Email/Password failed" error:error];
  1063. [self logFailedTest:@"sign-in with Email/Password should succeed."];
  1064. return;
  1065. }
  1066. [self logSuccess:@"sign-in with Email/Password succeeded."];
  1067. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR SIGN-IN WITH EMAIL/PASSWORD."];
  1068. // Delete the user so that we can reuse the fake email address for subsequent tests.
  1069. [auth.currentUser deleteWithCompletion:^(NSError *_Nullable error) {
  1070. if (error) {
  1071. [self logFailure:@"Failed to delete user" error:error];
  1072. [self logFailedTest:@"Deleting a user that was recently signed-in should succeed."];
  1073. return;
  1074. }
  1075. [self logSuccess:@"User deleted."];
  1076. }];
  1077. }];
  1078. }];
  1079. }
  1080. /** @fn automatedAnonymousSignIn
  1081. @brief Automatically executes the manual test for sign-in anonymously.
  1082. */
  1083. - (void)automatedAnonymousSignIn {
  1084. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR ANONYMOUS SIGN IN:"];
  1085. FIRAuth *auth = [AppManager auth];
  1086. if (!auth) {
  1087. [self logFailedTest:@"Could not obtain auth object."];
  1088. return;
  1089. }
  1090. [auth signOut:NULL];
  1091. [self signInAnonymouslyWithCallback:^(FIRAuthDataResult *_Nullable result,
  1092. NSError *_Nullable error) {
  1093. if (result.user) {
  1094. NSString *anonymousUID = result.user.uid;
  1095. [self signInAnonymouslyWithCallback:^(FIRAuthDataResult *_Nullable user,
  1096. NSError *_Nullable error) {
  1097. if (![result.user.uid isEqual:anonymousUID]) {
  1098. [self logFailedTest:@"Consecutive anonymous sign-ins should yeild the same User ID"];
  1099. return;
  1100. }
  1101. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR ANONYMOUS SIGN IN."];
  1102. }];
  1103. }
  1104. }];
  1105. }
  1106. /** @fn signInAnonymouslyWithCallback:
  1107. @brief Performs anonymous sign in and then executes callback.
  1108. @param callback The callback to be executed.
  1109. */
  1110. - (void)signInAnonymouslyWithCallback:(nullable FIRAuthDataResultCallback)callback {
  1111. FIRAuth *auth = [AppManager auth];
  1112. if (!auth) {
  1113. [self logFailedTest:@"Could not obtain auth object."];
  1114. return;
  1115. }
  1116. [auth signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1117. NSError *_Nullable error) {
  1118. if (error) {
  1119. [self logFailure:@"sign-in anonymously failed" error:error];
  1120. [self logFailedTest:@"Recently signed out user should be able to sign in anonymously."];
  1121. return;
  1122. }
  1123. [self logSuccess:@"sign-in anonymously succeeded."];
  1124. if (callback) {
  1125. callback(result, nil);
  1126. }
  1127. }];
  1128. }
  1129. /** @fn automatedAccountLinking
  1130. @brief Automatically executes the manual test for account linking.
  1131. */
  1132. - (void)automatedAccountLinking {
  1133. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR ACCOUNT LINKING:"];
  1134. FIRAuth *auth = [AppManager auth];
  1135. if (!auth) {
  1136. [self logFailedTest:@"Could not obtain auth object."];
  1137. return;
  1138. }
  1139. [auth signOut:NULL];
  1140. [self signInAnonymouslyWithCallback:^(FIRAuthDataResult *_Nullable result,
  1141. NSError *_Nullable error) {
  1142. if (result.user) {
  1143. NSString *anonymousUID = result.user.uid;
  1144. [self showMessagePromptWithTitle:@"Sign In Instructions"
  1145. message:kUnlinkAccountMessagePrompt
  1146. showCancelButton:NO
  1147. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  1148. [[AuthProviders google]
  1149. getAuthCredentialWithPresentingViewController:self
  1150. callback:^(FIRAuthCredential *credential,
  1151. NSError *error) {
  1152. if (credential) {
  1153. [result.user linkWithCredential:credential completion:^(FIRUser *user,
  1154. NSError *error) {
  1155. if (error) {
  1156. [self logFailure:@"link auth provider failed" error:error];
  1157. [self logFailedTest:@"Account needs to be linked to complete the test."];
  1158. return;
  1159. }
  1160. [self logSuccess:@"link auth provider succeeded."];
  1161. if (user.isAnonymous) {
  1162. [self logFailure:@"link auth provider failed, user still anonymous" error:error];
  1163. [self logFailedTest:@"Account needs to be linked to complete the test."];
  1164. }
  1165. if (![user.uid isEqual:anonymousUID]){
  1166. [self logFailedTest:@"link auth provider failed, UID's are different. Make sure "
  1167. "you link an account that has NOT been Linked nor Signed-In before."];
  1168. return;
  1169. }
  1170. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR ACCOUNT LINKING."];
  1171. }];
  1172. }
  1173. }];
  1174. }];
  1175. }
  1176. }];
  1177. }
  1178. /** @fn automatedSignInFacebookDisplayNamePhotoURL
  1179. @brief Automatically executes the manual test for setting email and password for sign-in with
  1180. Facebook.
  1181. */
  1182. - (void)automatedSignInFacebookDisplayNamePhotoURL {
  1183. [self signInWithProvider:[AuthProviders facebook] callback:^{
  1184. [self updateDisplayNameAndPhotoURlWithCompletion:^{
  1185. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR SIGN-IN WITH FACEBOOK."];
  1186. [self reloadUser];
  1187. }];
  1188. }];
  1189. }
  1190. /** @fn automatedBYOauth
  1191. @brief Automatically executes the manual test for BYOAuth.
  1192. */
  1193. - (void)automatedBYOAuth {
  1194. [self log:@"INITIATING AUTOMATED MANUAL TEST FOR BYOAUTH:"];
  1195. [self showSpinner:^{
  1196. NSError *error;
  1197. NSString *customToken = [NSString stringWithContentsOfURL:[NSURL URLWithString:kCustomTokenUrl]
  1198. encoding:NSUTF8StringEncoding
  1199. error:&error];
  1200. NSString *expiredCustomToken =
  1201. [NSString stringWithContentsOfURL:[NSURL URLWithString:kExpiredCustomTokenUrl]
  1202. encoding:NSUTF8StringEncoding
  1203. error:&error];
  1204. [self hideSpinner:^{
  1205. if (error) {
  1206. [self log:@"There was an error retrieving the custom token."];
  1207. return;
  1208. }
  1209. FIRAuth *auth = [AppManager auth];
  1210. [auth signInWithCustomToken:customToken
  1211. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1212. if (error) {
  1213. [self logFailure:@"sign-in with custom token failed" error:error];
  1214. [self logFailedTest:@"A fresh custom token should succeed in signing-in."];
  1215. return;
  1216. }
  1217. [self logSuccess:@"sign-in with custom token succeeded."];
  1218. [auth.currentUser getIDTokenForcingRefresh:NO
  1219. completion:^(NSString *_Nullable token,
  1220. NSError *_Nullable error) {
  1221. if (error) {
  1222. [self logFailure:@"refresh token failed" error:error];
  1223. [self logFailedTest:@"Refresh token should be available."];
  1224. return;
  1225. }
  1226. [self logSuccess:@"refresh token succeeded."];
  1227. [auth signOut:NULL];
  1228. [auth signInWithCustomToken:expiredCustomToken
  1229. completion:^(FIRAuthDataResult *_Nullable result,
  1230. NSError *_Nullable error) {
  1231. if (!error) {
  1232. [self logSuccess:@"sign-in with custom token succeeded."];
  1233. [self logFailedTest:@"sign-in with an expired custom token should NOT succeed."];
  1234. return;
  1235. }
  1236. [self logFailure:@"sign-in with custom token failed" error:error];
  1237. [auth signInWithCustomToken:kInvalidCustomToken
  1238. completion:^(FIRAuthDataResult *_Nullable result,
  1239. NSError *_Nullable error) {
  1240. if (!error) {
  1241. [self logSuccess:@"sign-in with custom token succeeded."];
  1242. [self logFailedTest:@"sign-in with an invalid custom token should NOT succeed."];
  1243. return;
  1244. }
  1245. [self logFailure:@"sign-in with custom token failed" error:error];
  1246. //next step of automated test.
  1247. [self automatedBYOAuthEmailPassword];
  1248. }];
  1249. }];
  1250. }];
  1251. }];
  1252. }];
  1253. }];
  1254. }
  1255. /** @fn automatedBYOAuthEmailPassword
  1256. @brief Automatically executes the manual test for setting email and password in BYOAuth.
  1257. */
  1258. - (void)automatedBYOAuthEmailPassword {
  1259. [self showSpinner:^{
  1260. NSError *error;
  1261. NSString *customToken = [NSString stringWithContentsOfURL:[NSURL URLWithString:kCustomTokenUrl]
  1262. encoding:NSUTF8StringEncoding
  1263. error:&error];
  1264. [self hideSpinner:^{
  1265. if (error) {
  1266. [self log:@"There was an error retrieving the custom token."];
  1267. return;
  1268. }
  1269. [[AppManager auth] signInWithCustomToken:customToken
  1270. completion:^(FIRAuthDataResult *_Nullable user,
  1271. NSError *_Nullable error) {
  1272. if (error) {
  1273. [self logFailure:@"sign-in with custom token failed" error:error];
  1274. [self logFailedTest:@"A fresh custom token should succeed in signing-in."];
  1275. return;
  1276. }
  1277. [self logSuccess:@"sign-in with custom token succeeded."];
  1278. [self updateEmailPasswordWithCompletion:^{
  1279. [self automatedBYOAuthDisplayNameAndPhotoURl];
  1280. }];
  1281. }];
  1282. }];
  1283. }];
  1284. }
  1285. /** @fn automatedBYOAuthDisplayNameAndPhotoURl
  1286. @brief Automatically executes the manual test for setting display name and photo url in BYOAuth.
  1287. */
  1288. - (void)automatedBYOAuthDisplayNameAndPhotoURl {
  1289. [self showSpinner:^{
  1290. NSError *error;
  1291. NSString *customToken = [NSString stringWithContentsOfURL:[NSURL URLWithString:kCustomTokenUrl]
  1292. encoding:NSUTF8StringEncoding
  1293. error:&error];
  1294. [self hideSpinner:^{
  1295. if (error) {
  1296. [self log:@"There was an error retrieving the custom token."];
  1297. return;
  1298. }
  1299. [[AppManager auth] signInWithCustomToken:customToken
  1300. completion:^(FIRAuthDataResult *_Nullable result,
  1301. NSError *_Nullable error) {
  1302. if (error) {
  1303. [self logFailure:@"sign-in with custom token failed" error:error];
  1304. [self logFailedTest:@"A fresh custom token should succeed in signing-in."];
  1305. return;
  1306. }
  1307. [self logSuccess:@"sign-in with custom token succeeded."];
  1308. [self updateDisplayNameAndPhotoURlWithCompletion:^{
  1309. [self log:@"FINISHED AUTOMATED MANUAL TEST FOR BYOAUTH."];
  1310. [self reloadUser];
  1311. }];
  1312. }];
  1313. }];
  1314. }];
  1315. }
  1316. /** @fn updateEmailPasswordWithCompletion:
  1317. @brief Updates email and password for automatic manual tests, and signs user in with new email
  1318. and password.
  1319. @param completion The completion block to continue the automatic test flow.
  1320. */
  1321. - (void)updateEmailPasswordWithCompletion:(void(^)(void))completion {
  1322. FIRAuth *auth = [AppManager auth];
  1323. [auth.currentUser updateEmail:kFakeEmail completion:^(NSError *_Nullable error) {
  1324. if (error) {
  1325. [self logFailure:@"update email failed" error:error];
  1326. [self logFailedTest:@"Update email should succeed when properly signed-in."];
  1327. return;
  1328. }
  1329. [self logSuccess:@"update email succeeded."];
  1330. [auth.currentUser updatePassword:kFakePassword completion:^(NSError *_Nullable error) {
  1331. if (error) {
  1332. [self logFailure:@"update password failed" error:error];
  1333. [self logFailedTest:@"Update password should succeed when properly signed-in."];
  1334. return;
  1335. }
  1336. [self logSuccess:@"update password succeeded."];
  1337. [auth signOut:NULL];
  1338. FIRAuthCredential *credential =
  1339. [FIREmailAuthProvider credentialWithEmail:kFakeEmail password:kFakePassword];
  1340. [auth signInWithCredential:credential
  1341. completion:^(FIRUser *_Nullable user,
  1342. NSError *_Nullable error) {
  1343. if (error) {
  1344. [self logFailure:@"sign-in with Email/Password failed" error:error];
  1345. [self logFailedTest:@"sign-in with Email/Password should succeed."];
  1346. return;
  1347. }
  1348. [self logSuccess:@"sign-in with Email/Password succeeded."];
  1349. // Delete the user so that we can reuse the fake email address for subsequent tests.
  1350. [auth.currentUser deleteWithCompletion:^(NSError *_Nullable error) {
  1351. if (error) {
  1352. [self logFailure:@"Failed to delete user." error:error];
  1353. [self logFailedTest:@"Deleting a user that was recently signed-in should succeed"];
  1354. return;
  1355. }
  1356. [self logSuccess:@"User deleted."];
  1357. completion();
  1358. }];
  1359. }];
  1360. }];
  1361. }];
  1362. }
  1363. /** @fn updateDisplayNameAndPhotoURlWithCompletion:
  1364. @brief Automatically executes the manual test for setting displayName and photoUrl.
  1365. @param completion The completion block to continue the automatic test flow.
  1366. */
  1367. - (void)updateDisplayNameAndPhotoURlWithCompletion:(void(^)(void))completion {
  1368. FIRAuth *auth = [AppManager auth];
  1369. FIRUserProfileChangeRequest *changeRequest = [auth.currentUser profileChangeRequest];
  1370. changeRequest.photoURL = [NSURL URLWithString:kFakeDisplayPhotoUrl];
  1371. [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
  1372. if (error) {
  1373. [self logFailure:@"set photo URL failed" error:error];
  1374. [self logFailedTest:@"Change photo Url should succeed when signed-in."];
  1375. return;
  1376. }
  1377. [self logSuccess:@"set PhotoURL succeeded."];
  1378. FIRUserProfileChangeRequest *changeRequest = [auth.currentUser profileChangeRequest];
  1379. changeRequest.displayName = kFakeDisplayName;
  1380. [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
  1381. if (error) {
  1382. [self logFailure:@"set display name failed" error:error];
  1383. [self logFailedTest:@"Change display name should succeed when signed-in."];
  1384. return;
  1385. }
  1386. [self logSuccess:@"set display name succeeded."];
  1387. completion();
  1388. }];
  1389. }];
  1390. }
  1391. /** @fn addAuthStateListener
  1392. @brief Adds an auth state did change listener (block).
  1393. */
  1394. - (void)addAuthStateListener {
  1395. __weak typeof(self) weakSelf = self;
  1396. NSUInteger index = _authStateDidChangeListeners.count;
  1397. [self log:[NSString stringWithFormat:@"Auth State Did Change Listener #%lu was added.",
  1398. (unsigned long)index]];
  1399. FIRAuthStateDidChangeListenerHandle handle =
  1400. [[AppManager auth] addAuthStateDidChangeListener:^(FIRAuth *_Nonnull auth,
  1401. FIRUser *_Nullable user) {
  1402. [weakSelf log:[NSString stringWithFormat:
  1403. @"Auth State Did Change Listener #%lu was invoked on user '%@'.",
  1404. (unsigned long)index, user.uid]];
  1405. }];
  1406. [_authStateDidChangeListeners addObject:handle];
  1407. }
  1408. /** @fn removeAuthStateListener
  1409. @brief Removes an auth state did change listener (block).
  1410. */
  1411. - (void)removeAuthStateListener {
  1412. if (!_authStateDidChangeListeners.count) {
  1413. [self log:@"No remaining Auth State Did Change Listeners."];
  1414. return;
  1415. }
  1416. NSUInteger index = _authStateDidChangeListeners.count - 1;
  1417. FIRAuthStateDidChangeListenerHandle handle = _authStateDidChangeListeners.lastObject;
  1418. [[AppManager auth] removeAuthStateDidChangeListener:handle];
  1419. [_authStateDidChangeListeners removeObject:handle];
  1420. NSString *logString =
  1421. [NSString stringWithFormat:@"Auth State Did Change Listener #%lu was removed.",
  1422. (unsigned long)index];
  1423. [self log:logString];
  1424. }
  1425. /** @fn addIDTokenListener
  1426. @brief Adds an ID token did change listener (block).
  1427. */
  1428. - (void)addIDTokenListener {
  1429. __weak typeof(self) weakSelf = self;
  1430. NSUInteger index = _IDTokenDidChangeListeners.count;
  1431. [self log:[NSString stringWithFormat:@"ID Token Did Change Listener #%lu was added.",
  1432. (unsigned long)index]];
  1433. FIRIDTokenDidChangeListenerHandle handle =
  1434. [[AppManager auth] addIDTokenDidChangeListener:^(FIRAuth *_Nonnull auth,
  1435. FIRUser *_Nullable user) {
  1436. [weakSelf log:[NSString stringWithFormat:
  1437. @"ID Token Did Change Listener #%lu was invoked on user '%@'.",
  1438. (unsigned long)index, user.uid]];
  1439. }];
  1440. [_IDTokenDidChangeListeners addObject:handle];
  1441. }
  1442. /** @fn removeIDTokenListener
  1443. @brief Removes an ID token did change listener (block).
  1444. */
  1445. - (void)removeIDTokenListener {
  1446. if (!_IDTokenDidChangeListeners.count) {
  1447. [self log:@"No remaining ID Token Did Change Listeners."];
  1448. return;
  1449. }
  1450. NSUInteger index = _IDTokenDidChangeListeners.count - 1;
  1451. FIRIDTokenDidChangeListenerHandle handle = _IDTokenDidChangeListeners.lastObject;
  1452. [[AppManager auth] removeIDTokenDidChangeListener:handle];
  1453. [_IDTokenDidChangeListeners removeObject:handle];
  1454. NSString *logString =
  1455. [NSString stringWithFormat:@"ID Token Did Change Listener #%lu was removed.",
  1456. (unsigned long)index];
  1457. [self log:logString];
  1458. }
  1459. /** @fn log:
  1460. @brief Prints a log message to the sample app console.
  1461. @param string The string to add to the console.
  1462. */
  1463. - (void)log:(NSString *)string {
  1464. dispatch_async(dispatch_get_main_queue(), ^{
  1465. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1466. dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
  1467. NSString *date = [dateFormatter stringFromDate:[NSDate date]];
  1468. if (!_consoleString) {
  1469. _consoleString = [NSMutableString string];
  1470. }
  1471. [_consoleString appendString:[NSString stringWithFormat:@"%@ %@\n", date, string]];
  1472. _consoleTextView.text = _consoleString;
  1473. CGRect targetRect = CGRectMake(0, _consoleTextView.contentSize.height - 1, 1, 1);
  1474. [_consoleTextView scrollRectToVisible:targetRect animated:YES];
  1475. });
  1476. }
  1477. /** @fn logSuccess:
  1478. @brief Wraps a string into a succeful log message format.
  1479. @param string Part of the log message.
  1480. @remarks The @string parameter should be a string ending with a period, as it is the end of the
  1481. log message.
  1482. */
  1483. - (void)logSuccess:(NSString *)string {
  1484. [self log:[NSString stringWithFormat:@"SUCCESS: %@", string]];
  1485. }
  1486. /** @fn logFailure:
  1487. @brief Wraps a string into a failed log message format.
  1488. @param string Part of the message to wrap.
  1489. @remarks The @string parameter should be a string that NEVER ends with a period, as it is
  1490. guaranteed not to be the last part fo the log message.
  1491. */
  1492. - (void)logFailure:(NSString *)string error:(NSError *) error {
  1493. NSString *message =
  1494. [NSString stringWithFormat:@"FAILURE: %@ Error Description: %@.", string, error.description];
  1495. [self log:message];
  1496. }
  1497. /** @fn logTestFailed
  1498. @brief Logs test failure to the console.
  1499. @param reason The reason why the test is considered a failure.
  1500. @remarks The calling method should immediately terminate after invoking this method i.e by
  1501. return statement or end of fucntions. The @reason parameter should be a string ending with a
  1502. period, as it is the end of the log message.
  1503. */
  1504. - (void)logFailedTest:( NSString *_Nonnull )reason {
  1505. [self log:[NSString stringWithFormat:@"FAILIURE: TEST FAILED - %@", reason]];
  1506. }
  1507. /** @fn presentSettings
  1508. @brief Invoked when the settings row is pressed.
  1509. */
  1510. - (void)presentSettings {
  1511. SettingsViewController *settingsViewController = [[SettingsViewController alloc]
  1512. initWithNibName:NSStringFromClass([SettingsViewController class])
  1513. bundle:nil];
  1514. [self showViewController:settingsViewController sender:self];
  1515. }
  1516. /** @fn presentUserInfo
  1517. @brief Invoked when the user info row is pressed.
  1518. */
  1519. - (void)presentUserInfo {
  1520. UserInfoViewController *userInfoViewController =
  1521. [[UserInfoViewController alloc] initWithUser:[AppManager auth].currentUser];
  1522. [self showViewController:userInfoViewController sender:self];
  1523. }
  1524. /** @fn presentUserInMemoryInfo
  1525. @brief Invoked when the user in memory info row is pressed.
  1526. */
  1527. - (void)presentUserInMemoryInfo {
  1528. UserInfoViewController *userInfoViewController =
  1529. [[UserInfoViewController alloc] initWithUser:_userInMemory];
  1530. [self showViewController:userInfoViewController sender:self];
  1531. }
  1532. /** @fn signInGoogle
  1533. @brief Invoked when "Sign in with Google" row is pressed.
  1534. */
  1535. - (void)signInGoogle {
  1536. [self signinWithProvider:[AuthProviders google] retrieveData:YES];
  1537. }
  1538. /** @fn signInGoogleAndRetrieveData
  1539. @brief Invoked when "Sign in with Google and retrieve data" row is pressed.
  1540. */
  1541. - (void)signInGoogleAndRetrieveData {
  1542. [self signinWithProvider:[AuthProviders google] retrieveData:YES];
  1543. }
  1544. /** @fn signInFacebook
  1545. @brief Invoked when "Sign in with Facebook" row is pressed.
  1546. */
  1547. - (void)signInFacebook {
  1548. [self signinWithProvider:[AuthProviders facebook] retrieveData:YES];
  1549. }
  1550. /** @fn signInFacebookAndRetrieveData
  1551. @brief Invoked when "Sign in with Facebook and retrieve data" row is pressed.
  1552. */
  1553. - (void)signInFacebookAndRetrieveData {
  1554. [self signinWithProvider:[AuthProviders facebook] retrieveData:YES];
  1555. }
  1556. /** @fn signInEmailPassword
  1557. @brief Invoked when "Sign in with Email/Password" row is pressed.
  1558. */
  1559. - (void)signInEmailPassword {
  1560. [self showTextInputPromptWithMessage:@"Email Address:"
  1561. keyboardType:UIKeyboardTypeEmailAddress
  1562. completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
  1563. if (!userPressedOK || !email.length) {
  1564. return;
  1565. }
  1566. [self showTextInputPromptWithMessage:@"Password:"
  1567. completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
  1568. if (!userPressedOK) {
  1569. return;
  1570. }
  1571. FIRAuthCredential *credential =
  1572. [FIREmailAuthProvider credentialWithEmail:email
  1573. password:password];
  1574. [self showSpinner:^{
  1575. [[AppManager auth] signInWithCredential:credential
  1576. completion:^(FIRUser *_Nullable user,
  1577. NSError *_Nullable error) {
  1578. [self hideSpinner:^{
  1579. if (error) {
  1580. [self logFailure:@"sign-in with Email/Password failed" error:error];
  1581. } else {
  1582. [self logSuccess:@"sign-in with Email/Password succeeded."];
  1583. }
  1584. [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In Error" error:error];
  1585. }];
  1586. }];
  1587. }];
  1588. }];
  1589. }];
  1590. }
  1591. - (void)signInEmailPasswordAuthDataResult {
  1592. [self showTextInputPromptWithMessage:@"Email Address:"
  1593. keyboardType:UIKeyboardTypeEmailAddress
  1594. completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
  1595. if (!userPressedOK || !email.length) {
  1596. return;
  1597. }
  1598. [self showTextInputPromptWithMessage:@"Password:"
  1599. completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
  1600. if (!userPressedOK) {
  1601. return;
  1602. }
  1603. [self showSpinner:^{
  1604. [[AppManager auth] signInAndRetrieveDataWithEmail:email
  1605. password:password
  1606. completion:^(FIRAuthDataResult *_Nullable authResult,
  1607. NSError *_Nullable error) {
  1608. [self hideSpinner:^{
  1609. if (error) {
  1610. [self logFailure:@"sign-in with Email/Password failed" error:error];
  1611. } else {
  1612. [self logSuccess:@"sign-in with Email/Password succeeded."];
  1613. [self log:[NSString stringWithFormat:@"UID: %@",authResult.user.uid]];
  1614. }
  1615. [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In Error" error:error];
  1616. }];
  1617. }];
  1618. }];
  1619. }];
  1620. }];
  1621. }
  1622. /** @fn signInWithEmailLink
  1623. @brief Invoked when "Sign in with email link" row is pressed.
  1624. */
  1625. - (void)signInWithEmailLink {
  1626. [self showTextInputPromptWithMessage:@"Email Address:"
  1627. keyboardType:UIKeyboardTypeEmailAddress
  1628. completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
  1629. if (!userPressedOK || !email.length) {
  1630. return;
  1631. }
  1632. [self showTextInputPromptWithMessage:@"Email Sign-In Link:"
  1633. completionBlock:^(BOOL userPressedOK, NSString *_Nullable link) {
  1634. if (!userPressedOK) {
  1635. return;
  1636. }
  1637. if ([[FIRAuth auth] isSignInWithEmailLink:link]) {
  1638. [self showSpinner:^{
  1639. [[AppManager auth] signInWithEmail:email
  1640. link:link
  1641. completion:^(FIRAuthDataResult *_Nullable authResult,
  1642. NSError *_Nullable error) {
  1643. [self hideSpinner:^{
  1644. if (error) {
  1645. [self logFailure:@"sign-in with Email/Sign-In failed" error:error];
  1646. } else {
  1647. [self logSuccess:@"sign-in with Email/Sign-In link succeeded."];
  1648. [self log:[NSString stringWithFormat:@"UID: %@",authResult.user.uid]];
  1649. }
  1650. [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In Error" error:error];
  1651. }];
  1652. }];
  1653. }];
  1654. } else {
  1655. [self log:@"The sign-in link is invalid"];
  1656. }
  1657. }];
  1658. }];
  1659. }
  1660. /** @fn verifyEmailLinkAccount
  1661. @brief Invoked to verify that the current user is an email-link user.
  1662. */
  1663. - (void)verifyEmailLinkAccount {
  1664. if (![FIRAuth auth].currentUser.email) {
  1665. [self showMessagePrompt:@"There is no signed-in user available."];
  1666. return;
  1667. }
  1668. [[FIRAuth auth] fetchSignInMethodsForEmail:[FIRAuth auth].currentUser.email
  1669. completion:^(NSArray<NSString *> *_Nullable signInMethods,
  1670. NSError *_Nullable error) {
  1671. if (error) {
  1672. [self showMessagePrompt:@"There was an error fetching sign-in methods."];
  1673. return;
  1674. }
  1675. if (![signInMethods containsObject:FIREmailLinkAuthSignInMethod]) {
  1676. [self showMessagePrompt:@"Error: The current user is NOT an email-link user."];
  1677. return;
  1678. }
  1679. [self showMessagePrompt:@"The current user is an email-link user."];
  1680. }];
  1681. }
  1682. /** @fn sendEmailSignInLink
  1683. @brief Invoked when "Send email sign-in link" row is pressed.
  1684. */
  1685. - (void)sendEmailSignInLink {
  1686. [self showTextInputPromptWithMessage:@"Email:"
  1687. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  1688. if (!userPressedOK) {
  1689. return;
  1690. }
  1691. [self showSpinner:^{
  1692. void (^requestEmailSignInLink)(void (^)(NSError *)) = ^(void (^completion)(NSError *)) {
  1693. [[AppManager auth] sendSignInLinkToEmail:userInput
  1694. actionCodeSettings:[self actionCodeSettings]
  1695. completion:completion];
  1696. };
  1697. requestEmailSignInLink(^(NSError *_Nullable error) {
  1698. [self hideSpinner:^{
  1699. if (error) {
  1700. [self logFailure:@"Email Link request failed" error:error];
  1701. [self showMessagePrompt:error.localizedDescription];
  1702. return;
  1703. }
  1704. [self logSuccess:@"Email Link request succeeded."];
  1705. [self showMessagePrompt:@"Sent"];
  1706. }];
  1707. });
  1708. }];
  1709. }];
  1710. }
  1711. /** @fn signUpNewEmail
  1712. @brief Invoked if sign-in is attempted with new email/password.
  1713. @remarks Should only be called if @c FIRAuthErrorCodeInvalidEmail is encountered on attepmt to
  1714. sign in with email/password.
  1715. */
  1716. - (void)signUpNewEmail:(NSString *)email
  1717. password:(NSString *)password
  1718. callback:(nullable FIRAuthResultCallback)callback {
  1719. [[AppManager auth] createUserWithEmail:email
  1720. password:password
  1721. completion:^(FIRAuthDataResult *_Nullable result,
  1722. NSError *_Nullable error) {
  1723. if (error) {
  1724. [self logFailure:@"sign-up with Email/Password failed" error:error];
  1725. if (callback) {
  1726. callback(nil, error);
  1727. }
  1728. } else {
  1729. [self logSuccess:@"sign-up with Email/Password succeeded."];
  1730. if (callback) {
  1731. callback(result.user, nil);
  1732. }
  1733. }
  1734. [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In" error:error];
  1735. }];
  1736. }
  1737. /** @fn signInWithCustomToken
  1738. @brief Signs the user in using a manually-entered custom token.
  1739. */
  1740. - (void)signInWithCustomToken {
  1741. CustomTokenDataEntryViewControllerCompletion action =
  1742. ^(BOOL cancelled, NSString *_Nullable userEnteredTokenText) {
  1743. if (cancelled) {
  1744. [self log:@"CANCELLED:sign-in with custom token cancelled."];
  1745. return;
  1746. }
  1747. [self doSignInWithCustomToken:userEnteredTokenText];
  1748. };
  1749. CustomTokenDataEntryViewController *dataEntryViewController =
  1750. [[CustomTokenDataEntryViewController alloc] initWithCompletion:action];
  1751. [self presentViewController:dataEntryViewController animated:YES completion:nil];
  1752. }
  1753. /** @fn signInWithCustomTokenAuthResult
  1754. @brief Signs the user in using a manually-entered custom token.
  1755. */
  1756. - (void)signInWithCustomTokenAuthResult {
  1757. CustomTokenDataEntryViewControllerCompletion action =
  1758. ^(BOOL cancelled, NSString *_Nullable userEnteredTokenText) {
  1759. if (cancelled) {
  1760. [self log:@"CANCELLED:sign-in with custom token cancelled."];
  1761. return;
  1762. }
  1763. [self doSignInAndRetrieveDataWithCustomToken:userEnteredTokenText];
  1764. };
  1765. CustomTokenDataEntryViewController *dataEntryViewController =
  1766. [[CustomTokenDataEntryViewController alloc] initWithCompletion:action];
  1767. [self presentViewController:dataEntryViewController animated:YES completion:nil];
  1768. }
  1769. /** @fn signOut
  1770. @brief Signs the user out.
  1771. */
  1772. - (void)signOut {
  1773. [[AuthProviders google] signOut];
  1774. [[AuthProviders facebook] signOut];
  1775. [[AppManager auth] signOut:NULL];
  1776. }
  1777. /** @fn deleteAccount
  1778. @brief Deletes the current user account and signs the user out.
  1779. */
  1780. - (void)deleteAccount {
  1781. FIRUser *user = [self user];
  1782. [user deleteWithCompletion:^(NSError *_Nullable error) {
  1783. if (error) {
  1784. [self logFailure:@"delete account failed" error:error];
  1785. }
  1786. [self showTypicalUIForUserUpdateResultsWithTitle:kDeleteUserText error:error];
  1787. }];
  1788. }
  1789. /** @fn reauthenticateGoogle
  1790. @brief Asks the user to reauthenticate with Google.
  1791. */
  1792. - (void)reauthenticateGoogle {
  1793. [self reauthenticate:[AuthProviders google] retrieveData:NO];
  1794. }
  1795. /** @fn reauthenticateGoogleAndRetrieveData
  1796. @brief Asks the user to reauthenticate with Google and retrieve additional data.
  1797. */
  1798. - (void)reauthenticateGoogleAndRetrieveData {
  1799. [self reauthenticate:[AuthProviders google] retrieveData:YES];
  1800. }
  1801. /** @fn reauthenticateFB
  1802. @brief Asks the user to reauthenticate with Facebook.
  1803. */
  1804. - (void)reauthenticateFB {
  1805. [self reauthenticate:[AuthProviders facebook] retrieveData:NO];
  1806. }
  1807. /** @fn reauthenticateFBAndRetrieveData
  1808. @brief Asks the user to reauthenticate with Facebook and retrieve additional data.
  1809. */
  1810. - (void)reauthenticateFBAndRetrieveData {
  1811. [self reauthenticate:[AuthProviders facebook] retrieveData:YES];
  1812. }
  1813. /** @fn reauthenticateEmailPassword
  1814. @brief Asks the user to reauthenticate with email/password.
  1815. */
  1816. - (void)reauthenticateEmailPassword {
  1817. FIRUser *user = [self user];
  1818. if (!user) {
  1819. NSString *title = @"Missing User";
  1820. NSString *message = @"There is no signed-in email/password user.";
  1821. [self showMessagePromptWithTitle:title message:message showCancelButton:NO completion:nil];
  1822. return;
  1823. }
  1824. [self showEmailPasswordDialogWithCompletion:^(FIRAuthCredential *credential) {
  1825. [self showSpinner:^{
  1826. [[self user] reauthenticateWithCredential:credential
  1827. completion:^(NSError *_Nullable error) {
  1828. if (error) {
  1829. [self logFailure:@"reauthicate with email/password failed" error:error];
  1830. } else {
  1831. [self logSuccess:@"reauthicate with email/password succeeded."];
  1832. }
  1833. [self hideSpinner:^{
  1834. [self showTypicalUIForUserUpdateResultsWithTitle:kReauthenticateEmailText error:error];
  1835. }];
  1836. }];
  1837. }];
  1838. }];
  1839. }
  1840. /** @fn reauthenticate:
  1841. @brief Reauthenticates user.
  1842. @param authProvider The auth provider to use for reauthentication.
  1843. @param retrieveData Defines if additional provider data should be read.
  1844. */
  1845. - (void)reauthenticate:(id<AuthProvider>)authProvider retrieveData:(BOOL)retrieveData {
  1846. FIRUser *user = [self user];
  1847. if (!user) {
  1848. NSString *provider = @"Firebase";
  1849. if ([authProvider isKindOfClass:[GoogleAuthProvider class]]) {
  1850. provider = @"Google";
  1851. } else if ([authProvider isKindOfClass:[FacebookAuthProvider class]]) {
  1852. provider = @"Facebook";
  1853. }
  1854. NSString *title = @"Missing User";
  1855. NSString *message =
  1856. [NSString stringWithFormat:@"There is no signed-in %@ user.", provider];
  1857. [self showMessagePromptWithTitle:title message:message showCancelButton:NO completion:nil];
  1858. return;
  1859. }
  1860. [authProvider getAuthCredentialWithPresentingViewController:self
  1861. callback:^(FIRAuthCredential *credential,
  1862. NSError *error) {
  1863. if (credential) {
  1864. FIRAuthDataResultCallback completion = ^(FIRAuthDataResult *_Nullable authResult,
  1865. NSError *_Nullable error) {
  1866. if (error) {
  1867. [self logFailure:@"reauthenticate operation failed" error:error];
  1868. } else {
  1869. [self logSuccess:@"reauthenticate operation succeeded."];
  1870. }
  1871. if (authResult.additionalUserInfo) {
  1872. [self logSuccess:[self stringWithAdditionalUserInfo:authResult.additionalUserInfo]];
  1873. }
  1874. [self showTypicalUIForUserUpdateResultsWithTitle:@"Reauthenticate" error:error];
  1875. };
  1876. FIRUserProfileChangeCallback callback = ^(NSError *_Nullable error) {
  1877. completion(nil, error);
  1878. };
  1879. if (retrieveData) {
  1880. [user reauthenticateAndRetrieveDataWithCredential:credential completion:completion];
  1881. } else {
  1882. [user reauthenticateWithCredential:credential completion:callback];
  1883. }
  1884. }
  1885. }];
  1886. }
  1887. /** @fn signinWithProvider:
  1888. @brief Signs in the user with provided auth provider.
  1889. @param authProvider The auth provider to use for sign-in.
  1890. @param retrieveData Defines if additional provider data should be read.
  1891. */
  1892. - (void)signinWithProvider:(id<AuthProvider>)authProvider retrieveData:(BOOL)retrieveData {
  1893. FIRAuth *auth = [AppManager auth];
  1894. if (!auth) {
  1895. return;
  1896. }
  1897. [authProvider getAuthCredentialWithPresentingViewController:self
  1898. callback:^(FIRAuthCredential *credential,
  1899. NSError *error) {
  1900. if (credential) {
  1901. FIRAuthDataResultCallback completion = ^(FIRAuthDataResult *_Nullable authResult,
  1902. NSError *_Nullable error) {
  1903. if (error) {
  1904. [self logFailure:@"sign-in with provider failed" error:error];
  1905. } else {
  1906. [self logSuccess:@"sign-in with provider succeeded."];
  1907. }
  1908. if (authResult.additionalUserInfo) {
  1909. [self logSuccess:[self stringWithAdditionalUserInfo:authResult.additionalUserInfo]];
  1910. if (_isNewUserToggleOn) {
  1911. NSString *newUserString = authResult.additionalUserInfo.isNewUser ?
  1912. @"New user" : @"Existing user";
  1913. [self showMessagePromptWithTitle:@"New or Existing"
  1914. message:newUserString
  1915. showCancelButton:NO
  1916. completion:nil];
  1917. }
  1918. }
  1919. [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In" error:error];
  1920. };
  1921. FIRAuthResultCallback callback = ^(FIRUser *_Nullable user,
  1922. NSError *_Nullable error) {
  1923. completion(nil, error);
  1924. };
  1925. if (retrieveData) {
  1926. [auth signInAndRetrieveDataWithCredential:credential completion:completion];
  1927. } else {
  1928. [auth signInWithCredential:credential completion:callback];
  1929. }
  1930. }
  1931. }];
  1932. }
  1933. /** @fn tokenCallback
  1934. @return A callback block to show the token.
  1935. */
  1936. - (FIRAuthTokenCallback)tokenCallback {
  1937. return ^(NSString *_Nullable token, NSError *_Nullable error) {
  1938. if (error) {
  1939. [self showMessagePromptWithTitle:kTokenRefreshErrorAlertTitle
  1940. message:error.localizedDescription
  1941. showCancelButton:NO
  1942. completion:nil];
  1943. [self logFailure:@"refresh token failed" error:error];
  1944. return;
  1945. }
  1946. [self logSuccess:@"refresh token succeeded."];
  1947. [self showMessagePromptWithTitle:kTokenRefreshedAlertTitle
  1948. message:token
  1949. showCancelButton:NO
  1950. completion:nil];
  1951. };
  1952. }
  1953. /** @fn getUserTokenWithForce:
  1954. @brief Gets the token from @c FIRUser, optionally a refreshed one.
  1955. @param force Whether the refresh is forced or not.
  1956. */
  1957. - (void)getUserTokenWithForce:(BOOL)force {
  1958. [[self user] getIDTokenForcingRefresh:force completion:[self tokenCallback]];
  1959. }
  1960. /** @fn getUserTokenResultWithForce:
  1961. @brief Gets the token result object from @c FIRUser, optionally a refreshed one.
  1962. @param force Whether the refresh is forced or not.
  1963. */
  1964. - (void)getUserTokenResultWithForce:(BOOL)force {
  1965. [[self user] getIDTokenResultForcingRefresh:force
  1966. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  1967. NSError *_Nullable error) {
  1968. if (error) {
  1969. [self showMessagePromptWithTitle:kTokenRefreshErrorAlertTitle
  1970. message:error.localizedDescription
  1971. showCancelButton:NO
  1972. completion:nil];
  1973. [self logFailure:@"refresh token failed" error:error];
  1974. return;
  1975. }
  1976. [self logSuccess:@"refresh token succeeded."];
  1977. NSMutableString *message =
  1978. [[NSMutableString alloc] initWithString:
  1979. [NSString stringWithFormat:@"Token : %@\n", tokenResult.token]];
  1980. [message appendString:[NSString stringWithFormat:@"Auth Date : %@\n", tokenResult.authDate]];
  1981. [message appendString:
  1982. [NSString stringWithFormat:@"EXP Date : %@\n", tokenResult.expirationDate]];
  1983. [message appendString:
  1984. [NSString stringWithFormat:@"Issued Date : %@\n", tokenResult.issuedAtDate]];
  1985. [self showMessagePromptWithTitle:kTokenRefreshedAlertTitle
  1986. message:message
  1987. showCancelButton:NO
  1988. completion:nil];
  1989. }];
  1990. }
  1991. /** @fn getAppTokenWithForce:
  1992. @brief Gets the token from @c FIRApp , optionally a refreshed one.
  1993. @param force Whether the refresh is forced or not.
  1994. */
  1995. - (void)getAppTokenWithForce:(BOOL)force {
  1996. [[FIRApp defaultApp] getTokenForcingRefresh:force withCallback:[self tokenCallback]];
  1997. }
  1998. /** @fn setDisplayName
  1999. @brief Changes the display name of the current user.
  2000. */
  2001. - (void)setDisplayName {
  2002. [self showTextInputPromptWithMessage:@"Display Name:"
  2003. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2004. if (!userPressedOK || !userInput.length) {
  2005. return;
  2006. }
  2007. [self showSpinner:^{
  2008. FIRUserProfileChangeRequest *changeRequest = [[self user] profileChangeRequest];
  2009. changeRequest.displayName = userInput;
  2010. [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
  2011. [self hideSpinner:^{
  2012. if (error) {
  2013. [self logFailure:@"set display name failed" error:error];
  2014. } else {
  2015. [self logSuccess:@"set display name succeeded."];
  2016. }
  2017. [self showTypicalUIForUserUpdateResultsWithTitle:kSetDisplayNameTitle error:error];
  2018. }];
  2019. }];
  2020. }];
  2021. }];
  2022. }
  2023. /** @fn setPhotoURL
  2024. @brief Changes the photo url of the current user.
  2025. */
  2026. - (void)setPhotoURL {
  2027. [self showTextInputPromptWithMessage:@"Photo URL:"
  2028. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2029. if (!userPressedOK || !userInput.length) {
  2030. return;
  2031. }
  2032. [self showSpinner:^{
  2033. FIRUserProfileChangeRequest *changeRequest = [[self user] profileChangeRequest];
  2034. changeRequest.photoURL = [NSURL URLWithString:userInput];
  2035. [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
  2036. if (error) {
  2037. [self logFailure:@"set photo URL failed" error:error];
  2038. } else {
  2039. [self logSuccess:@"set Photo URL succeeded."];
  2040. }
  2041. [self hideSpinner:^{
  2042. [self showTypicalUIForUserUpdateResultsWithTitle:kSetPhotoURLText error:error];
  2043. }];
  2044. }];
  2045. }];
  2046. }];
  2047. }
  2048. /** @fn reloadUser
  2049. @brief Reloads the user from server.
  2050. */
  2051. - (void)reloadUser {
  2052. [self showSpinner:^() {
  2053. [[self user] reloadWithCompletion:^(NSError *_Nullable error) {
  2054. if (error) {
  2055. [self logFailure:@"reload user failed" error:error];
  2056. } else {
  2057. [self logSuccess:@"reload user succeeded."];
  2058. }
  2059. [self hideSpinner:^() {
  2060. [self showTypicalUIForUserUpdateResultsWithTitle:kReloadText error:error];
  2061. }];
  2062. }];
  2063. }];
  2064. }
  2065. /** @fn linkWithAuthProvider:retrieveData:
  2066. @brief Asks the user to sign in with an auth provider and link the current user with it.
  2067. @param authProvider The auth provider to sign in and link with.
  2068. @param retrieveData Defines if additional provider data should be read.
  2069. */
  2070. - (void)linkWithAuthProvider:(id<AuthProvider>)authProvider retrieveData:(BOOL)retrieveData {
  2071. FIRUser *user = [self user];
  2072. if (!user) {
  2073. return;
  2074. }
  2075. [authProvider getAuthCredentialWithPresentingViewController:self
  2076. callback:^(FIRAuthCredential *credential,
  2077. NSError *error) {
  2078. if (credential) {
  2079. FIRAuthDataResultCallback completion = ^(FIRAuthDataResult *_Nullable authResult,
  2080. NSError *_Nullable error) {
  2081. if (error) {
  2082. [self logFailure:@"link auth provider failed" error:error];
  2083. } else {
  2084. [self logSuccess:@"link auth provider succeeded."];
  2085. }
  2086. if (authResult.additionalUserInfo) {
  2087. [self logSuccess:[self stringWithAdditionalUserInfo:authResult.additionalUserInfo]];
  2088. }
  2089. if (retrieveData) {
  2090. [self showUIForAuthDataResultWithResult:authResult error:error];
  2091. } else {
  2092. [self showTypicalUIForUserUpdateResultsWithTitle:@"Link Account" error:error];
  2093. }
  2094. };
  2095. FIRAuthResultCallback callback = ^(FIRUser *_Nullable user,
  2096. NSError *_Nullable error) {
  2097. completion(nil, error);
  2098. };
  2099. if (retrieveData) {
  2100. [user linkAndRetrieveDataWithCredential:credential completion:completion];
  2101. } else {
  2102. [user linkWithCredential:credential completion:callback];
  2103. }
  2104. }
  2105. }];
  2106. }
  2107. /** @fn linkWithGoogle
  2108. @brief Asks the user to sign in with Google and link the current user with this Google account.
  2109. */
  2110. - (void)linkWithGoogle {
  2111. [self linkWithAuthProvider:[AuthProviders google] retrieveData:NO];
  2112. }
  2113. /** @fn linkWithGoogleAndRetrieveData
  2114. @brief Asks the user to sign in with Google and link the current user with this Google account
  2115. and retrieve additional data.
  2116. */
  2117. - (void)linkWithGoogleAndRetrieveData {
  2118. [self linkWithAuthProvider:[AuthProviders google] retrieveData:YES];
  2119. }
  2120. /** @fn linkWithFacebook
  2121. @brief Asks the user to sign in with Facebook and link the current user with this Facebook
  2122. account.
  2123. */
  2124. - (void)linkWithFacebook {
  2125. [self linkWithAuthProvider:[AuthProviders facebook] retrieveData:NO];
  2126. }
  2127. /** @fn linkWithFacebookAndRetrieveData
  2128. @brief Asks the user to sign in with Facebook and link the current user with this Facebook
  2129. account and retrieve additional data.
  2130. */
  2131. - (void)linkWithFacebookAndRetrieveData {
  2132. [self linkWithAuthProvider:[AuthProviders facebook] retrieveData:YES];
  2133. }
  2134. /** @fn linkWithEmailPassword
  2135. @brief Asks the user to sign in with Facebook and link the current user with this Facebook
  2136. account.
  2137. */
  2138. - (void)linkWithEmailPassword {
  2139. [self showEmailPasswordDialogWithCompletion:^(FIRAuthCredential *credential) {
  2140. [self showSpinner:^{
  2141. [[self user] linkWithCredential:credential
  2142. completion:^(FIRUser *user, NSError *_Nullable error) {
  2143. if (error) {
  2144. [self logFailure:@"link Email/Password failed" error:error];
  2145. } else {
  2146. [self logSuccess:@"link Email/Password succeeded."];
  2147. }
  2148. [self hideSpinner:^{
  2149. [self showTypicalUIForUserUpdateResultsWithTitle:kLinkWithEmailPasswordText error:error];
  2150. }];
  2151. }];
  2152. }];
  2153. }];
  2154. }
  2155. /** @fn showEmailPasswordDialogWithCompletion:
  2156. @brief shows email/password input dialog.
  2157. @param completion The completion block that will do some operation on the credential email
  2158. /passwowrd credential obtained.
  2159. */
  2160. - (void)showEmailPasswordDialogWithCompletion:(ShowEmailPasswordDialogCompletion)completion {
  2161. [self showTextInputPromptWithMessage:@"Email Address:"
  2162. completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
  2163. if (!userPressedOK || !email.length) {
  2164. return;
  2165. }
  2166. [self showTextInputPromptWithMessage:@"Password:"
  2167. completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
  2168. if (!userPressedOK || !password.length) {
  2169. return;
  2170. }
  2171. FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:email
  2172. password:password];
  2173. completion(credential);
  2174. }];
  2175. }];
  2176. }
  2177. /** @fn unlinkFromProvider:
  2178. @brief Unlinks the current user from the provider with the specified provider ID.
  2179. @param provider The provider ID of the provider to unlink the current user's account from.
  2180. @completion A completion block to be executed after the provider is unlinked.
  2181. */
  2182. - (void)unlinkFromProvider:(NSString *)provider
  2183. completion:(nullable testAutomationCallback)completion {
  2184. [[self user] unlinkFromProvider:provider
  2185. completion:^(FIRUser *_Nullable user,
  2186. NSError *_Nullable error) {
  2187. if (error) {
  2188. [self logFailure:@"unlink auth provider failed" error:error];
  2189. if (completion) {
  2190. completion(error);
  2191. }
  2192. return;
  2193. }
  2194. [self logSuccess:@"unlink auth provider succeeded."];
  2195. if (completion) {
  2196. completion(nil);
  2197. }
  2198. [self showTypicalUIForUserUpdateResultsWithTitle:kUnlinkTitle error:error];
  2199. }];
  2200. }
  2201. /** @fn getProvidersForEmail
  2202. @brief Prompts the user for an email address, calls @c FIRAuth.getProvidersForEmail:callback:
  2203. and displays the result.
  2204. */
  2205. - (void)getProvidersForEmail {
  2206. [self showTextInputPromptWithMessage:@"Email:"
  2207. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2208. if (!userPressedOK || !userInput.length) {
  2209. return;
  2210. }
  2211. [self showSpinner:^{
  2212. [[AppManager auth] fetchProvidersForEmail:userInput
  2213. completion:^(NSArray<NSString *> *_Nullable providers,
  2214. NSError *_Nullable error) {
  2215. if (error) {
  2216. [self logFailure:@"get providers for email failed" error:error];
  2217. } else {
  2218. [self logSuccess:@"get providers for email succeeded."];
  2219. }
  2220. [self hideSpinner:^{
  2221. if (error) {
  2222. [self showMessagePrompt:error.localizedDescription];
  2223. return;
  2224. }
  2225. [self showMessagePrompt:[providers componentsJoinedByString:@", "]];
  2226. }];
  2227. }];
  2228. }];
  2229. }];
  2230. }
  2231. /** @fn getAllSignInMethodsForEmail
  2232. @brief Prompts user for an email address, calls @c FIRAuth.getAllSignInMethodsForEmail:callback:
  2233. and displays the result.
  2234. */
  2235. - (void)getAllSignInMethodsForEmail {
  2236. [self showTextInputPromptWithMessage:@"Email:"
  2237. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2238. if (!userPressedOK || !userInput.length) {
  2239. return;
  2240. }
  2241. [self showSpinner:^{
  2242. [[AppManager auth] fetchSignInMethodsForEmail:userInput
  2243. completion:^(NSArray<NSString *> *_Nullable signInMethods,
  2244. NSError *_Nullable error) {
  2245. if (error) {
  2246. [self logFailure:@"get sign-in methods for email failed" error:error];
  2247. } else {
  2248. [self logSuccess:@"get sign-in methods for email succeeded."];
  2249. }
  2250. [self hideSpinner:^{
  2251. if (error) {
  2252. [self showMessagePrompt:error.localizedDescription];
  2253. return;
  2254. }
  2255. [self showMessagePrompt:[signInMethods componentsJoinedByString:@", "]];
  2256. }];
  2257. }];
  2258. }];
  2259. }];
  2260. }
  2261. /** @fn actionCodeRequestTypeString
  2262. @brief Returns a string description for the type of the next action code request.
  2263. */
  2264. - (NSString *)actionCodeRequestTypeString {
  2265. switch (_actionCodeRequestType) {
  2266. case ActionCodeRequestTypeInApp:
  2267. return @"In-App + Continue URL";
  2268. case ActionCodeRequestTypeContinue:
  2269. return @"Continue URL";
  2270. case ActionCodeRequestTypeEmail:
  2271. return @"Email Only";
  2272. }
  2273. }
  2274. /** @fn toggleActionCodeRequestType
  2275. @brief Toggle the next action code request type.
  2276. */
  2277. - (void)toggleActionCodeRequestType {
  2278. switch (_actionCodeRequestType) {
  2279. case ActionCodeRequestTypeInApp:
  2280. _actionCodeRequestType = ActionCodeRequestTypeContinue;
  2281. break;
  2282. case ActionCodeRequestTypeContinue:
  2283. _actionCodeRequestType = ActionCodeRequestTypeEmail;
  2284. break;
  2285. case ActionCodeRequestTypeEmail:
  2286. _actionCodeRequestType = ActionCodeRequestTypeInApp;
  2287. break;
  2288. }
  2289. [self updateTable];
  2290. }
  2291. - (void)changeActionCodeContinueURL {
  2292. [self showTextInputPromptWithMessage:kContinueURLDescription
  2293. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2294. if (userPressedOK) {
  2295. _actionCodeContinueURL = userInput.length ? [NSURL URLWithString:userInput] : nil;
  2296. [self updateTable];
  2297. }
  2298. }];
  2299. }
  2300. /** @fn requestVerifyEmail
  2301. @brief Requests a "verify email" email be sent.
  2302. */
  2303. - (void)requestVerifyEmail {
  2304. [self showSpinner:^{
  2305. void (^sendEmailVerification)(void (^)(NSError *)) = ^(void (^completion)(NSError *)) {
  2306. if (_actionCodeRequestType == ActionCodeRequestTypeEmail) {
  2307. [[self user] sendEmailVerificationWithCompletion:completion];
  2308. } else {
  2309. [[self user] sendEmailVerificationWithActionCodeSettings:[self actionCodeSettings]
  2310. completion:completion];
  2311. }
  2312. };
  2313. sendEmailVerification(^(NSError *_Nullable error) {
  2314. [self hideSpinner:^{
  2315. if (error) {
  2316. [self logFailure:@"request verify email failed" error:error];
  2317. [self showMessagePrompt:error.localizedDescription];
  2318. return;
  2319. }
  2320. [self logSuccess:@"request verify email succeeded."];
  2321. [self showMessagePrompt:@"Sent"];
  2322. }];
  2323. });
  2324. }];
  2325. }
  2326. /** @fn requestPasswordReset
  2327. @brief Requests a "password reset" email be sent.
  2328. */
  2329. - (void)requestPasswordReset {
  2330. [self showTextInputPromptWithMessage:@"Email:"
  2331. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2332. if (!userPressedOK || !userInput.length) {
  2333. return;
  2334. }
  2335. [self showSpinner:^{
  2336. void (^requestPasswordReset)(void (^)(NSError *)) = ^(void (^completion)(NSError *)) {
  2337. if (_actionCodeRequestType == ActionCodeRequestTypeEmail) {
  2338. [[AppManager auth] sendPasswordResetWithEmail:userInput completion:completion];
  2339. } else {
  2340. [[AppManager auth] sendPasswordResetWithEmail:userInput
  2341. actionCodeSettings:[self actionCodeSettings]
  2342. completion:completion];
  2343. }
  2344. };
  2345. requestPasswordReset(^(NSError *_Nullable error) {
  2346. [self hideSpinner:^{
  2347. if (error) {
  2348. [self logFailure:@"request password reset failed" error:error];
  2349. [self showMessagePrompt:error.localizedDescription];
  2350. return;
  2351. }
  2352. [self logSuccess:@"request password reset succeeded."];
  2353. [self showMessagePrompt:@"Sent"];
  2354. }];
  2355. });
  2356. }];
  2357. }];
  2358. }
  2359. /** @fn resetPassword
  2360. @brief Performs a password reset operation.
  2361. */
  2362. - (void)resetPassword {
  2363. [self showTextInputPromptWithMessage:@"OOB Code:"
  2364. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2365. if (!userPressedOK || !userInput.length) {
  2366. return;
  2367. }
  2368. NSString *code = userInput;
  2369. [self showTextInputPromptWithMessage:@"New Password:"
  2370. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2371. if (!userPressedOK || !userInput.length) {
  2372. return;
  2373. }
  2374. [self showSpinner:^{
  2375. [[AppManager auth] confirmPasswordResetWithCode:code
  2376. newPassword:userInput
  2377. completion:^(NSError *_Nullable error) {
  2378. [self hideSpinner:^{
  2379. if (error) {
  2380. [self logFailure:@"Password reset failed" error:error];
  2381. [self showMessagePrompt:error.localizedDescription];
  2382. return;
  2383. }
  2384. [self logSuccess:@"Password reset succeeded."];
  2385. [self showMessagePrompt:@"Password reset succeeded."];
  2386. }];
  2387. }];
  2388. }];
  2389. }];
  2390. }];
  2391. }
  2392. /** @fn checkActionCode
  2393. @brief Performs a "check action code" operation.
  2394. */
  2395. - (void)checkActionCode {
  2396. [self showTextInputPromptWithMessage:@"OOB Code:"
  2397. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2398. if (!userPressedOK || !userInput.length) {
  2399. return;
  2400. }
  2401. [self showSpinner:^{
  2402. [[AppManager auth] checkActionCode:userInput completion:^(FIRActionCodeInfo *_Nullable info,
  2403. NSError *_Nullable error) {
  2404. [self hideSpinner:^{
  2405. if (error) {
  2406. [self logFailure:@"Check action code failed" error:error];
  2407. [self showMessagePrompt:error.localizedDescription];
  2408. return;
  2409. }
  2410. [self logSuccess:@"Check action code succeeded."];
  2411. NSString *email = [info dataForKey:FIRActionCodeEmailKey];
  2412. NSString *fromEmail = [info dataForKey:FIRActionCodeFromEmailKey];
  2413. NSString *message =
  2414. fromEmail ? [NSString stringWithFormat:@"%@ -> %@", fromEmail, email] : email;
  2415. NSString *operation = [self nameForActionCodeOperation:info.operation];
  2416. [self showMessagePromptWithTitle:operation
  2417. message:message
  2418. showCancelButton:NO
  2419. completion:nil];
  2420. }];
  2421. }];
  2422. }];
  2423. }];
  2424. }
  2425. /** @fn applyActionCode
  2426. @brief Performs a "apply action code" operation.
  2427. */
  2428. - (void)applyActionCode {
  2429. [self showTextInputPromptWithMessage:@"OOB Code:"
  2430. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2431. if (!userPressedOK || !userInput.length) {
  2432. return;
  2433. }
  2434. [self showSpinner:^{
  2435. [[AppManager auth] applyActionCode:userInput completion:^(NSError *_Nullable error) {
  2436. [self hideSpinner:^{
  2437. if (error) {
  2438. [self logFailure:@"Apply action code failed" error:error];
  2439. [self showMessagePrompt:error.localizedDescription];
  2440. return;
  2441. }
  2442. [self logSuccess:@"Apply action code succeeded."];
  2443. [self showMessagePrompt:@"Action code was properly applied."];
  2444. }];
  2445. }];
  2446. }];
  2447. }];
  2448. }
  2449. /** @fn verifyPasswordResetCode
  2450. @brief Performs a "verify password reset code" operation.
  2451. */
  2452. - (void)verifyPasswordResetCode {
  2453. [self showTextInputPromptWithMessage:@"OOB Code:"
  2454. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2455. if (!userPressedOK || !userInput.length) {
  2456. return;
  2457. }
  2458. [self showSpinner:^{
  2459. [[AppManager auth] verifyPasswordResetCode:userInput completion:^(NSString *_Nullable email,
  2460. NSError *_Nullable error) {
  2461. [self hideSpinner:^{
  2462. if (error) {
  2463. [self logFailure:@"Verify password reset code failed" error:error];
  2464. [self showMessagePrompt:error.localizedDescription];
  2465. return;
  2466. }
  2467. [self logSuccess:@"Verify password resest code succeeded."];
  2468. NSString *alertMessage =
  2469. [[NSString alloc] initWithFormat:@"Code verified for email: %@", email];
  2470. [self showMessagePrompt:alertMessage];
  2471. }];
  2472. }];
  2473. }];
  2474. }];
  2475. }
  2476. /** @fn nameForActionCodeOperation
  2477. @brief Returns the string value of the provided FIRActionCodeOperation value.
  2478. @param operation the FIRActionCodeOperation value to convert to string.
  2479. @return String conversion of FIRActionCodeOperation value.
  2480. */
  2481. - (NSString *)nameForActionCodeOperation:(FIRActionCodeOperation)operation {
  2482. switch (operation) {
  2483. case FIRActionCodeOperationVerifyEmail:
  2484. return @"Verify Email";
  2485. case FIRActionCodeOperationRecoverEmail:
  2486. return @"Recover Email";
  2487. case FIRActionCodeOperationPasswordReset:
  2488. return @"Password Reset";
  2489. case FIRActionCodeOperationEmailLink:
  2490. return @"Email Sign-In Link";
  2491. case FIRActionCodeOperationUnknown:
  2492. return @"Unknown action";
  2493. }
  2494. }
  2495. /** @fn updateEmail
  2496. @brief Changes the email address of the current user.
  2497. */
  2498. - (void)updateEmail {
  2499. [self showTextInputPromptWithMessage:@"Email Address:"
  2500. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2501. if (!userPressedOK || !userInput.length) {
  2502. return;
  2503. }
  2504. [self showSpinner:^{
  2505. [[self user] updateEmail:userInput completion:^(NSError *_Nullable error) {
  2506. if (error) {
  2507. [self logFailure:@"update email failed" error:error];
  2508. } else {
  2509. [self logSuccess:@"update email succeeded."];
  2510. }
  2511. [self hideSpinner:^{
  2512. [self showTypicalUIForUserUpdateResultsWithTitle:kUpdateEmailText error:error];
  2513. }];
  2514. }];
  2515. }];
  2516. }];
  2517. }
  2518. /** @fn updatePassword
  2519. @brief Updates the password of the current user.
  2520. */
  2521. - (void)updatePassword {
  2522. [self showTextInputPromptWithMessage:@"New Password:"
  2523. completionBlock:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  2524. if (!userPressedOK) {
  2525. return;
  2526. }
  2527. [self showSpinner:^{
  2528. [[self user] updatePassword:userInput completion:^(NSError *_Nullable error) {
  2529. if (error) {
  2530. [self logFailure:@"update password failed" error:error];
  2531. } else {
  2532. [self logSuccess:@"update password succeeded."];
  2533. }
  2534. [self hideSpinner:^{
  2535. [self showTypicalUIForUserUpdateResultsWithTitle:kUpdatePasswordText error:error];
  2536. }];
  2537. }];
  2538. }];
  2539. }];
  2540. }
  2541. /** @fn updateToSavedUser
  2542. @brief updates the current user to the saved user.
  2543. */
  2544. - (void)updateToSavedUser {
  2545. if(![AppManager auth].currentUser) {
  2546. NSLog(@"You must be signed in to perform this action");
  2547. return;
  2548. }
  2549. if (!_userInMemory) {
  2550. [self showMessagePrompt:[NSString stringWithFormat:@"You need an in-memory user to perform this"
  2551. "action, use the M+ button to save a user to memory.", nil]];
  2552. return;
  2553. }
  2554. [[AppManager auth] updateCurrentUser:_userInMemory completion:^(NSError *_Nullable error) {
  2555. if (error) {
  2556. [self showMessagePrompt:
  2557. [NSString stringWithFormat:@"An error Occurred: %@", error.localizedDescription]];
  2558. return;
  2559. }
  2560. }];
  2561. }
  2562. /** @fn createUser
  2563. @brief Creates a new user.
  2564. */
  2565. - (void)createUser {
  2566. [self showTextInputPromptWithMessage:@"Email:"
  2567. keyboardType:UIKeyboardTypeEmailAddress
  2568. completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
  2569. if (!userPressedOK || !email.length) {
  2570. return;
  2571. }
  2572. [self showTextInputPromptWithMessage:@"Password:"
  2573. completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
  2574. if (!userPressedOK) {
  2575. return;
  2576. }
  2577. [self showSpinner:^{
  2578. [[AppManager auth] createUserWithEmail:email
  2579. password:password
  2580. completion:^(FIRAuthDataResult *_Nullable result,
  2581. NSError *_Nullable error) {
  2582. if (error) {
  2583. [self logFailure:@"create user failed" error:error];
  2584. } else {
  2585. [self logSuccess:@"create user succeeded."];
  2586. }
  2587. [self hideSpinner:^{
  2588. [self showTypicalUIForUserUpdateResultsWithTitle:kCreateUserTitle error:error];
  2589. }];
  2590. }];
  2591. }];
  2592. }];
  2593. }];
  2594. }
  2595. /** @fn createUserAuthDataResult
  2596. @brief Creates a new user.
  2597. */
  2598. - (void)createUserAuthDataResult {
  2599. [self showTextInputPromptWithMessage:@"Email:"
  2600. keyboardType:UIKeyboardTypeEmailAddress
  2601. completionBlock:^(BOOL userPressedOK, NSString *_Nullable email) {
  2602. if (!userPressedOK || !email.length) {
  2603. return;
  2604. }
  2605. [self showTextInputPromptWithMessage:@"Password:"
  2606. completionBlock:^(BOOL userPressedOK, NSString *_Nullable password) {
  2607. if (!userPressedOK) {
  2608. return;
  2609. }
  2610. [self showSpinner:^{
  2611. [[AppManager auth] createUserAndRetrieveDataWithEmail:email
  2612. password:password
  2613. completion:^(FIRAuthDataResult *_Nullable result,
  2614. NSError *_Nullable error) {
  2615. if (error) {
  2616. [self logFailure:@"create user failed" error:error];
  2617. } else {
  2618. [self logSuccess:@"create user succeeded."];
  2619. [self log:result.user.uid];
  2620. }
  2621. [self hideSpinner:^{
  2622. [self showTypicalUIForUserUpdateResultsWithTitle:kCreateUserTitle error:error];
  2623. }];
  2624. }];
  2625. }];
  2626. }];
  2627. }];
  2628. }
  2629. /** @fn signInWithPhoneNumber
  2630. @brief Allows sign in with phone number using reCAPTCHA.
  2631. @param phoneNumber Number pass in string.
  2632. @completion A completion block to be executed after successful phone number sign in.
  2633. */
  2634. - (void)signInWithPhoneNumber:(NSString *_Nullable)phoneNumber
  2635. completion:(nullable testAutomationCallback)completion {
  2636. [self showSpinner:^{
  2637. [[AppManager phoneAuthProvider] verifyPhoneNumber:phoneNumber
  2638. UIDelegate:nil
  2639. completion:^(NSString *_Nullable verificationID,
  2640. NSError *_Nullable error) {
  2641. [self hideSpinner:^{
  2642. if (error) {
  2643. [self logFailure:@"failed to send verification code" error:error];
  2644. [self showMessagePrompt:error.localizedDescription];
  2645. if (completion) {
  2646. completion(error);
  2647. }
  2648. return;
  2649. }
  2650. [self logSuccess:@"Code sent"];
  2651. [self commonPhoneNumberInputWithTitle:@"Code"
  2652. Completion:^(NSString *_Nullable verificationCode) {
  2653. [self commontPhoneVerificationWithVerificationID:verificationID
  2654. verificationCode:verificationCode];
  2655. if (completion) {
  2656. completion(nil);
  2657. }
  2658. }];
  2659. }];
  2660. }];
  2661. }];
  2662. }
  2663. /** @fn verifyIOSClient
  2664. @brief Trigger verify iOS client by sending a verification code to the test number.
  2665. */
  2666. - (void)verifyIOSClient {
  2667. [[AppManager auth].tokenManager getTokenWithCallback:^(FIRAuthAPNSToken *_Nullable token,
  2668. NSError *_Nullable error) {
  2669. if (!token) {
  2670. [self logFailure:@"Verify iOS client failed." error:error];
  2671. return;
  2672. }
  2673. FIRVerifyClientRequest *request =
  2674. [[FIRVerifyClientRequest alloc] initWithAppToken:token.string
  2675. isSandbox:token.type == FIRAuthAPNSTokenTypeSandbox
  2676. requestConfiguration:[AppManager auth].requestConfiguration];
  2677. [FIRAuthBackend verifyClient:request callback:^(FIRVerifyClientResponse *_Nullable response,
  2678. NSError *_Nullable error) {
  2679. if (error) {
  2680. [self logFailure:@"Verify iOS client failed." error:error];
  2681. return;
  2682. }
  2683. NSTimeInterval timeout = [response.suggestedTimeOutDate timeIntervalSinceNow];
  2684. [[AppManager auth].appCredentialManager
  2685. didStartVerificationWithReceipt:response.receipt
  2686. timeout:timeout
  2687. callback:^(FIRAuthAppCredential *credential) {
  2688. if (!credential.secret) {
  2689. [self logFailure:@"Failed to receive remote notification to verify app identity."
  2690. error:error];
  2691. return;
  2692. }
  2693. NSString *testPhoneNumber = @"+16509964692";
  2694. FIRSendVerificationCodeRequest *request =
  2695. [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:testPhoneNumber
  2696. appCredential:credential
  2697. reCAPTCHAToken:nil
  2698. requestConfiguration:
  2699. [AppManager auth].requestConfiguration];
  2700. [FIRAuthBackend sendVerificationCode:request
  2701. callback:^(FIRSendVerificationCodeResponse *_Nullable response,
  2702. NSError *_Nullable error) {
  2703. if (error) {
  2704. [self logFailure:@"Verify iOS client failed." error:error];
  2705. return;
  2706. } else {
  2707. [self logSuccess:@"Verify iOS client succeeded."];
  2708. [self showMessagePrompt:@"Verify iOS client succeed."];
  2709. }
  2710. }];
  2711. }];
  2712. }];
  2713. }];
  2714. }
  2715. /** @fn signInWithPhoneNumberWithPrompt
  2716. @brief Allows sign in with phone number via popup prompt.
  2717. */
  2718. - (void)signInWithPhoneNumberWithPrompt {
  2719. [self commonPhoneNumberInputWithTitle:@"Phone #"
  2720. Completion:^(NSString *_Nullable phone) {
  2721. [self signInWithPhoneNumber:phone completion:nil];
  2722. }];
  2723. }
  2724. /** @fn commonPhoneNumberInputWithLabel:Completion
  2725. @brief Allows user input into a text field.
  2726. @param title of the promt.
  2727. */
  2728. - (void)commonPhoneNumberInputWithTitle:(NSString *)title
  2729. Completion:(textInputCompletionBlock)completion {
  2730. [self showTextInputPromptWithMessage:title
  2731. keyboardType:UIKeyboardTypePhonePad
  2732. completionBlock:^(BOOL userPressedOK, NSString *_Nullable phoneNumber) {
  2733. if (!userPressedOK) {
  2734. return;
  2735. }
  2736. completion(phoneNumber);
  2737. }];
  2738. }
  2739. /** @fn commonPhoneNumberInputWithLabel:Completion
  2740. @brief Finishes the phone number verification flow.
  2741. @param verificationID The verificationID from the backend.
  2742. @param verificationCode The verificationCode from the SMS message.
  2743. */
  2744. - (void)commontPhoneVerificationWithVerificationID:(NSString *)verificationID
  2745. verificationCode:(NSString *)verificationCode {
  2746. [self showSpinner:^{
  2747. FIRAuthCredential *credential =
  2748. [[AppManager phoneAuthProvider] credentialWithVerificationID:verificationID
  2749. verificationCode:verificationCode];
  2750. [[AppManager auth] signInAndRetrieveDataWithCredential:credential
  2751. completion:^(FIRAuthDataResult *_Nullable result,
  2752. NSError *_Nullable error) {
  2753. [self hideSpinner:^{
  2754. if (error) {
  2755. [self logFailure:@"failed to verify phone number" error:error];
  2756. [self showMessagePrompt:error.localizedDescription];
  2757. return;
  2758. }
  2759. if (_isNewUserToggleOn) {
  2760. NSString *newUserString = result.additionalUserInfo.isNewUser ?
  2761. @"New user" : @"Existing user";
  2762. [self showMessagePromptWithTitle:@"New or Existing"
  2763. message:newUserString
  2764. showCancelButton:NO
  2765. completion:nil];
  2766. }
  2767. }];
  2768. }];
  2769. }];
  2770. }
  2771. /** @fn updatePhoneNumber
  2772. @brief Allows adding a verified phone number to the currently signed user.
  2773. @param phoneNumber Number pass in string.
  2774. @completion A completion block to be executed after phone number is updated.
  2775. */
  2776. - (void)updatePhoneNumber:(NSString *_Nullable)phoneNumber
  2777. completion:(nullable testAutomationCallback)completion {
  2778. [self showSpinner:^{
  2779. [[AppManager phoneAuthProvider] verifyPhoneNumber:phoneNumber
  2780. UIDelegate:nil
  2781. completion:^(NSString *_Nullable verificationID,
  2782. NSError *_Nullable error) {
  2783. if (error) {
  2784. [self logFailure:@"failed to send verification code" error:error];
  2785. [self showMessagePrompt:error.localizedDescription];
  2786. if (completion) {
  2787. completion(error);
  2788. }
  2789. return;
  2790. }
  2791. [self logSuccess:@"Code sent"];
  2792. [self showTextInputPromptWithMessage:@"Verification code:"
  2793. keyboardType:UIKeyboardTypeNumberPad
  2794. completionBlock:^(BOOL userPressedOK,
  2795. NSString *_Nullable verificationCode) {
  2796. if (!userPressedOK || !verificationCode.length) {
  2797. return;
  2798. }
  2799. [self showSpinner:^{
  2800. FIRPhoneAuthCredential *credential =
  2801. [[AppManager phoneAuthProvider] credentialWithVerificationID:verificationID
  2802. verificationCode:verificationCode];
  2803. [[self user] updatePhoneNumberCredential:credential
  2804. completion:^(NSError *_Nullable error) {
  2805. if (error) {
  2806. [self logFailure:@"update phone number failed" error:error];
  2807. [self showMessagePrompt:error.localizedDescription];
  2808. if (completion) {
  2809. completion(error);
  2810. }
  2811. } else {
  2812. [self logSuccess:@"update phone number succeeded."];
  2813. if (completion) {
  2814. completion(nil);
  2815. }
  2816. }
  2817. }];
  2818. }];
  2819. }];
  2820. [self hideSpinner:^{
  2821. [self showTypicalUIForUserUpdateResultsWithTitle:kCreateUserTitle error:error];
  2822. }];
  2823. }];
  2824. }];
  2825. }
  2826. /** @fn updatePhoneNumberWithPrompt
  2827. @brief Allows adding a verified phone number to the currently signed user via popup prompt.
  2828. */
  2829. - (void)updatePhoneNumberWithPrompt {
  2830. [self showTextInputPromptWithMessage:@"Update Phone #:"
  2831. keyboardType:UIKeyboardTypePhonePad
  2832. completionBlock:^(BOOL userPressedOK, NSString *_Nullable phoneNumber) {
  2833. if (!userPressedOK || !phoneNumber.length) {
  2834. return;
  2835. }
  2836. [self updatePhoneNumber:phoneNumber completion:nil];
  2837. }];
  2838. }
  2839. /** @fn linkPhoneNumber
  2840. @brief Allows linking a verified phone number to the currently signed user.
  2841. @param phoneNumber Number pass in string.
  2842. @completion A completion block to be executed after linking phone number.
  2843. */
  2844. - (void)linkPhoneNumber:(NSString *_Nullable)phoneNumber
  2845. completion:(nullable testAutomationCallback)completion {
  2846. [self showSpinner:^{
  2847. [[AppManager phoneAuthProvider] verifyPhoneNumber:phoneNumber
  2848. UIDelegate:nil
  2849. completion:^(NSString *_Nullable verificationID,
  2850. NSError *_Nullable error) {
  2851. [self hideSpinner:^{
  2852. if (error) {
  2853. [self logFailure:@"failed to send verification code" error:error];
  2854. [self showMessagePrompt:error.localizedDescription];
  2855. if (completion) {
  2856. completion(error);
  2857. }
  2858. return;
  2859. }
  2860. [self logSuccess:@"Code sent"];
  2861. [self showTextInputPromptWithMessage:@"Verification code:"
  2862. keyboardType:UIKeyboardTypeNumberPad
  2863. completionBlock:^(BOOL userPressedOK,
  2864. NSString *_Nullable verificationCode) {
  2865. if (!userPressedOK || !verificationCode.length) {
  2866. return;
  2867. }
  2868. [self showSpinner:^{
  2869. FIRPhoneAuthCredential *credential =
  2870. [[AppManager phoneAuthProvider] credentialWithVerificationID:verificationID
  2871. verificationCode:verificationCode];
  2872. [[self user] linkWithCredential:credential
  2873. completion:^(FIRUser *_Nullable user,
  2874. NSError *_Nullable error) {
  2875. [self hideSpinner:^{
  2876. if (error) {
  2877. if (error.code == FIRAuthErrorCodeCredentialAlreadyInUse) {
  2878. [self showMessagePromptWithTitle:@"Phone number is already linked to "
  2879. @"another user"
  2880. message:@"Tap Ok to sign in with that user now."
  2881. showCancelButton:YES
  2882. completion:^(BOOL userPressedOK,
  2883. NSString *_Nullable userInput) {
  2884. if (userPressedOK) {
  2885. // If FIRAuthErrorCodeCredentialAlreadyInUse error, sign in with the
  2886. // provided credential.
  2887. [self showSpinner:^{
  2888. FIRPhoneAuthCredential *credential =
  2889. error.userInfo[FIRAuthUpdatedCredentialKey];
  2890. [[AppManager auth] signInWithCredential:credential
  2891. completion:^(FIRUser *_Nullable user,
  2892. NSError *_Nullable error) {
  2893. [self hideSpinner:^{
  2894. if (error) {
  2895. [self logFailure:@"failed to verify phone number" error:error];
  2896. [self showMessagePrompt:error.localizedDescription];
  2897. if (completion) {
  2898. completion(error);
  2899. }
  2900. return;
  2901. }
  2902. }];
  2903. }];
  2904. }];
  2905. }
  2906. }];
  2907. } else {
  2908. [self logFailure:@"link phone number failed" error:error];
  2909. [self showMessagePrompt:error.localizedDescription];
  2910. }
  2911. return;
  2912. }
  2913. [self logSuccess:@"link phone number succeeded."];
  2914. if (completion) {
  2915. completion(nil);
  2916. }
  2917. }];
  2918. }];
  2919. }];
  2920. }];
  2921. }];
  2922. }];
  2923. }];
  2924. }
  2925. /** @fn linkPhoneNumberWithPrompt
  2926. @brief Allows linking a verified phone number to the currently signed user via popup prompt.
  2927. */
  2928. - (void)linkPhoneNumberWithPrompt {
  2929. [self showTextInputPromptWithMessage:@"Phone #:"
  2930. keyboardType:UIKeyboardTypePhonePad
  2931. completionBlock:^(BOOL userPressedOK, NSString *_Nullable phoneNumber) {
  2932. if (!userPressedOK || !phoneNumber.length) {
  2933. return;
  2934. }
  2935. [self linkPhoneNumber:phoneNumber completion:nil];
  2936. }];
  2937. }
  2938. /** @fn signInAnonymously
  2939. @brief Signs in as an anonymous user.
  2940. */
  2941. - (void)signInAnonymously {
  2942. [[AppManager auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  2943. NSError *_Nullable error) {
  2944. if (error) {
  2945. [self logFailure:@"sign-in anonymously failed" error:error];
  2946. } else {
  2947. [self logSuccess:@"sign-in anonymously succeeded."];
  2948. [self log:[NSString stringWithFormat:@"User ID : %@", result.user.uid]];
  2949. }
  2950. [self showTypicalUIForUserUpdateResultsWithTitle:kSignInAnonymouslyButtonText error:error];
  2951. }];
  2952. }
  2953. /** @fn signInAnonymouslyAuthDataResult
  2954. @brief Signs in as an anonymous user, receiving an auth result containing a signed in user upon
  2955. success.
  2956. */
  2957. - (void)signInAnonymouslyAuthDataResult {
  2958. [[AppManager auth] signInAnonymouslyAndRetrieveDataWithCompletion:
  2959. ^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  2960. if (error) {
  2961. [self logFailure:@"sign-in anonymously failed" error:error];
  2962. } else {
  2963. [self logSuccess:@"sign-in anonymously succeeded."];
  2964. [self log:[NSString stringWithFormat:@"User ID : %@", authResult.user.uid]];
  2965. }
  2966. [self showTypicalUIForUserUpdateResultsWithTitle:kSignInAnonymouslyButtonText error:error];
  2967. }];
  2968. }
  2969. /** @fn signInWithGitHub
  2970. @brief Signs in as a GitHub user. Prompts the user for an access token and uses this access
  2971. token to create a GitHub (generic) credential for signing in.
  2972. */
  2973. - (void)signInWithGitHub {
  2974. [self showTextInputPromptWithMessage:@"GitHub Access Token:"
  2975. completionBlock:^(BOOL userPressedOK, NSString *_Nullable accessToken) {
  2976. if (!userPressedOK || !accessToken.length) {
  2977. return;
  2978. }
  2979. FIRAuthCredential *credential =
  2980. [FIROAuthProvider credentialWithProviderID:FIRGitHubAuthProviderID accessToken:accessToken];
  2981. if (credential) {
  2982. [[AppManager auth] signInWithCredential:credential
  2983. completion:^(FIRUser *_Nullable result,
  2984. NSError *_Nullable error) {
  2985. if (error) {
  2986. [self logFailure:@"sign-in with provider failed" error:error];
  2987. } else {
  2988. [self logSuccess:@"sign-in with provider succeeded."];
  2989. }
  2990. [self showTypicalUIForUserUpdateResultsWithTitle:@"Sign-In" error:error];
  2991. }];
  2992. }
  2993. }];
  2994. }
  2995. /** @fn deleteApp
  2996. @brief Deletes the @c FIRApp associated with our @c FIRAuth instance.
  2997. */
  2998. - (void)deleteApp {
  2999. [[FIRApp defaultApp] deleteApp:^(BOOL success) {
  3000. [self log:success ? @"App deleted successfully." : @"Failed to delete app."];
  3001. }];
  3002. }
  3003. /** @fn timeAuthInitialization
  3004. @brief Times FIRAuth instance initialization time.
  3005. */
  3006. - (void)timeAuthInitialization {
  3007. // Temporarily disable auth state listener to avoid interfering with the result.
  3008. [[NSNotificationCenter defaultCenter] removeObserver:self
  3009. name:FIRAuthStateDidChangeNotification
  3010. object:nil];
  3011. [self showSpinner:^() {
  3012. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^() {
  3013. const int numberOfRuns = 4096;
  3014. FIRApp *app = [FIRApp defaultApp];
  3015. NSString *key = NSStringFromClass([FIRAuth class]);
  3016. NSDate *startTime = [NSDate date];
  3017. for (int i = 0; i < numberOfRuns; i++) {
  3018. @autoreleasepool {
  3019. [FIRAppAssociationRegistration deregisterObjectWithHost:app key:key];
  3020. [FIRAuth auth];
  3021. }
  3022. }
  3023. NSDate *endTime = [NSDate date];
  3024. dispatch_async(dispatch_get_main_queue(), ^() {
  3025. // Re-enable auth state listener.
  3026. [[NSNotificationCenter defaultCenter] addObserver:self
  3027. selector:@selector(authStateChangedForAuth:)
  3028. name:FIRAuthStateDidChangeNotification
  3029. object:nil];
  3030. [self hideSpinner:^() {
  3031. NSTimeInterval averageTime = [endTime timeIntervalSinceDate:startTime] / numberOfRuns;
  3032. NSString *message = [NSString stringWithFormat:
  3033. @"Each [FIRAuth auth] takes average of %.3f ms for %d runs",
  3034. averageTime * 1000, numberOfRuns];
  3035. [self showMessagePromptWithTitle:@"Timing Result"
  3036. message:message
  3037. showCancelButton:NO
  3038. completion:nil];
  3039. }];
  3040. });
  3041. });
  3042. }];
  3043. }
  3044. #pragma mark - Helpers
  3045. /** @fn user
  3046. @brief The user to use for user operations. Takes into account the "use signed-in user vs. use
  3047. user in memory" setting.
  3048. */
  3049. - (FIRUser *)user {
  3050. return _useUserInMemory ? _userInMemory : [AppManager auth].currentUser;
  3051. }
  3052. /** @fn actionCodeSettings
  3053. @brief Returns the action code settings for this app.
  3054. */
  3055. - (FIRActionCodeSettings *)actionCodeSettings {
  3056. FIRActionCodeSettings *actionCodeSettings = [[FIRActionCodeSettings alloc] init];
  3057. actionCodeSettings.URL = _actionCodeContinueURL;
  3058. actionCodeSettings.handleCodeInApp = _actionCodeRequestType == ActionCodeRequestTypeInApp;
  3059. return actionCodeSettings;
  3060. }
  3061. /** @fn stringWithAdditionalUserInfo:
  3062. @brief Gets the string description of the additional user info.
  3063. @param additionalUserInfo The additional user info in question.
  3064. @return A string to description the additional user info.
  3065. */
  3066. - (NSString *)stringWithAdditionalUserInfo:(nullable FIRAdditionalUserInfo *)additionalUserInfo {
  3067. if (!additionalUserInfo) {
  3068. return @"(no additional user info)";
  3069. }
  3070. NSString *newUserString = additionalUserInfo.isNewUser ? @"new user" : @"existing user";
  3071. return [NSString stringWithFormat:@"%@: %@", newUserString, additionalUserInfo.profile];
  3072. }
  3073. /** @fn showTypicalUIForUserUpdateResultsWithTitle:error:
  3074. @brief Shows a prompt if error is non-nil with the localized description of the error.
  3075. @param resultsTitle The title of the prompt
  3076. @param error The error details to display if non-nil.
  3077. */
  3078. - (void)showTypicalUIForUserUpdateResultsWithTitle:(NSString *)resultsTitle
  3079. error:(NSError *)error {
  3080. if (error) {
  3081. NSString *message = [NSString stringWithFormat:@"%@ (%ld)\n%@",
  3082. error.domain,
  3083. (long)error.code,
  3084. error.localizedDescription];
  3085. if (error.code == FIRAuthErrorCodeAccountExistsWithDifferentCredential) {
  3086. NSString *errorEmail = error.userInfo[FIRAuthErrorUserInfoEmailKey];
  3087. resultsTitle = [NSString stringWithFormat:@"Existing email : %@", errorEmail];
  3088. }
  3089. [self showMessagePromptWithTitle:resultsTitle
  3090. message:message
  3091. showCancelButton:NO
  3092. completion:nil];
  3093. return;
  3094. }
  3095. [self updateUserInfo];
  3096. }
  3097. /** @fn showUIForAuthDataResultWithResult:error:
  3098. @brief Shows a prompt if error is non-nil with the localized description of the error.
  3099. @param result The auth data result if non-nil.
  3100. @param error The error details to display if non-nil.
  3101. */
  3102. - (void)showUIForAuthDataResultWithResult:(FIRAuthDataResult *)result
  3103. error:(NSError *)error {
  3104. NSString *errorMessage = [NSString stringWithFormat:@"%@ (%ld)\n%@",
  3105. error.domain ?: @"",
  3106. (long)error.code,
  3107. error.localizedDescription ?: @""];
  3108. [self showMessagePromptWithTitle:@"Error"
  3109. message:errorMessage
  3110. showCancelButton:NO
  3111. completion:^(BOOL userPressedOK,
  3112. NSString *_Nullable userInput) {
  3113. [self showMessagePromptWithTitle:@"Profile Info"
  3114. message:[self stringWithAdditionalUserInfo:result.additionalUserInfo]
  3115. showCancelButton:NO
  3116. completion:nil];
  3117. [self updateUserInfo];
  3118. }];
  3119. }
  3120. - (void)doSignInWithCustomToken:(NSString *_Nullable)userEnteredTokenText {
  3121. [[AppManager auth] signInWithCustomToken:userEnteredTokenText
  3122. completion:^(FIRAuthDataResult *_Nullable result,
  3123. NSError *_Nullable error) {
  3124. if (error) {
  3125. [self logFailure:@"sign-in with custom token failed" error:error];
  3126. [self showMessagePromptWithTitle:kSignInErrorAlertTitle
  3127. message:error.localizedDescription
  3128. showCancelButton:NO
  3129. completion:nil];
  3130. return;
  3131. }
  3132. [self logSuccess:@"sign-in with custom token succeeded."];
  3133. [self showMessagePromptWithTitle:kSignedInAlertTitle
  3134. message:result.user.displayName
  3135. showCancelButton:NO
  3136. completion:nil];
  3137. }];
  3138. }
  3139. - (void)doSignInAndRetrieveDataWithCustomToken:(NSString *_Nullable)userEnteredTokenText {
  3140. [[AppManager auth] signInAndRetrieveDataWithCustomToken:userEnteredTokenText
  3141. completion:^(FIRAuthDataResult *_Nullable result,
  3142. NSError *_Nullable error) {
  3143. if (error) {
  3144. [self logFailure:@"sign-in with custom token failed" error:error];
  3145. [self showMessagePromptWithTitle:kSignInErrorAlertTitle
  3146. message:error.localizedDescription
  3147. showCancelButton:NO
  3148. completion:nil];
  3149. return;
  3150. }
  3151. [self logSuccess:@"sign-in with custom token succeeded."];
  3152. [self showMessagePromptWithTitle:kSignedInAlertTitle
  3153. message:result.user.displayName
  3154. showCancelButton:NO
  3155. completion:nil];
  3156. }];
  3157. }
  3158. - (void)updateUserInfo {
  3159. [_userInfoTableViewCell updateContentsWithUser:[AppManager auth].currentUser];
  3160. [_userInMemoryInfoTableViewCell updateContentsWithUser:_userInMemory];
  3161. }
  3162. - (void)authStateChangedForAuth:(NSNotification *)notification {
  3163. [self updateUserInfo];
  3164. if (notification) {
  3165. [self log:[NSString stringWithFormat:
  3166. @"received FIRAuthStateDidChange notification on user '%@'.",
  3167. ((FIRAuth *)notification.object).currentUser.uid]];
  3168. }
  3169. }
  3170. /** @fn clearConsole
  3171. @brief Clears the console text.
  3172. */
  3173. - (IBAction)clearConsole:(id)sender {
  3174. [_consoleString appendString:@"\n\n"];
  3175. _consoleTextView.text = @"";
  3176. }
  3177. /** @fn copyConsole
  3178. @brief Copies the current console string to the clipboard.
  3179. */
  3180. - (IBAction)copyConsole:(id)sender {
  3181. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  3182. pasteboard.string = _consoleString ?: @"";
  3183. }
  3184. @end
  3185. NS_ASSUME_NONNULL_END