MainViewController.m 101 KB

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