MainViewController.m 124 KB

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