MainViewController.m 97 KB

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