MainViewController.m 130 KB

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