MainViewController.m 133 KB

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