MainViewController.m 117 KB

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