MainViewController.m 112 KB

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