MainViewController.m 111 KB

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