MainViewController.m 124 KB

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