MainViewController.m 124 KB

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