MainViewController.m 97 KB

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