MainViewController.m 109 KB

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