MainViewController.m 113 KB

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