MainViewController.m 142 KB

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