FIRAuth.m 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274
  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 <Foundation/Foundation.h>
  17. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  18. #if __has_include(<UIKit/UIKit.h>)
  19. #import <UIKit/UIKit.h>
  20. #endif
  21. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  22. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  23. #import <GoogleUtilities/GULSceneDelegateSwizzler.h>
  24. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FirebaseAuth.h"
  25. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  26. #import "FirebaseAuth/Sources/Auth/FIRAuthDataResult_Internal.h"
  27. #import "FirebaseAuth/Sources/Auth/FIRAuthDispatcher.h"
  28. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  29. #import "FirebaseAuth/Sources/Auth/FIRAuthOperationType.h"
  30. #import "FirebaseAuth/Sources/AuthProvider/Email/FIREmailPasswordAuthCredential.h"
  31. #import "FirebaseAuth/Sources/AuthProvider/FIRAuthCredential_Internal.h"
  32. #import "FirebaseAuth/Sources/AuthProvider/GameCenter/FIRGameCenterAuthCredential.h"
  33. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  34. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  35. #import "FirebaseAuth/Sources/Backend/FIRAuthRequestConfiguration.h"
  36. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIRequest.h"
  37. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIResponse.h"
  38. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
  39. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
  40. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
  41. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
  42. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordRequest.h"
  43. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordResponse.h"
  44. #import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeRequest.h"
  45. #import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeResponse.h"
  46. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
  47. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
  48. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterRequest.h"
  49. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterResponse.h"
  50. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
  51. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
  52. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
  53. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
  54. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
  55. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
  56. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
  57. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
  58. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
  59. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
  60. #import "FirebaseAuth/Sources/Storage/FIRAuthKeychainServices.h"
  61. #import "FirebaseAuth/Sources/SystemService/FIRAuthStoredUserManager.h"
  62. #import "FirebaseAuth/Sources/User/FIRAdditionalUserInfo_Internal.h"
  63. #import "FirebaseAuth/Sources/User/FIRUser_Internal.h"
  64. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  65. #import "FirebaseAuth/Sources/Utilities/FIRAuthExceptionUtils.h"
  66. #import "FirebaseAuth/Sources/Utilities/FIRAuthWebUtils.h"
  67. #if TARGET_OS_IOS
  68. #import "FirebaseAuth/Sources/AuthProvider/Phone/FIRPhoneAuthCredential_Internal.h"
  69. #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSToken.h"
  70. #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSTokenManager.h"
  71. #import "FirebaseAuth/Sources/SystemService/FIRAuthAppCredentialManager.h"
  72. #import "FirebaseAuth/Sources/SystemService/FIRAuthNotificationManager.h"
  73. #import "FirebaseAuth/Sources/Utilities/FIRAuthURLPresenter.h"
  74. #endif
  75. NS_ASSUME_NONNULL_BEGIN
  76. #pragma mark-- Logger Service String.
  77. FIRLoggerService kFIRLoggerAuth = @"[Firebase/Auth]";
  78. #pragma mark - Constants
  79. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  80. const NSNotificationName FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification";
  81. #else
  82. NSString *const FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification";
  83. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  84. /** @var kMaxWaitTimeForBackoff
  85. @brief The maximum wait time before attempting to retry auto refreshing tokens after a failed
  86. attempt.
  87. @remarks This is the upper limit (in seconds) of the exponential backoff used for retrying
  88. token refresh.
  89. */
  90. static NSTimeInterval kMaxWaitTimeForBackoff = 16 * 60;
  91. /** @var kTokenRefreshHeadStart
  92. @brief The amount of time before the token expires that proactive refresh should be attempted.
  93. */
  94. NSTimeInterval kTokenRefreshHeadStart = 5 * 60;
  95. /** @var kUserKey
  96. @brief Key of user stored in the keychain. Prefixed with a Firebase app name.
  97. */
  98. static NSString *const kUserKey = @"%@_firebase_user";
  99. /** @var kMissingEmailInvalidParameterExceptionReason
  100. @brief The reason for @c invalidParameterException when the email used to initiate password
  101. reset is nil.
  102. */
  103. static NSString *const kMissingEmailInvalidParameterExceptionReason =
  104. @"The email used to initiate password reset cannot be nil.";
  105. /** @var kHandleCodeInAppFalseExceptionReason
  106. @brief The reason for @c invalidParameterException when the handleCodeInApp parameter is false
  107. on the ActionCodeSettings object used to send the link for Email-link Authentication.
  108. */
  109. static NSString *const kHandleCodeInAppFalseExceptionReason =
  110. @"You must set handleCodeInApp in your ActionCodeSettings to true for Email-link "
  111. "Authentication.";
  112. static NSString *const kInvalidEmailSignInLinkExceptionMessage =
  113. @"The link provided is not valid for email/link sign-in. Please check the link by calling "
  114. "isSignInWithEmailLink:link: on Auth before attempting to use it for email/link sign-in.";
  115. /** @var kPasswordResetRequestType
  116. @brief The action code type value for resetting password in the check action code response.
  117. */
  118. static NSString *const kPasswordResetRequestType = @"PASSWORD_RESET";
  119. /** @var kVerifyEmailRequestType
  120. @brief The action code type value for verifying email in the check action code response.
  121. */
  122. static NSString *const kVerifyEmailRequestType = @"VERIFY_EMAIL";
  123. /** @var kRecoverEmailRequestType
  124. @brief The action code type value for recovering email in the check action code response.
  125. */
  126. static NSString *const kRecoverEmailRequestType = @"RECOVER_EMAIL";
  127. /** @var kEmailLinkSignInRequestType
  128. @brief The action code type value for an email sign-in link in the check action code response.
  129. */
  130. static NSString *const kEmailLinkSignInRequestType = @"EMAIL_SIGNIN";
  131. /** @var kVerifyAndChangeEmailRequestType
  132. @brief The action code type value for verifing and changing email in the check action code
  133. response.
  134. */
  135. static NSString *const kVerifyAndChangeEmailRequestType = @"VERIFY_AND_CHANGE_EMAIL";
  136. /** @var kRevertSecondFactorAdditionRequestType
  137. @brief The action code type value for reverting second factor addition in the check action code
  138. response.
  139. */
  140. static NSString *const kRevertSecondFactorAdditionRequestType = @"REVERT_SECOND_FACTOR_ADDITION";
  141. /** @var kMissingPasswordReason
  142. @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown.
  143. @remarks This error message will be localized in the future.
  144. */
  145. static NSString *const kMissingPasswordReason = @"Missing Password";
  146. /** @var gKeychainServiceNameForAppName
  147. @brief A map from Firebase app name to keychain service names.
  148. @remarks This map is needed for looking up the keychain service name after the FIRApp instance
  149. is deleted, to remove the associated keychain item. Accessing should occur within a
  150. @syncronized([FIRAuth class]) context.
  151. */
  152. static NSMutableDictionary *gKeychainServiceNameForAppName;
  153. #pragma mark - FIRActionCodeInfo
  154. @interface FIRActionCodeInfo ()
  155. /**
  156. @brief The operation being performed.
  157. */
  158. @property(nonatomic, readwrite) FIRActionCodeOperation operation;
  159. /** @property email
  160. @brief The email address to which the code was sent. The new email address in the case of
  161. FIRActionCodeOperationRecoverEmail.
  162. */
  163. @property(nonatomic, nullable, readwrite, copy) NSString *email;
  164. /** @property previousEmail
  165. @brief The current email address in the case of FIRActionCodeOperationRecoverEmail.
  166. */
  167. @property(nonatomic, nullable, readwrite, copy) NSString *previousEmail;
  168. #if TARGET_OS_IOS
  169. /** @property multiFactorInfo
  170. @brief The MultiFactorInfo object of the second factor to be reverted in case of
  171. FIRActionCodeMultiFactorInfoKey.
  172. */
  173. @property(nonatomic, nullable, readwrite) FIRMultiFactorInfo *multiFactorInfo;
  174. #endif
  175. @end
  176. @implementation FIRActionCodeInfo
  177. - (instancetype)initWithOperation:(FIRActionCodeOperation)operation
  178. email:(NSString *)email
  179. newEmail:(nullable NSString *)newEmail {
  180. self = [super init];
  181. if (self) {
  182. _operation = operation;
  183. if (newEmail) {
  184. _email = [newEmail copy];
  185. _previousEmail = [email copy];
  186. } else {
  187. _email = [email copy];
  188. }
  189. }
  190. return self;
  191. }
  192. /** @fn actionCodeOperationForRequestType:
  193. @brief Returns the corresponding operation type per provided request type string.
  194. @param requestType Request type returned in in the server response.
  195. @return The corresponding FIRActionCodeOperation for the supplied request type.
  196. */
  197. + (FIRActionCodeOperation)actionCodeOperationForRequestType:(NSString *)requestType {
  198. if ([requestType isEqualToString:kPasswordResetRequestType]) {
  199. return FIRActionCodeOperationPasswordReset;
  200. }
  201. if ([requestType isEqualToString:kVerifyEmailRequestType]) {
  202. return FIRActionCodeOperationVerifyEmail;
  203. }
  204. if ([requestType isEqualToString:kRecoverEmailRequestType]) {
  205. return FIRActionCodeOperationRecoverEmail;
  206. }
  207. if ([requestType isEqualToString:kEmailLinkSignInRequestType]) {
  208. return FIRActionCodeOperationEmailLink;
  209. }
  210. if ([requestType isEqualToString:kVerifyAndChangeEmailRequestType]) {
  211. return FIRActionCodeOperationVerifyAndChangeEmail;
  212. }
  213. if ([requestType isEqualToString:kRevertSecondFactorAdditionRequestType]) {
  214. return FIRActionCodeOperationRevertSecondFactorAddition;
  215. }
  216. return FIRActionCodeOperationUnknown;
  217. }
  218. @end
  219. #pragma mark - FIRActionCodeURL
  220. @implementation FIRActionCodeURL
  221. /** @fn FIRAuthParseURL:NSString
  222. @brief Parses an incoming URL into all available query items.
  223. @param urlString The url to be parsed.
  224. @return A dictionary of available query items in the target URL.
  225. */
  226. + (NSDictionary<NSString *, NSString *> *)parseURL:(NSString *)urlString {
  227. NSString *linkURL = [NSURLComponents componentsWithString:urlString].query;
  228. if (!linkURL) {
  229. return @{};
  230. }
  231. NSArray<NSString *> *URLComponents = [linkURL componentsSeparatedByString:@"&"];
  232. NSMutableDictionary<NSString *, NSString *> *queryItems =
  233. [[NSMutableDictionary alloc] initWithCapacity:URLComponents.count];
  234. for (NSString *component in URLComponents) {
  235. NSRange equalRange = [component rangeOfString:@"="];
  236. if (equalRange.location != NSNotFound) {
  237. NSString *queryItemKey =
  238. [[component substringToIndex:equalRange.location] stringByRemovingPercentEncoding];
  239. NSString *queryItemValue =
  240. [[component substringFromIndex:equalRange.location + 1] stringByRemovingPercentEncoding];
  241. if (queryItemKey && queryItemValue) {
  242. queryItems[queryItemKey] = queryItemValue;
  243. }
  244. }
  245. }
  246. return queryItems;
  247. }
  248. + (nullable instancetype)actionCodeURLWithLink:(NSString *)link {
  249. NSDictionary<NSString *, NSString *> *queryItems = [FIRActionCodeURL parseURL:link];
  250. if (!queryItems.count) {
  251. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  252. queryItems = [FIRActionCodeURL parseURL:urlComponents.query];
  253. }
  254. if (!queryItems.count) {
  255. return nil;
  256. }
  257. NSString *APIKey = queryItems[@"apiKey"];
  258. NSString *actionCode = queryItems[@"oobCode"];
  259. NSString *continueURLString = queryItems[@"continueUrl"];
  260. NSString *languageCode = queryItems[@"languageCode"];
  261. NSString *mode = queryItems[@"mode"];
  262. NSString *tenantID = queryItems[@"tenantID"];
  263. return [[FIRActionCodeURL alloc] initWithAPIKey:APIKey
  264. actionCode:actionCode
  265. continueURLString:continueURLString
  266. languageCode:languageCode
  267. mode:mode
  268. tenantID:tenantID];
  269. }
  270. - (nullable instancetype)initWithAPIKey:(NSString *)APIKey
  271. actionCode:(NSString *)actionCode
  272. continueURLString:(NSString *)continueURLString
  273. languageCode:(NSString *)languageCode
  274. mode:(NSString *)mode
  275. tenantID:(NSString *)tenantID {
  276. self = [super init];
  277. if (self) {
  278. _APIKey = APIKey;
  279. _operation = [FIRActionCodeInfo actionCodeOperationForRequestType:mode];
  280. _code = actionCode;
  281. _continueURL = [NSURL URLWithString:continueURLString];
  282. _languageCode = languageCode;
  283. }
  284. return self;
  285. }
  286. @end
  287. #pragma mark - FIRAuth
  288. #if TARGET_OS_IOS
  289. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  290. @interface FIRAuth () <UIApplicationDelegate,
  291. UISceneDelegate,
  292. FIRLibrary,
  293. FIRComponentLifecycleMaintainer>
  294. #else
  295. @interface FIRAuth () <UIApplicationDelegate, FIRLibrary, FIRComponentLifecycleMaintainer>
  296. #endif
  297. #else
  298. @interface FIRAuth () <FIRLibrary, FIRComponentLifecycleMaintainer>
  299. #endif
  300. /** @property firebaseAppId
  301. @brief The Firebase app ID.
  302. */
  303. @property(nonatomic, copy, readonly) NSString *firebaseAppId;
  304. /** @property additionalFrameworkMarker
  305. @brief Additional framework marker that will be added as part of the header of every request.
  306. */
  307. @property(nonatomic, copy, nullable) NSString *additionalFrameworkMarker;
  308. /** @property storedUserManager
  309. @brief The stored user manager.
  310. */
  311. @property(nonatomic, strong, nullable) FIRAuthStoredUserManager *storedUserManager;
  312. /** @fn initWithApp:
  313. @brief Creates a @c FIRAuth instance associated with the provided @c FIRApp instance.
  314. @param app The application to associate the auth instance with.
  315. */
  316. - (instancetype)initWithApp:(FIRApp *)app;
  317. @end
  318. @implementation FIRAuth {
  319. /** @var _currentUser
  320. @brief The current user.
  321. */
  322. FIRUser *_currentUser;
  323. /** @var _firebaseAppName
  324. @brief The Firebase app name.
  325. */
  326. NSString *_firebaseAppName;
  327. /** @var _listenerHandles
  328. @brief Handles returned from @c NSNotificationCenter for blocks which are "auth state did
  329. change" notification listeners.
  330. @remarks Mutations should occur within a @syncronized(self) context.
  331. */
  332. NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_listenerHandles;
  333. /** @var _keychainServices
  334. @brief The keychain service.
  335. */
  336. FIRAuthKeychainServices *_keychainServices;
  337. /** @var _lastNotifiedUserToken
  338. @brief The user access (ID) token used last time for posting auth state changed notification.
  339. */
  340. NSString *_lastNotifiedUserToken;
  341. /** @var _autoRefreshTokens
  342. @brief This flag denotes whether or not tokens should be automatically refreshed.
  343. @remarks Will only be set to @YES if the another Firebase service is included (additionally to
  344. Firebase Auth).
  345. */
  346. BOOL _autoRefreshTokens;
  347. /** @var _autoRefreshScheduled
  348. @brief Whether or not token auto-refresh is currently scheduled.
  349. */
  350. BOOL _autoRefreshScheduled;
  351. /** @var _isAppInBackground
  352. @brief A flag that is set to YES if the app is put in the background and no when the app is
  353. returned to the foreground.
  354. */
  355. BOOL _isAppInBackground;
  356. /** @var _applicationDidBecomeActiveObserver
  357. @brief An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification.
  358. */
  359. id<NSObject> _applicationDidBecomeActiveObserver;
  360. /** @var _applicationDidBecomeActiveObserver
  361. @brief An opaque object to act as the observer for
  362. UIApplicationDidEnterBackgroundNotification.
  363. */
  364. id<NSObject> _applicationDidEnterBackgroundObserver;
  365. }
  366. + (void)load {
  367. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-auth"];
  368. }
  369. + (void)initialize {
  370. gKeychainServiceNameForAppName = [[NSMutableDictionary alloc] init];
  371. }
  372. + (FIRAuth *)auth {
  373. FIRApp *defaultApp = [FIRApp defaultApp];
  374. if (!defaultApp) {
  375. [NSException
  376. raise:NSInternalInconsistencyException
  377. format:@"The default FirebaseApp instance must be configured before the default Auth"
  378. @"instance can be initialized. One way to ensure this is to call "
  379. @"`FirebaseApp.configure()` in the App Delegate's "
  380. @"`application(_:didFinishLaunchingWithOptions:)` (or the `@main` struct's "
  381. @"initializer in SwiftUI)."];
  382. }
  383. return [self authWithApp:defaultApp];
  384. }
  385. + (FIRAuth *)authWithApp:(FIRApp *)app {
  386. // Get the instance of Auth from the container, which will create or return the cached instance
  387. // associated with this app.
  388. id<FIRAuthInterop> auth = FIR_COMPONENT(FIRAuthInterop, app.container);
  389. return (FIRAuth *)auth;
  390. }
  391. - (instancetype)initWithApp:(FIRApp *)app {
  392. [FIRAuth setKeychainServiceNameForApp:app];
  393. self = [self initWithAPIKey:app.options.APIKey appName:app.name];
  394. if (self) {
  395. _app = app;
  396. #if TARGET_OS_IOS
  397. _authURLPresenter = [[FIRAuthURLPresenter alloc] init];
  398. #endif
  399. }
  400. return self;
  401. }
  402. - (nullable instancetype)initWithAPIKey:(NSString *)APIKey appName:(NSString *)appName {
  403. self = [super init];
  404. if (self) {
  405. _listenerHandles = [NSMutableArray array];
  406. _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey];
  407. _firebaseAppName = [appName copy];
  408. #if TARGET_OS_IOS
  409. _settings = [[FIRAuthSettings alloc] init];
  410. static Class applicationClass = nil;
  411. // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication
  412. // responds to it.
  413. if (![GULAppEnvironmentUtil isAppExtension]) {
  414. Class cls = NSClassFromString(@"UIApplication");
  415. if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) {
  416. applicationClass = cls;
  417. }
  418. }
  419. UIApplication *application = [applicationClass sharedApplication];
  420. [GULAppDelegateSwizzler proxyOriginalDelegateIncludingAPNSMethods];
  421. [GULSceneDelegateSwizzler proxyOriginalSceneDelegate];
  422. #endif // TARGET_OS_IOS
  423. // Continue with the rest of initialization in the work thread.
  424. __weak FIRAuth *weakSelf = self;
  425. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  426. // Load current user from Keychain.
  427. FIRAuth *strongSelf = weakSelf;
  428. if (!strongSelf) {
  429. return;
  430. }
  431. NSString *keychainServiceName =
  432. [FIRAuth keychainServiceNameForAppName:strongSelf->_firebaseAppName];
  433. if (keychainServiceName) {
  434. strongSelf->_keychainServices =
  435. [[FIRAuthKeychainServices alloc] initWithService:keychainServiceName];
  436. strongSelf.storedUserManager =
  437. [[FIRAuthStoredUserManager alloc] initWithServiceName:keychainServiceName];
  438. }
  439. NSError *error;
  440. NSString *storedUserAccessGroup =
  441. [strongSelf.storedUserManager getStoredUserAccessGroupWithError:&error];
  442. if (!error) {
  443. if (!storedUserAccessGroup) {
  444. FIRUser *user;
  445. if ([strongSelf getUser:&user error:&error]) {
  446. strongSelf.tenantID = user.tenantID;
  447. [strongSelf updateCurrentUser:user byForce:NO savingToDisk:NO error:&error];
  448. self->_lastNotifiedUserToken = user.rawAccessToken;
  449. } else {
  450. FIRLogError(kFIRLoggerAuth, @"I-AUT000001",
  451. @"Error loading saved user when starting up: %@", error);
  452. }
  453. } else {
  454. [strongSelf internalUseUserAccessGroup:storedUserAccessGroup error:&error];
  455. if (error) {
  456. FIRLogError(kFIRLoggerAuth, @"I-AUT000001",
  457. @"Error loading saved user when starting up: %@", error);
  458. }
  459. }
  460. } else {
  461. FIRLogError(kFIRLoggerAuth, @"I-AUT000001",
  462. @"Error loading saved user when starting up: %@", error);
  463. }
  464. #if TARGET_OS_IOS
  465. // Initialize for phone number auth.
  466. strongSelf->_tokenManager = [[FIRAuthAPNSTokenManager alloc] initWithApplication:application];
  467. strongSelf->_appCredentialManager =
  468. [[FIRAuthAppCredentialManager alloc] initWithKeychain:strongSelf->_keychainServices];
  469. strongSelf->_notificationManager = [[FIRAuthNotificationManager alloc]
  470. initWithApplication:application
  471. appCredentialManager:strongSelf->_appCredentialManager];
  472. [GULAppDelegateSwizzler registerAppDelegateInterceptor:strongSelf];
  473. #if ((TARGET_OS_IOS || TARGET_OS_TV) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 130000))
  474. if (@available(iOS 13, tvos 13, *)) {
  475. [GULSceneDelegateSwizzler registerSceneDelegateInterceptor:strongSelf];
  476. }
  477. #endif // ((TARGET_OS_IOS || TARGET_OS_TV) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 130000))
  478. #endif // TARGET_OS_IOS
  479. });
  480. }
  481. return self;
  482. }
  483. - (void)dealloc {
  484. @synchronized(self) {
  485. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  486. while (_listenerHandles.count != 0) {
  487. FIRAuthStateDidChangeListenerHandle handleToRemove = _listenerHandles.lastObject;
  488. [defaultCenter removeObserver:handleToRemove];
  489. [_listenerHandles removeLastObject];
  490. }
  491. #if TARGET_OS_IOS
  492. [defaultCenter removeObserver:_applicationDidBecomeActiveObserver
  493. name:UIApplicationDidBecomeActiveNotification
  494. object:nil];
  495. [defaultCenter removeObserver:_applicationDidEnterBackgroundObserver
  496. name:UIApplicationDidEnterBackgroundNotification
  497. object:nil];
  498. #endif
  499. }
  500. }
  501. #pragma mark - Public API
  502. - (nullable FIRUser *)currentUser {
  503. __block FIRUser *result;
  504. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  505. result = self->_currentUser;
  506. });
  507. return result;
  508. }
  509. - (void)signInWithProvider:(id<FIRFederatedAuthProvider>)provider
  510. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  511. completion:(nullable FIRAuthDataResultCallback)completion {
  512. #if TARGET_OS_IOS
  513. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  514. FIRAuthDataResultCallback decoratedCallback =
  515. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  516. [provider getCredentialWithUIDelegate:UIDelegate
  517. completion:^(FIRAuthCredential *_Nullable credential,
  518. NSError *_Nullable error) {
  519. if (error) {
  520. decoratedCallback(nil, error);
  521. return;
  522. }
  523. [self
  524. internalSignInAndRetrieveDataWithCredential:credential
  525. isReauthentication:NO
  526. callback:decoratedCallback];
  527. }];
  528. });
  529. #endif // TARGET_OS_IOS
  530. }
  531. - (void)fetchSignInMethodsForEmail:(nonnull NSString *)email
  532. completion:(nullable FIRSignInMethodQueryCallback)completion {
  533. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  534. FIRCreateAuthURIRequest *request =
  535. [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email
  536. continueURI:@"http://www.google.com/"
  537. requestConfiguration:self->_requestConfiguration];
  538. [FIRAuthBackend
  539. createAuthURI:request
  540. callback:^(FIRCreateAuthURIResponse *_Nullable response, NSError *_Nullable error) {
  541. if (completion) {
  542. dispatch_async(dispatch_get_main_queue(), ^{
  543. completion(response.signinMethods, error);
  544. });
  545. }
  546. }];
  547. });
  548. }
  549. - (void)signInWithEmail:(NSString *)email
  550. password:(NSString *)password
  551. completion:(nullable FIRAuthDataResultCallback)completion {
  552. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  553. FIRAuthDataResultCallback decoratedCallback =
  554. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  555. [self internalSignInAndRetrieveDataWithEmail:email
  556. password:password
  557. completion:^(FIRAuthDataResult *_Nullable authResult,
  558. NSError *_Nullable error) {
  559. decoratedCallback(authResult, error);
  560. }];
  561. });
  562. }
  563. - (void)signInWithEmail:(NSString *)email
  564. link:(NSString *)link
  565. completion:(nullable FIRAuthDataResultCallback)completion {
  566. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  567. FIRAuthDataResultCallback decoratedCallback =
  568. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  569. FIREmailPasswordAuthCredential *credential =
  570. [[FIREmailPasswordAuthCredential alloc] initWithEmail:email link:link];
  571. [self internalSignInAndRetrieveDataWithCredential:credential
  572. isReauthentication:NO
  573. callback:^(FIRAuthDataResult *_Nullable authResult,
  574. NSError *_Nullable error) {
  575. decoratedCallback(authResult, error);
  576. }];
  577. });
  578. }
  579. /** @fn signInWithEmail:password:callback:
  580. @brief Signs in using an email address and password.
  581. @param email The user's email address.
  582. @param password The user's password.
  583. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  584. asynchronously on the global auth work queue in the future.
  585. @remarks This is the internal counterpart of this method, which uses a callback that does not
  586. update the current user.
  587. */
  588. - (void)signInWithEmail:(NSString *)email
  589. password:(NSString *)password
  590. callback:(FIRAuthResultCallback)callback {
  591. FIRVerifyPasswordRequest *request =
  592. [[FIRVerifyPasswordRequest alloc] initWithEmail:email
  593. password:password
  594. requestConfiguration:_requestConfiguration];
  595. if (![request.password length]) {
  596. callback(nil, [FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  597. return;
  598. }
  599. [FIRAuthBackend
  600. verifyPassword:request
  601. callback:^(FIRVerifyPasswordResponse *_Nullable response, NSError *_Nullable error) {
  602. if (error) {
  603. callback(nil, error);
  604. return;
  605. }
  606. [self completeSignInWithAccessToken:response.IDToken
  607. accessTokenExpirationDate:response.approximateExpirationDate
  608. refreshToken:response.refreshToken
  609. anonymous:NO
  610. callback:callback];
  611. }];
  612. }
  613. /** @fn internalSignInAndRetrieveDataWithEmail:password:callback:
  614. @brief Signs in using an email address and password.
  615. @param email The user's email address.
  616. @param password The user's password.
  617. @param completion A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  618. asynchronously on the global auth work queue in the future.
  619. @remarks This is the internal counterpart of this method, which uses a callback that does not
  620. update the current user.
  621. */
  622. - (void)internalSignInAndRetrieveDataWithEmail:(NSString *)email
  623. password:(NSString *)password
  624. completion:(FIRAuthDataResultCallback)completion {
  625. FIREmailPasswordAuthCredential *credentail =
  626. [[FIREmailPasswordAuthCredential alloc] initWithEmail:email password:password];
  627. [self internalSignInAndRetrieveDataWithCredential:credentail
  628. isReauthentication:NO
  629. callback:completion];
  630. }
  631. /** @fn signInAndRetrieveDataWithGameCenterCredential:callback:
  632. @brief Signs in using a game center credential.
  633. @param credential The Game Center Auth Credential used to sign in.
  634. @param callback A block which is invoked when the sign in finished (or is cancelled). Invoked
  635. asynchronously on the global auth work queue in the future.
  636. */
  637. - (void)signInAndRetrieveDataWithGameCenterCredential:(FIRGameCenterAuthCredential *)credential
  638. callback:(FIRAuthDataResultCallback)callback {
  639. FIRSignInWithGameCenterRequest *request =
  640. [[FIRSignInWithGameCenterRequest alloc] initWithPlayerID:credential.playerID
  641. publicKeyURL:credential.publicKeyURL
  642. signature:credential.signature
  643. salt:credential.salt
  644. timestamp:credential.timestamp
  645. displayName:credential.displayName
  646. requestConfiguration:_requestConfiguration];
  647. [FIRAuthBackend
  648. signInWithGameCenter:request
  649. callback:^(FIRSignInWithGameCenterResponse *_Nullable response,
  650. NSError *_Nullable error) {
  651. if (error) {
  652. if (callback) {
  653. callback(nil, error);
  654. }
  655. return;
  656. }
  657. [self
  658. completeSignInWithAccessToken:response.IDToken
  659. accessTokenExpirationDate:response.approximateExpirationDate
  660. refreshToken:response.refreshToken
  661. anonymous:NO
  662. callback:^(FIRUser *_Nullable user,
  663. NSError *_Nullable error) {
  664. if (error && callback) {
  665. callback(nil, error);
  666. return;
  667. }
  668. FIRAdditionalUserInfo *additionalUserInfo =
  669. [[FIRAdditionalUserInfo alloc]
  670. initWithProviderID:
  671. FIRGameCenterAuthProviderID
  672. profile:nil
  673. username:nil
  674. isNewUser:response.isNewUser];
  675. FIRAuthDataResult *result =
  676. user ? [[FIRAuthDataResult alloc]
  677. initWithUser:user
  678. additionalUserInfo:additionalUserInfo]
  679. : nil;
  680. if (callback) {
  681. callback(result, error);
  682. }
  683. }];
  684. }];
  685. }
  686. /** @fn internalSignInAndRetrieveDataWithEmail:link:completion:
  687. @brief Signs in using an email and email sign-in link.
  688. @param email The user's email address.
  689. @param link The email sign-in link.
  690. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  691. asynchronously on the global auth work queue in the future.
  692. */
  693. - (void)internalSignInAndRetrieveDataWithEmail:(nonnull NSString *)email
  694. link:(nonnull NSString *)link
  695. callback:(nullable FIRAuthDataResultCallback)callback {
  696. if (![self isSignInWithEmailLink:link]) {
  697. [FIRAuthExceptionUtils
  698. raiseInvalidParameterExceptionWithReason:kInvalidEmailSignInLinkExceptionMessage];
  699. return;
  700. }
  701. NSDictionary<NSString *, NSString *> *queryItems = [FIRAuthWebUtils parseURL:link];
  702. if (![queryItems count]) {
  703. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  704. queryItems = [FIRAuthWebUtils parseURL:urlComponents.query];
  705. }
  706. NSString *actionCode = queryItems[@"oobCode"];
  707. FIREmailLinkSignInRequest *request =
  708. [[FIREmailLinkSignInRequest alloc] initWithEmail:email
  709. oobCode:actionCode
  710. requestConfiguration:_requestConfiguration];
  711. [FIRAuthBackend
  712. emailLinkSignin:request
  713. callback:^(FIREmailLinkSignInResponse *_Nullable response, NSError *_Nullable error) {
  714. if (error) {
  715. if (callback) {
  716. callback(nil, error);
  717. }
  718. return;
  719. }
  720. [self completeSignInWithAccessToken:response.IDToken
  721. accessTokenExpirationDate:response.approximateExpirationDate
  722. refreshToken:response.refreshToken
  723. anonymous:NO
  724. callback:^(FIRUser *_Nullable user,
  725. NSError *_Nullable error) {
  726. if (error && callback) {
  727. callback(nil, error);
  728. return;
  729. }
  730. FIRAdditionalUserInfo *additionalUserInfo =
  731. [[FIRAdditionalUserInfo alloc]
  732. initWithProviderID:FIREmailAuthProviderID
  733. profile:nil
  734. username:nil
  735. isNewUser:response.isNewUser];
  736. FIRAuthDataResult *result =
  737. user ? [[FIRAuthDataResult alloc]
  738. initWithUser:user
  739. additionalUserInfo:additionalUserInfo]
  740. : nil;
  741. if (callback) {
  742. callback(result, error);
  743. }
  744. }];
  745. }];
  746. }
  747. - (void)signInWithCredential:(FIRAuthCredential *)credential
  748. completion:(nullable FIRAuthDataResultCallback)completion {
  749. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  750. FIRAuthDataResultCallback callback =
  751. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  752. [self internalSignInAndRetrieveDataWithCredential:credential
  753. isReauthentication:NO
  754. callback:callback];
  755. });
  756. }
  757. - (void)internalSignInWithCredential:(FIRAuthCredential *)credential
  758. callback:(FIRAuthResultCallback)callback {
  759. [self internalSignInAndRetrieveDataWithCredential:credential
  760. isReauthentication:NO
  761. callback:^(FIRAuthDataResult *_Nullable authResult,
  762. NSError *_Nullable error) {
  763. callback(authResult.user, error);
  764. }];
  765. }
  766. - (void)internalSignInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  767. isReauthentication:(BOOL)isReauthentication
  768. callback:(nullable FIRAuthDataResultCallback)callback {
  769. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  770. // Special case for email/password credentials
  771. FIREmailPasswordAuthCredential *emailPasswordCredential =
  772. (FIREmailPasswordAuthCredential *)credential;
  773. if (emailPasswordCredential.link) {
  774. // Email link sign in
  775. [self internalSignInAndRetrieveDataWithEmail:emailPasswordCredential.email
  776. link:emailPasswordCredential.link
  777. callback:callback];
  778. } else {
  779. // Email password sign in
  780. FIRAuthResultCallback completeEmailSignIn =
  781. ^(FIRUser *_Nullable user, NSError *_Nullable error) {
  782. if (callback) {
  783. if (error) {
  784. callback(nil, error);
  785. return;
  786. }
  787. FIRAdditionalUserInfo *additionalUserInfo =
  788. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  789. profile:nil
  790. username:nil
  791. isNewUser:NO];
  792. FIRAuthDataResult *result =
  793. user ? [[FIRAuthDataResult alloc] initWithUser:user
  794. additionalUserInfo:additionalUserInfo]
  795. : nil;
  796. callback(result, error);
  797. }
  798. };
  799. [self signInWithEmail:emailPasswordCredential.email
  800. password:emailPasswordCredential.password
  801. callback:completeEmailSignIn];
  802. }
  803. return;
  804. }
  805. if ([credential isKindOfClass:[FIRGameCenterAuthCredential class]]) {
  806. // Special case for Game Center credentials.
  807. [self signInAndRetrieveDataWithGameCenterCredential:(FIRGameCenterAuthCredential *)credential
  808. callback:callback];
  809. return;
  810. }
  811. #if TARGET_OS_IOS
  812. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  813. // Special case for phone auth credentials
  814. FIRPhoneAuthCredential *phoneCredential = (FIRPhoneAuthCredential *)credential;
  815. FIRAuthOperationType operation =
  816. isReauthentication ? FIRAuthOperationTypeReauth : FIRAuthOperationTypeSignUpOrSignIn;
  817. [self
  818. signInWithPhoneCredential:phoneCredential
  819. operation:operation
  820. callback:^(FIRVerifyPhoneNumberResponse *_Nullable response,
  821. NSError *_Nullable error) {
  822. if (callback) {
  823. if (error) {
  824. callback(nil, error);
  825. return;
  826. }
  827. [self
  828. completeSignInWithAccessToken:response.IDToken
  829. accessTokenExpirationDate:response.approximateExpirationDate
  830. refreshToken:response.refreshToken
  831. anonymous:NO
  832. callback:^(FIRUser *_Nullable user,
  833. NSError *_Nullable error) {
  834. if (error && callback) {
  835. callback(nil, error);
  836. return;
  837. }
  838. FIRAdditionalUserInfo *additionalUserInfo =
  839. [[FIRAdditionalUserInfo alloc]
  840. initWithProviderID:
  841. FIRPhoneAuthProviderID
  842. profile:nil
  843. username:nil
  844. isNewUser:response
  845. .isNewUser];
  846. FIRAuthDataResult *result =
  847. user ? [[FIRAuthDataResult alloc]
  848. initWithUser:user
  849. additionalUserInfo:
  850. additionalUserInfo]
  851. : nil;
  852. if (callback) {
  853. callback(result, error);
  854. }
  855. }];
  856. }
  857. }];
  858. return;
  859. }
  860. #endif
  861. FIRVerifyAssertionRequest *request =
  862. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  863. requestConfiguration:_requestConfiguration];
  864. request.autoCreate = !isReauthentication;
  865. [credential prepareVerifyAssertionRequest:request];
  866. [FIRAuthBackend
  867. verifyAssertion:request
  868. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  869. if (error) {
  870. if (callback) {
  871. callback(nil, error);
  872. }
  873. return;
  874. }
  875. if (response.needConfirmation) {
  876. if (callback) {
  877. NSString *email = response.email;
  878. FIROAuthCredential *credential =
  879. [[FIROAuthCredential alloc] initWithVerifyAssertionResponse:response];
  880. callback(nil,
  881. [FIRAuthErrorUtils
  882. accountExistsWithDifferentCredentialErrorWithEmail:email
  883. updatedCredential:credential]);
  884. }
  885. return;
  886. }
  887. if (!response.providerID.length) {
  888. if (callback) {
  889. callback(nil, [FIRAuthErrorUtils
  890. unexpectedResponseWithDeserializedResponse:response]);
  891. }
  892. return;
  893. }
  894. [self
  895. completeSignInWithAccessToken:response.IDToken
  896. accessTokenExpirationDate:response.approximateExpirationDate
  897. refreshToken:response.refreshToken
  898. anonymous:NO
  899. callback:^(FIRUser *_Nullable user,
  900. NSError *_Nullable error) {
  901. if (callback) {
  902. if (error) {
  903. callback(nil, error);
  904. return;
  905. }
  906. FIRAdditionalUserInfo *additionalUserInfo =
  907. [FIRAdditionalUserInfo
  908. userInfoWithVerifyAssertionResponse:response];
  909. FIROAuthCredential *updatedOAuthCredential =
  910. [[FIROAuthCredential alloc]
  911. initWithVerifyAssertionResponse:response];
  912. FIRAuthDataResult *result =
  913. user
  914. ? [[FIRAuthDataResult alloc]
  915. initWithUser:user
  916. additionalUserInfo:additionalUserInfo
  917. credential:updatedOAuthCredential]
  918. : nil;
  919. callback(result, error);
  920. }
  921. }];
  922. }];
  923. }
  924. - (void)signInAnonymouslyWithCompletion:(nullable FIRAuthDataResultCallback)completion {
  925. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  926. FIRAuthDataResultCallback decoratedCallback =
  927. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  928. if (self->_currentUser.anonymous) {
  929. FIRAuthDataResult *result = [[FIRAuthDataResult alloc] initWithUser:self->_currentUser
  930. additionalUserInfo:nil];
  931. decoratedCallback(result, nil);
  932. return;
  933. }
  934. [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response,
  935. NSError *_Nullable error) {
  936. if (error) {
  937. decoratedCallback(nil, error);
  938. return;
  939. }
  940. [self completeSignInWithAccessToken:response.IDToken
  941. accessTokenExpirationDate:response.approximateExpirationDate
  942. refreshToken:response.refreshToken
  943. anonymous:YES
  944. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  945. if (error) {
  946. decoratedCallback(nil, error);
  947. return;
  948. }
  949. FIRAdditionalUserInfo *additionalUserInfo =
  950. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  951. profile:nil
  952. username:nil
  953. isNewUser:YES];
  954. FIRAuthDataResult *authDataResult =
  955. user ? [[FIRAuthDataResult alloc]
  956. initWithUser:user
  957. additionalUserInfo:additionalUserInfo]
  958. : nil;
  959. decoratedCallback(authDataResult, error);
  960. }];
  961. }];
  962. });
  963. }
  964. - (void)signInWithCustomToken:(NSString *)token
  965. completion:(nullable FIRAuthDataResultCallback)completion {
  966. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  967. FIRAuthDataResultCallback decoratedCallback =
  968. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  969. [self internalSignInAndRetrieveDataWithCustomToken:token
  970. completion:^(FIRAuthDataResult *_Nullable authResult,
  971. NSError *_Nullable error) {
  972. decoratedCallback(authResult, error);
  973. }];
  974. });
  975. }
  976. - (void)createUserWithEmail:(NSString *)email
  977. password:(NSString *)password
  978. completion:(nullable FIRAuthDataResultCallback)completion {
  979. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  980. FIRAuthDataResultCallback decoratedCallback =
  981. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  982. [self internalCreateUserWithEmail:email
  983. password:password
  984. completion:^(FIRSignUpNewUserResponse *_Nullable response,
  985. NSError *_Nullable error) {
  986. if (error) {
  987. decoratedCallback(nil, error);
  988. return;
  989. }
  990. [self
  991. completeSignInWithAccessToken:response.IDToken
  992. accessTokenExpirationDate:response.approximateExpirationDate
  993. refreshToken:response.refreshToken
  994. anonymous:NO
  995. callback:^(FIRUser *_Nullable user,
  996. NSError *_Nullable error) {
  997. if (error) {
  998. decoratedCallback(nil, error);
  999. return;
  1000. }
  1001. FIRAdditionalUserInfo *additionalUserInfo =
  1002. [[FIRAdditionalUserInfo alloc]
  1003. initWithProviderID:
  1004. FIREmailAuthProviderID
  1005. profile:nil
  1006. username:nil
  1007. isNewUser:YES];
  1008. FIRAuthDataResult *authDataResult =
  1009. user ? [[FIRAuthDataResult alloc]
  1010. initWithUser:user
  1011. additionalUserInfo:
  1012. additionalUserInfo]
  1013. : nil;
  1014. decoratedCallback(authDataResult, error);
  1015. }];
  1016. }];
  1017. });
  1018. }
  1019. - (void)confirmPasswordResetWithCode:(NSString *)code
  1020. newPassword:(NSString *)newPassword
  1021. completion:(FIRConfirmPasswordResetCallback)completion {
  1022. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1023. FIRResetPasswordRequest *request =
  1024. [[FIRResetPasswordRequest alloc] initWithOobCode:code
  1025. newPassword:newPassword
  1026. requestConfiguration:self->_requestConfiguration];
  1027. [FIRAuthBackend
  1028. resetPassword:request
  1029. callback:^(FIRResetPasswordResponse *_Nullable response, NSError *_Nullable error) {
  1030. if (completion) {
  1031. dispatch_async(dispatch_get_main_queue(), ^{
  1032. if (error) {
  1033. completion(error);
  1034. return;
  1035. }
  1036. completion(nil);
  1037. });
  1038. }
  1039. }];
  1040. });
  1041. }
  1042. - (void)checkActionCode:(NSString *)code completion:(FIRCheckActionCodeCallBack)completion {
  1043. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1044. FIRResetPasswordRequest *request =
  1045. [[FIRResetPasswordRequest alloc] initWithOobCode:code
  1046. newPassword:nil
  1047. requestConfiguration:self->_requestConfiguration];
  1048. [FIRAuthBackend
  1049. resetPassword:request
  1050. callback:^(FIRResetPasswordResponse *_Nullable response, NSError *_Nullable error) {
  1051. if (completion) {
  1052. if (error) {
  1053. dispatch_async(dispatch_get_main_queue(), ^{
  1054. completion(nil, error);
  1055. });
  1056. return;
  1057. }
  1058. FIRActionCodeOperation operation =
  1059. [FIRActionCodeInfo actionCodeOperationForRequestType:response.requestType];
  1060. FIRActionCodeInfo *actionCodeInfo =
  1061. [[FIRActionCodeInfo alloc] initWithOperation:operation
  1062. email:response.email
  1063. newEmail:response.verifiedEmail];
  1064. dispatch_async(dispatch_get_main_queue(), ^{
  1065. completion(actionCodeInfo, nil);
  1066. });
  1067. }
  1068. }];
  1069. });
  1070. }
  1071. - (void)verifyPasswordResetCode:(NSString *)code
  1072. completion:(FIRVerifyPasswordResetCodeCallback)completion {
  1073. [self checkActionCode:code
  1074. completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
  1075. if (completion) {
  1076. if (error) {
  1077. completion(nil, error);
  1078. return;
  1079. }
  1080. completion(info.email, nil);
  1081. }
  1082. }];
  1083. }
  1084. - (void)applyActionCode:(NSString *)code completion:(FIRApplyActionCodeCallback)completion {
  1085. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1086. FIRSetAccountInfoRequest *request =
  1087. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:self->_requestConfiguration];
  1088. request.OOBCode = code;
  1089. [FIRAuthBackend
  1090. setAccountInfo:request
  1091. callback:^(FIRSetAccountInfoResponse *_Nullable response, NSError *_Nullable error) {
  1092. if (completion) {
  1093. dispatch_async(dispatch_get_main_queue(), ^{
  1094. completion(error);
  1095. });
  1096. }
  1097. }];
  1098. });
  1099. }
  1100. - (void)sendPasswordResetWithEmail:(NSString *)email
  1101. completion:(nullable FIRSendPasswordResetCallback)completion {
  1102. [self sendPasswordResetWithNullableActionCodeSettings:nil email:email completion:completion];
  1103. }
  1104. - (void)sendPasswordResetWithEmail:(NSString *)email
  1105. actionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1106. completion:(nullable FIRSendPasswordResetCallback)completion {
  1107. [self sendPasswordResetWithNullableActionCodeSettings:actionCodeSettings
  1108. email:email
  1109. completion:completion];
  1110. }
  1111. /** @fn sendPasswordResetWithNullableActionCodeSettings:actionCodeSetting:email:completion:
  1112. @brief Initiates a password reset for the given email address and @FIRActionCodeSettings object.
  1113. @param actionCodeSettings Optionally, An @c FIRActionCodeSettings object containing settings
  1114. related to the handling action codes.
  1115. @param email The email address of the user.
  1116. @param completion Optionally; a block which is invoked when the request finishes. Invoked
  1117. asynchronously on the main thread in the future.
  1118. */
  1119. - (void)sendPasswordResetWithNullableActionCodeSettings:
  1120. (nullable FIRActionCodeSettings *)actionCodeSettings
  1121. email:(NSString *)email
  1122. completion:
  1123. (nullable FIRSendPasswordResetCallback)completion {
  1124. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1125. if (!email) {
  1126. [FIRAuthExceptionUtils
  1127. raiseInvalidParameterExceptionWithReason:kMissingEmailInvalidParameterExceptionReason];
  1128. return;
  1129. }
  1130. FIRGetOOBConfirmationCodeRequest *request = [FIRGetOOBConfirmationCodeRequest
  1131. passwordResetRequestWithEmail:email
  1132. actionCodeSettings:actionCodeSettings
  1133. requestConfiguration:self->_requestConfiguration];
  1134. [FIRAuthBackend getOOBConfirmationCode:request
  1135. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1136. NSError *_Nullable error) {
  1137. if (completion) {
  1138. dispatch_async(dispatch_get_main_queue(), ^{
  1139. completion(error);
  1140. });
  1141. }
  1142. }];
  1143. });
  1144. }
  1145. - (void)sendSignInLinkToEmail:(nonnull NSString *)email
  1146. actionCodeSettings:(nonnull FIRActionCodeSettings *)actionCodeSettings
  1147. completion:(nullable FIRSendSignInLinkToEmailCallback)completion {
  1148. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1149. if (!email) {
  1150. [FIRAuthExceptionUtils
  1151. raiseInvalidParameterExceptionWithReason:kMissingEmailInvalidParameterExceptionReason];
  1152. }
  1153. if (!actionCodeSettings.handleCodeInApp) {
  1154. [FIRAuthExceptionUtils
  1155. raiseInvalidParameterExceptionWithReason:kHandleCodeInAppFalseExceptionReason];
  1156. }
  1157. FIRGetOOBConfirmationCodeRequest *request =
  1158. [FIRGetOOBConfirmationCodeRequest signInWithEmailLinkRequest:email
  1159. actionCodeSettings:actionCodeSettings
  1160. requestConfiguration:self->_requestConfiguration];
  1161. [FIRAuthBackend getOOBConfirmationCode:request
  1162. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1163. NSError *_Nullable error) {
  1164. if (completion) {
  1165. dispatch_async(dispatch_get_main_queue(), ^{
  1166. completion(error);
  1167. });
  1168. }
  1169. }];
  1170. });
  1171. }
  1172. - (void)updateCurrentUser:(FIRUser *)user completion:(nullable FIRUserUpdateCallback)completion {
  1173. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1174. if (!user) {
  1175. if (completion) {
  1176. dispatch_async(dispatch_get_main_queue(), ^{
  1177. completion([FIRAuthErrorUtils nullUserErrorWithMessage:nil]);
  1178. });
  1179. }
  1180. return;
  1181. }
  1182. void (^updateUserBlock)(FIRUser *user) = ^(FIRUser *user) {
  1183. NSError *error;
  1184. [self updateCurrentUser:user byForce:YES savingToDisk:YES error:(&error)];
  1185. if (error) {
  1186. if (completion) {
  1187. dispatch_async(dispatch_get_main_queue(), ^{
  1188. completion(error);
  1189. });
  1190. }
  1191. return;
  1192. }
  1193. if (completion) {
  1194. dispatch_async(dispatch_get_main_queue(), ^{
  1195. completion(nil);
  1196. });
  1197. }
  1198. };
  1199. if (![user.requestConfiguration.APIKey isEqualToString:self->_requestConfiguration.APIKey]) {
  1200. // If the API keys are different, then we need to confirm that the user belongs to the same
  1201. // project before proceeding.
  1202. user.requestConfiguration = self->_requestConfiguration;
  1203. [user reloadWithCompletion:^(NSError *_Nullable error) {
  1204. if (error) {
  1205. if (completion) {
  1206. dispatch_async(dispatch_get_main_queue(), ^{
  1207. completion(error);
  1208. });
  1209. }
  1210. return;
  1211. }
  1212. updateUserBlock(user);
  1213. }];
  1214. } else {
  1215. updateUserBlock(user);
  1216. }
  1217. });
  1218. }
  1219. - (BOOL)signOut:(NSError *_Nullable __autoreleasing *_Nullable)error {
  1220. __block BOOL result = YES;
  1221. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1222. if (!self->_currentUser) {
  1223. return;
  1224. }
  1225. result = [self updateCurrentUser:nil byForce:NO savingToDisk:YES error:error];
  1226. });
  1227. return result;
  1228. }
  1229. - (BOOL)signOutByForceWithUserID:(NSString *)userID error:(NSError *_Nullable *_Nullable)error {
  1230. if (_currentUser.uid != userID) {
  1231. return YES;
  1232. }
  1233. return [self updateCurrentUser:nil byForce:YES savingToDisk:YES error:error];
  1234. }
  1235. - (BOOL)isSignInWithEmailLink:(NSString *)link {
  1236. if (link.length == 0) {
  1237. return NO;
  1238. }
  1239. NSDictionary<NSString *, NSString *> *queryItems = [FIRAuthWebUtils parseURL:link];
  1240. if (![queryItems count]) {
  1241. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  1242. if (!urlComponents.query) {
  1243. return NO;
  1244. }
  1245. queryItems = [FIRAuthWebUtils parseURL:urlComponents.query];
  1246. }
  1247. if (![queryItems count]) {
  1248. return NO;
  1249. }
  1250. NSString *actionCode = queryItems[@"oobCode"];
  1251. NSString *mode = queryItems[@"mode"];
  1252. if (actionCode && [mode isEqualToString:@"signIn"]) {
  1253. return YES;
  1254. }
  1255. return NO;
  1256. }
  1257. - (FIRAuthStateDidChangeListenerHandle)addAuthStateDidChangeListener:
  1258. (FIRAuthStateDidChangeListenerBlock)listener {
  1259. __block BOOL firstInvocation = YES;
  1260. __block NSString *previousUserID;
  1261. return [self addIDTokenDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) {
  1262. BOOL shouldCallListener = firstInvocation || !(previousUserID == user.uid ||
  1263. [previousUserID isEqualToString:user.uid]);
  1264. firstInvocation = NO;
  1265. previousUserID = [user.uid copy];
  1266. if (shouldCallListener) {
  1267. listener(auth, user);
  1268. }
  1269. }];
  1270. }
  1271. - (void)removeAuthStateDidChangeListener:(FIRAuthStateDidChangeListenerHandle)listenerHandle {
  1272. [self removeIDTokenDidChangeListener:listenerHandle];
  1273. }
  1274. - (FIRIDTokenDidChangeListenerHandle)addIDTokenDidChangeListener:
  1275. (FIRIDTokenDidChangeListenerBlock)listener {
  1276. if (!listener) {
  1277. [NSException raise:NSInvalidArgumentException format:@"Listener must not be nil."];
  1278. return nil;
  1279. }
  1280. FIRAuthStateDidChangeListenerHandle handle;
  1281. NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter];
  1282. handle = [notifications addObserverForName:FIRAuthStateDidChangeNotification
  1283. object:self
  1284. queue:[NSOperationQueue mainQueue]
  1285. usingBlock:^(NSNotification *_Nonnull notification) {
  1286. FIRAuth *auth = notification.object;
  1287. listener(auth, auth.currentUser);
  1288. }];
  1289. @synchronized(self) {
  1290. [_listenerHandles addObject:handle];
  1291. }
  1292. dispatch_async(dispatch_get_main_queue(), ^{
  1293. listener(self, self->_currentUser);
  1294. });
  1295. return handle;
  1296. }
  1297. - (void)removeIDTokenDidChangeListener:(FIRIDTokenDidChangeListenerHandle)listenerHandle {
  1298. [[NSNotificationCenter defaultCenter] removeObserver:listenerHandle];
  1299. @synchronized(self) {
  1300. [_listenerHandles removeObject:listenerHandle];
  1301. }
  1302. }
  1303. - (void)useAppLanguage {
  1304. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1305. self->_requestConfiguration.languageCode = [[NSLocale preferredLanguages] firstObject];
  1306. });
  1307. }
  1308. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port {
  1309. NSAssert(host.length > 0, @"Cannot connect to nil or empty host");
  1310. NSString *formattedHost;
  1311. if ([host containsString:@":"]) {
  1312. // Host is an IPv6 address and should be formatted with surrounding brackets.
  1313. formattedHost = [NSString stringWithFormat:@"[%@]", host];
  1314. } else {
  1315. formattedHost = host;
  1316. }
  1317. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1318. self->_requestConfiguration.emulatorHostAndPort =
  1319. [NSString stringWithFormat:@"%@:%ld", formattedHost, (long)port];
  1320. #if TARGET_OS_IOS
  1321. self->_settings.appVerificationDisabledForTesting = YES;
  1322. #endif
  1323. });
  1324. }
  1325. - (nullable NSString *)languageCode {
  1326. return _requestConfiguration.languageCode;
  1327. }
  1328. - (void)setLanguageCode:(nullable NSString *)languageCode {
  1329. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1330. self->_requestConfiguration.languageCode = [languageCode copy];
  1331. });
  1332. }
  1333. - (nullable NSString *)additionalFrameworkMarker {
  1334. return self->_requestConfiguration.additionalFrameworkMarker;
  1335. }
  1336. - (void)setAdditionalFrameworkMarker:(nullable NSString *)additionalFrameworkMarker {
  1337. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1338. self->_requestConfiguration.additionalFrameworkMarker = [additionalFrameworkMarker copy];
  1339. });
  1340. }
  1341. #if TARGET_OS_IOS
  1342. #pragma clang diagnostic push
  1343. #pragma clang diagnostic ignored "-Wunused-property-ivar"
  1344. // The warning is ignored because we use the token manager to get the token, instead of using the
  1345. // ivar.
  1346. - (nullable NSData *)APNSToken {
  1347. __block NSData *result = nil;
  1348. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1349. result = self->_tokenManager.token.data;
  1350. });
  1351. return result;
  1352. }
  1353. #pragma clang diagnostic pop
  1354. #pragma mark - UIApplicationDelegate
  1355. - (void)application:(UIApplication *)application
  1356. didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  1357. [self setAPNSToken:deviceToken type:FIRAuthAPNSTokenTypeUnknown];
  1358. }
  1359. - (void)application:(UIApplication *)application
  1360. didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  1361. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1362. [self->_tokenManager cancelWithError:error];
  1363. });
  1364. }
  1365. - (void)application:(UIApplication *)application
  1366. didReceiveRemoteNotification:(NSDictionary *)userInfo
  1367. fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  1368. [self canHandleNotification:userInfo];
  1369. completionHandler(UIBackgroundFetchResultNoData);
  1370. }
  1371. // iOS 10 deprecation
  1372. #pragma clang diagnostic push
  1373. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  1374. - (void)application:(UIApplication *)application
  1375. didReceiveRemoteNotification:(NSDictionary *)userInfo {
  1376. [self canHandleNotification:userInfo];
  1377. }
  1378. #pragma clang diagnostic pop
  1379. - (BOOL)application:(UIApplication *)app
  1380. openURL:(NSURL *)url
  1381. options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
  1382. return [self canHandleURL:url];
  1383. }
  1384. // iOS 10 deprecation
  1385. #pragma clang diagnostic push
  1386. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  1387. - (BOOL)application:(UIApplication *)application
  1388. openURL:(NSURL *)url
  1389. sourceApplication:(nullable NSString *)sourceApplication
  1390. annotation:(id)annotation {
  1391. return [self canHandleURL:url];
  1392. }
  1393. #pragma clang diagnostic pop
  1394. - (void)setAPNSToken:(NSData *)token type:(FIRAuthAPNSTokenType)type {
  1395. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1396. self->_tokenManager.token = [[FIRAuthAPNSToken alloc] initWithData:token type:type];
  1397. });
  1398. }
  1399. - (BOOL)canHandleNotification:(NSDictionary *)userInfo {
  1400. __block BOOL result = NO;
  1401. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1402. result = [self->_notificationManager canHandleNotification:userInfo];
  1403. });
  1404. return result;
  1405. }
  1406. - (BOOL)canHandleURL:(NSURL *)URL {
  1407. __block BOOL result = NO;
  1408. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1409. result = [self->_authURLPresenter canHandleURL:URL];
  1410. });
  1411. return result;
  1412. }
  1413. #pragma mark - UISceneDelegate
  1414. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  1415. - (void)scene:(UIScene *)scene
  1416. openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts API_AVAILABLE(ios(13.0)) {
  1417. for (UIOpenURLContext *urlContext in URLContexts) {
  1418. NSURL *url = [urlContext URL];
  1419. [self canHandleURL:url];
  1420. }
  1421. }
  1422. #endif // __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  1423. #endif // TARGET_OS_IOS
  1424. #pragma mark - Internal Methods
  1425. #if TARGET_OS_IOS
  1426. /** @fn signInWithPhoneCredential:callback:
  1427. @brief Signs in using a phone credential.
  1428. @param credential The Phone Auth credential used to sign in.
  1429. @param operation The type of operation for which this sign-in attempt is initiated.
  1430. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  1431. asynchronously on the global auth work queue in the future.
  1432. */
  1433. - (void)signInWithPhoneCredential:(FIRPhoneAuthCredential *)credential
  1434. operation:(FIRAuthOperationType)operation
  1435. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  1436. if (credential.temporaryProof.length && credential.phoneNumber.length) {
  1437. FIRVerifyPhoneNumberRequest *request =
  1438. [[FIRVerifyPhoneNumberRequest alloc] initWithTemporaryProof:credential.temporaryProof
  1439. phoneNumber:credential.phoneNumber
  1440. operation:operation
  1441. requestConfiguration:_requestConfiguration];
  1442. [FIRAuthBackend verifyPhoneNumber:request callback:callback];
  1443. return;
  1444. }
  1445. if (!credential.verificationID.length) {
  1446. callback(nil, [FIRAuthErrorUtils missingVerificationIDErrorWithMessage:nil]);
  1447. return;
  1448. }
  1449. if (!credential.verificationCode.length) {
  1450. callback(nil, [FIRAuthErrorUtils missingVerificationCodeErrorWithMessage:nil]);
  1451. return;
  1452. }
  1453. FIRVerifyPhoneNumberRequest *request =
  1454. [[FIRVerifyPhoneNumberRequest alloc] initWithVerificationID:credential.verificationID
  1455. verificationCode:credential.verificationCode
  1456. operation:operation
  1457. requestConfiguration:_requestConfiguration];
  1458. [FIRAuthBackend verifyPhoneNumber:request callback:callback];
  1459. }
  1460. #endif
  1461. /** @fn internalSignInAndRetrieveDataWithCustomToken:completion:
  1462. @brief Signs in a Firebase user given a custom token.
  1463. @param token A self-signed custom auth token.
  1464. @param completion A block which is invoked when the custom token sign in request completes.
  1465. */
  1466. - (void)internalSignInAndRetrieveDataWithCustomToken:(NSString *)token
  1467. completion:
  1468. (nullable FIRAuthDataResultCallback)completion {
  1469. FIRVerifyCustomTokenRequest *request =
  1470. [[FIRVerifyCustomTokenRequest alloc] initWithToken:token
  1471. requestConfiguration:_requestConfiguration];
  1472. [FIRAuthBackend
  1473. verifyCustomToken:request
  1474. callback:^(FIRVerifyCustomTokenResponse *_Nullable response,
  1475. NSError *_Nullable error) {
  1476. if (error) {
  1477. if (completion) {
  1478. completion(nil, error);
  1479. return;
  1480. }
  1481. }
  1482. [self completeSignInWithAccessToken:response.IDToken
  1483. accessTokenExpirationDate:response.approximateExpirationDate
  1484. refreshToken:response.refreshToken
  1485. anonymous:NO
  1486. callback:^(FIRUser *_Nullable user,
  1487. NSError *_Nullable error) {
  1488. if (error && completion) {
  1489. completion(nil, error);
  1490. return;
  1491. }
  1492. FIRAdditionalUserInfo *additonalUserInfo =
  1493. [[FIRAdditionalUserInfo alloc]
  1494. initWithProviderID:nil
  1495. profile:nil
  1496. username:nil
  1497. isNewUser:response.isNewUser];
  1498. FIRAuthDataResult *result =
  1499. user ? [[FIRAuthDataResult alloc]
  1500. initWithUser:user
  1501. additionalUserInfo:additonalUserInfo]
  1502. : nil;
  1503. if (completion) {
  1504. completion(result, error);
  1505. }
  1506. }];
  1507. }];
  1508. }
  1509. /** @fn internalCreateUserWithEmail:password:completion:
  1510. @brief Makes a backend request attempting to create a new Firebase user given an email address
  1511. and password.
  1512. @param email The email address used to create the new Firebase user.
  1513. @param password The password used to create the new Firebase user.
  1514. @param completion Optionally; a block which is invoked when the request finishes.
  1515. */
  1516. - (void)internalCreateUserWithEmail:(NSString *)email
  1517. password:(NSString *)password
  1518. completion:(nullable FIRSignupNewUserCallback)completion {
  1519. FIRSignUpNewUserRequest *request =
  1520. [[FIRSignUpNewUserRequest alloc] initWithEmail:email
  1521. password:password
  1522. displayName:nil
  1523. requestConfiguration:_requestConfiguration];
  1524. if (![request.password length]) {
  1525. completion(
  1526. nil, [FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]);
  1527. return;
  1528. }
  1529. if (![request.email length]) {
  1530. completion(nil, [FIRAuthErrorUtils missingEmailErrorWithMessage:nil]);
  1531. return;
  1532. }
  1533. [FIRAuthBackend signUpNewUser:request callback:completion];
  1534. }
  1535. /** @fn internalSignInAnonymouslyWithCompletion:
  1536. @param completion A block which is invoked when the anonymous sign in request completes.
  1537. */
  1538. - (void)internalSignInAnonymouslyWithCompletion:(FIRSignupNewUserCallback)completion {
  1539. FIRSignUpNewUserRequest *request =
  1540. [[FIRSignUpNewUserRequest alloc] initWithRequestConfiguration:_requestConfiguration];
  1541. [FIRAuthBackend signUpNewUser:request callback:completion];
  1542. }
  1543. /** @fn possiblyPostAuthStateChangeNotification
  1544. @brief Posts the auth state change notificaton if current user's token has been changed.
  1545. */
  1546. - (void)possiblyPostAuthStateChangeNotification {
  1547. NSString *token = _currentUser.rawAccessToken;
  1548. if (_lastNotifiedUserToken == token ||
  1549. (token != nil && [_lastNotifiedUserToken isEqualToString:token])) {
  1550. return;
  1551. }
  1552. _lastNotifiedUserToken = token;
  1553. if (_autoRefreshTokens) {
  1554. // Shedule new refresh task after successful attempt.
  1555. [self scheduleAutoTokenRefresh];
  1556. }
  1557. NSMutableDictionary *internalNotificationParameters = [NSMutableDictionary dictionary];
  1558. if (self.app) {
  1559. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationAppKey] = self.app;
  1560. }
  1561. if (token.length) {
  1562. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationTokenKey] = token;
  1563. }
  1564. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationUIDKey] =
  1565. _currentUser.uid;
  1566. NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter];
  1567. dispatch_async(dispatch_get_main_queue(), ^{
  1568. [notifications postNotificationName:FIRAuthStateDidChangeInternalNotification
  1569. object:self
  1570. userInfo:internalNotificationParameters];
  1571. [notifications postNotificationName:FIRAuthStateDidChangeNotification object:self];
  1572. });
  1573. }
  1574. - (BOOL)updateKeychainWithUser:(FIRUser *)user error:(NSError *_Nullable *_Nullable)error {
  1575. if (user != _currentUser) {
  1576. // No-op if the user is no longer signed in. This is not considered an error as we don't check
  1577. // whether the user is still current on other callbacks of user operations either.
  1578. return YES;
  1579. }
  1580. if ([self saveUser:user error:error]) {
  1581. [self possiblyPostAuthStateChangeNotification];
  1582. return YES;
  1583. }
  1584. return NO;
  1585. }
  1586. /** @fn setKeychainServiceNameForApp
  1587. @brief Sets the keychain service name global data for the particular app.
  1588. @param app The Firebase app to set keychain service name for.
  1589. */
  1590. + (void)setKeychainServiceNameForApp:(FIRApp *)app {
  1591. @synchronized(self) {
  1592. gKeychainServiceNameForAppName[app.name] =
  1593. [@"firebase_auth_" stringByAppendingString:app.options.googleAppID];
  1594. }
  1595. }
  1596. /** @fn keychainServiceNameForAppName:
  1597. @brief Gets the keychain service name global data for the particular app by name.
  1598. @param appName The name of the Firebase app to get keychain service name for.
  1599. */
  1600. + (NSString *)keychainServiceNameForAppName:(NSString *)appName {
  1601. @synchronized(self) {
  1602. return gKeychainServiceNameForAppName[appName];
  1603. }
  1604. }
  1605. /** @fn deleteKeychainServiceNameForAppName:
  1606. @brief Deletes the keychain service name global data for the particular app by name.
  1607. @param appName The name of the Firebase app to delete keychain service name for.
  1608. */
  1609. + (void)deleteKeychainServiceNameForAppName:(NSString *)appName {
  1610. @synchronized(self) {
  1611. [gKeychainServiceNameForAppName removeObjectForKey:appName];
  1612. }
  1613. }
  1614. /** @fn scheduleAutoTokenRefreshWithDelay:
  1615. @brief Schedules a task to automatically refresh tokens on the current user. The token refresh
  1616. is scheduled 5 minutes before the scheduled expiration time.
  1617. @remarks If the token expires in less than 5 minutes, schedule the token refresh immediately.
  1618. */
  1619. - (void)scheduleAutoTokenRefresh {
  1620. NSTimeInterval tokenExpirationInterval =
  1621. [_currentUser.accessTokenExpirationDate timeIntervalSinceNow] - kTokenRefreshHeadStart;
  1622. [self scheduleAutoTokenRefreshWithDelay:MAX(tokenExpirationInterval, 0) retry:NO];
  1623. }
  1624. /** @fn scheduleAutoTokenRefreshWithDelay:
  1625. @brief Schedules a task to automatically refresh tokens on the current user.
  1626. @param delay The delay in seconds after which the token refresh task should be scheduled to be
  1627. executed.
  1628. @param retry Flag to determine whether the invocation is a retry attempt or not.
  1629. */
  1630. - (void)scheduleAutoTokenRefreshWithDelay:(NSTimeInterval)delay retry:(BOOL)retry {
  1631. NSString *accessToken = _currentUser.rawAccessToken;
  1632. if (!accessToken) {
  1633. return;
  1634. }
  1635. if (retry) {
  1636. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000003",
  1637. @"Token auto-refresh re-scheduled in %02d:%02d "
  1638. @"because of error on previous refresh attempt.",
  1639. (int)ceil(delay) / 60, (int)ceil(delay) % 60);
  1640. } else {
  1641. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000004",
  1642. @"Token auto-refresh scheduled in %02d:%02d for the new token.",
  1643. (int)ceil(delay) / 60, (int)ceil(delay) % 60);
  1644. }
  1645. _autoRefreshScheduled = YES;
  1646. __weak FIRAuth *weakSelf = self;
  1647. [[FIRAuthDispatcher sharedInstance]
  1648. dispatchAfterDelay:delay
  1649. queue:FIRAuthGlobalWorkQueue()
  1650. task:^(void) {
  1651. FIRAuth *strongSelf = weakSelf;
  1652. if (!strongSelf) {
  1653. return;
  1654. }
  1655. if (![strongSelf->_currentUser.rawAccessToken isEqualToString:accessToken]) {
  1656. // Another auto refresh must have been scheduled, so keep
  1657. // _autoRefreshScheduled unchanged.
  1658. return;
  1659. }
  1660. strongSelf->_autoRefreshScheduled = NO;
  1661. if (strongSelf->_isAppInBackground) {
  1662. return;
  1663. }
  1664. NSString *uid = strongSelf->_currentUser.uid;
  1665. [strongSelf->_currentUser
  1666. internalGetTokenForcingRefresh:YES
  1667. callback:^(NSString *_Nullable token,
  1668. NSError *_Nullable error) {
  1669. if (![strongSelf->_currentUser.uid
  1670. isEqualToString:uid]) {
  1671. return;
  1672. }
  1673. if (error) {
  1674. // Kicks off exponential back off logic to retry
  1675. // failed attempt. Starts with one minute delay
  1676. // (60 seconds) if this is the first failed
  1677. // attempt.
  1678. NSTimeInterval rescheduleDelay;
  1679. if (retry) {
  1680. rescheduleDelay =
  1681. MIN(delay * 2, kMaxWaitTimeForBackoff);
  1682. } else {
  1683. rescheduleDelay = 60;
  1684. }
  1685. [strongSelf
  1686. scheduleAutoTokenRefreshWithDelay:
  1687. rescheduleDelay
  1688. retry:YES];
  1689. }
  1690. }];
  1691. }];
  1692. }
  1693. #pragma mark -
  1694. /** @fn completeSignInWithTokenService:callback:
  1695. @brief Completes a sign-in flow once we have access and refresh tokens for the user.
  1696. @param accessToken The STS access token.
  1697. @param accessTokenExpirationDate The approximate expiration date of the access token.
  1698. @param refreshToken The STS refresh token.
  1699. @param anonymous Whether or not the user is anonymous.
  1700. @param callback Called when the user has been signed in or when an error occurred. Invoked
  1701. asynchronously on the global auth work queue in the future.
  1702. */
  1703. - (void)completeSignInWithAccessToken:(nullable NSString *)accessToken
  1704. accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate
  1705. refreshToken:(nullable NSString *)refreshToken
  1706. anonymous:(BOOL)anonymous
  1707. callback:(FIRAuthResultCallback)callback {
  1708. [FIRUser retrieveUserWithAuth:self
  1709. accessToken:accessToken
  1710. accessTokenExpirationDate:accessTokenExpirationDate
  1711. refreshToken:refreshToken
  1712. anonymous:anonymous
  1713. callback:callback];
  1714. }
  1715. /** @fn signInFlowAuthResultCallbackByDecoratingCallback:
  1716. @brief Creates a FIRAuthResultCallback block which wraps another FIRAuthResultCallback; trying
  1717. to update the current user before forwarding it's invocations along to a subject block
  1718. @param callback Called when the user has been updated or when an error has occurred. Invoked
  1719. asynchronously on the main thread in the future.
  1720. @return Returns a block that updates the current user.
  1721. @remarks Typically invoked as part of the complete sign-in flow. For any other uses please
  1722. consider alternative ways of updating the current user.
  1723. */
  1724. - (FIRAuthResultCallback)signInFlowAuthResultCallbackByDecoratingCallback:
  1725. (nullable FIRAuthResultCallback)callback {
  1726. return ^(FIRUser *_Nullable user, NSError *_Nullable error) {
  1727. if (error) {
  1728. if (callback) {
  1729. dispatch_async(dispatch_get_main_queue(), ^{
  1730. callback(nil, error);
  1731. });
  1732. }
  1733. return;
  1734. }
  1735. if (![self updateCurrentUser:user byForce:NO savingToDisk:YES error:&error]) {
  1736. if (callback) {
  1737. dispatch_async(dispatch_get_main_queue(), ^{
  1738. callback(nil, error);
  1739. });
  1740. }
  1741. return;
  1742. }
  1743. if (callback) {
  1744. dispatch_async(dispatch_get_main_queue(), ^{
  1745. callback(user, nil);
  1746. });
  1747. }
  1748. };
  1749. }
  1750. /** @fn signInFlowAuthDataResultCallbackByDecoratingCallback:
  1751. @brief Creates a FIRAuthDataResultCallback block which wraps another FIRAuthDataResultCallback;
  1752. trying to update the current user before forwarding it's invocations along to a subject
  1753. block.
  1754. @param callback Called when the user has been updated or when an error has occurred. Invoked
  1755. asynchronously on the main thread in the future.
  1756. @return Returns a block that updates the current user.
  1757. @remarks Typically invoked as part of the complete sign-in flow. For any other uses please
  1758. consider alternative ways of updating the current user.
  1759. */
  1760. - (FIRAuthDataResultCallback)signInFlowAuthDataResultCallbackByDecoratingCallback:
  1761. (nullable FIRAuthDataResultCallback)callback {
  1762. return ^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1763. if (error) {
  1764. if (callback) {
  1765. dispatch_async(dispatch_get_main_queue(), ^{
  1766. callback(nil, error);
  1767. });
  1768. }
  1769. return;
  1770. }
  1771. if (![self updateCurrentUser:authResult.user byForce:NO savingToDisk:YES error:&error]) {
  1772. if (callback) {
  1773. dispatch_async(dispatch_get_main_queue(), ^{
  1774. callback(nil, error);
  1775. });
  1776. }
  1777. return;
  1778. }
  1779. if (callback) {
  1780. dispatch_async(dispatch_get_main_queue(), ^{
  1781. callback(authResult, nil);
  1782. });
  1783. }
  1784. };
  1785. }
  1786. #pragma mark - User-Related Methods
  1787. /** @fn updateCurrentUser:byForce:savingToDisk:error:
  1788. @brief Update the current user; initializing the user's internal properties correctly, and
  1789. optionally saving the user to disk.
  1790. @remarks This method is called during: sign in and sign out events, as well as during class
  1791. initialization time. The only time the saveToDisk parameter should be set to NO is during
  1792. class initialization time because the user was just read from disk.
  1793. @param user The user to use as the current user (including nil, which is passed at sign out
  1794. time.)
  1795. @param saveToDisk Indicates the method should persist the user data to disk.
  1796. */
  1797. - (BOOL)updateCurrentUser:(nullable FIRUser *)user
  1798. byForce:(BOOL)force
  1799. savingToDisk:(BOOL)saveToDisk
  1800. error:(NSError *_Nullable *_Nullable)error {
  1801. if (user == _currentUser) {
  1802. [self possiblyPostAuthStateChangeNotification];
  1803. return YES;
  1804. }
  1805. if (user) {
  1806. if ((user.tenantID || self.tenantID) && ![self.tenantID isEqualToString:user.tenantID]) {
  1807. if (error) {
  1808. *error = [FIRAuthErrorUtils tenantIDMismatchError];
  1809. }
  1810. return NO;
  1811. }
  1812. }
  1813. BOOL success = YES;
  1814. if (saveToDisk) {
  1815. success = [self saveUser:user error:error];
  1816. }
  1817. if (success || force) {
  1818. _currentUser = user;
  1819. [self possiblyPostAuthStateChangeNotification];
  1820. }
  1821. return success;
  1822. }
  1823. /** @fn saveUser:error:
  1824. @brief Persists user.
  1825. @param user The user to save.
  1826. @param outError Return value for any error which occurs.
  1827. @return @YES on success, @NO otherwise.
  1828. */
  1829. - (BOOL)saveUser:(nullable FIRUser *)user error:(NSError *_Nullable *_Nullable)outError {
  1830. BOOL success;
  1831. if (!self.userAccessGroup) {
  1832. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  1833. if (!user) {
  1834. success = [_keychainServices removeDataForKey:userKey error:outError];
  1835. } else {
  1836. #if TARGET_OS_WATCH
  1837. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initRequiringSecureCoding:false];
  1838. #else
  1839. // Encode the user object.
  1840. NSMutableData *archiveData = [NSMutableData data];
  1841. // iOS 12 deprecation
  1842. #pragma clang diagnostic push
  1843. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1844. NSKeyedArchiver *archiver =
  1845. [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData];
  1846. #pragma clang diagnostic pop
  1847. #endif // TARGET_OS_WATCH
  1848. [archiver encodeObject:user forKey:userKey];
  1849. [archiver finishEncoding];
  1850. #if TARGET_OS_WATCH
  1851. NSData *archiveData = archiver.encodedData;
  1852. #endif // TARGET_OS_WATCH
  1853. // Save the user object's encoded value.
  1854. success = [_keychainServices setData:archiveData forKey:userKey error:outError];
  1855. }
  1856. } else {
  1857. if (!user) {
  1858. success =
  1859. [self.storedUserManager removeStoredUserForAccessGroup:self.userAccessGroup
  1860. shareAuthStateAcrossDevices:self.shareAuthStateAcrossDevices
  1861. projectIdentifier:self.app.options.APIKey
  1862. error:outError];
  1863. } else {
  1864. success = [self.storedUserManager setStoredUser:user
  1865. forAccessGroup:self.userAccessGroup
  1866. shareAuthStateAcrossDevices:self.shareAuthStateAcrossDevices
  1867. projectIdentifier:self.app.options.APIKey
  1868. error:outError];
  1869. }
  1870. }
  1871. return success;
  1872. }
  1873. /** @fn getUser:error:
  1874. @brief Retrieves the saved user associated, if one exists, from the keychain.
  1875. @param outUser An out parameter which is populated with the saved user, if one exists.
  1876. @param error Return value for any error which occurs.
  1877. @return YES if the operation was a success (irrespective of whether or not a saved user existed
  1878. for the given @c firebaseAppId,) NO if an error occurred.
  1879. */
  1880. - (BOOL)getUser:(FIRUser *_Nullable *)outUser error:(NSError *_Nullable *_Nullable)error {
  1881. if (!self.userAccessGroup) {
  1882. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  1883. NSError *keychainError;
  1884. NSData *encodedUserData = [_keychainServices dataForKey:userKey error:&keychainError];
  1885. if (keychainError) {
  1886. if (error) {
  1887. *error = keychainError;
  1888. }
  1889. return NO;
  1890. }
  1891. if (!encodedUserData) {
  1892. *outUser = nil;
  1893. return YES;
  1894. }
  1895. #if TARGET_OS_WATCH
  1896. NSKeyedUnarchiver *unarchiver =
  1897. [[NSKeyedUnarchiver alloc] initForReadingFromData:encodedUserData error:error];
  1898. if (error && *error) {
  1899. return NO;
  1900. }
  1901. #else
  1902. // iOS 12 deprecation
  1903. #pragma clang diagnostic push
  1904. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1905. NSKeyedUnarchiver *unarchiver =
  1906. [[NSKeyedUnarchiver alloc] initForReadingWithData:encodedUserData];
  1907. #pragma clang diagnostic pop
  1908. #endif // TARGET_OS_WATCH
  1909. FIRUser *user = [unarchiver decodeObjectOfClass:[FIRUser class] forKey:userKey];
  1910. user.auth = self;
  1911. *outUser = user;
  1912. return YES;
  1913. } else {
  1914. FIRUser *user =
  1915. [self.storedUserManager getStoredUserForAccessGroup:self.userAccessGroup
  1916. shareAuthStateAcrossDevices:self.shareAuthStateAcrossDevices
  1917. projectIdentifier:self.app.options.APIKey
  1918. error:error];
  1919. user.auth = self;
  1920. *outUser = user;
  1921. if (user) {
  1922. return YES;
  1923. } else {
  1924. if (error && *error) {
  1925. return NO;
  1926. } else {
  1927. return YES;
  1928. }
  1929. }
  1930. }
  1931. }
  1932. #pragma mark - Interoperability
  1933. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  1934. FIRComponentCreationBlock authCreationBlock =
  1935. ^id _Nullable(FIRComponentContainer *_Nonnull container, BOOL *_Nonnull isCacheable) {
  1936. *isCacheable = YES;
  1937. return [[FIRAuth alloc] initWithApp:container.app];
  1938. };
  1939. FIRComponent *authInterop = [FIRComponent componentWithProtocol:@protocol(FIRAuthInterop)
  1940. instantiationTiming:FIRInstantiationTimingAlwaysEager
  1941. dependencies:@[]
  1942. creationBlock:authCreationBlock];
  1943. return @[ authInterop ];
  1944. }
  1945. #pragma mark - FIRComponentLifecycleMaintainer
  1946. - (void)appWillBeDeleted:(nonnull FIRApp *)app {
  1947. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1948. // This doesn't stop any request already issued, see b/27704535 .
  1949. NSString *keychainServiceName = [FIRAuth keychainServiceNameForAppName:app.name];
  1950. if (keychainServiceName) {
  1951. [[self class] deleteKeychainServiceNameForAppName:app.name];
  1952. FIRAuthKeychainServices *keychain =
  1953. [[FIRAuthKeychainServices alloc] initWithService:keychainServiceName];
  1954. NSString *userKey = [NSString stringWithFormat:kUserKey, app.name];
  1955. [keychain removeDataForKey:userKey error:NULL];
  1956. }
  1957. dispatch_async(dispatch_get_main_queue(), ^{
  1958. // TODO: Move over to fire an event instead, once ready.
  1959. [[NSNotificationCenter defaultCenter] postNotificationName:FIRAuthStateDidChangeNotification
  1960. object:nil];
  1961. });
  1962. });
  1963. }
  1964. #pragma mark - FIRAuthInterop
  1965. - (void)getTokenForcingRefresh:(BOOL)forceRefresh withCallback:(FIRTokenCallback)callback {
  1966. __weak FIRAuth *weakSelf = self;
  1967. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1968. FIRAuth *strongSelf = weakSelf;
  1969. // Enable token auto-refresh if not aleady enabled.
  1970. if (strongSelf && !strongSelf->_autoRefreshTokens) {
  1971. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000002", @"Token auto-refresh enabled.");
  1972. strongSelf->_autoRefreshTokens = YES;
  1973. [strongSelf scheduleAutoTokenRefresh];
  1974. #if TARGET_OS_IOS || TARGET_OS_TV // TODO: Is a similar mechanism needed on macOS?
  1975. strongSelf->_applicationDidBecomeActiveObserver = [[NSNotificationCenter defaultCenter]
  1976. addObserverForName:UIApplicationDidBecomeActiveNotification
  1977. object:nil
  1978. queue:nil
  1979. usingBlock:^(NSNotification *notification) {
  1980. FIRAuth *strongSelf = weakSelf;
  1981. if (strongSelf) {
  1982. strongSelf->_isAppInBackground = NO;
  1983. if (!strongSelf->_autoRefreshScheduled) {
  1984. [weakSelf scheduleAutoTokenRefresh];
  1985. }
  1986. }
  1987. }];
  1988. strongSelf->_applicationDidEnterBackgroundObserver = [[NSNotificationCenter defaultCenter]
  1989. addObserverForName:UIApplicationDidEnterBackgroundNotification
  1990. object:nil
  1991. queue:nil
  1992. usingBlock:^(NSNotification *notification) {
  1993. FIRAuth *strongSelf = weakSelf;
  1994. if (strongSelf) {
  1995. strongSelf->_isAppInBackground = YES;
  1996. }
  1997. }];
  1998. #endif
  1999. }
  2000. // Call back with 'nil' if there is no current user.
  2001. if (!strongSelf || !strongSelf->_currentUser) {
  2002. dispatch_async(dispatch_get_main_queue(), ^{
  2003. callback(nil, nil);
  2004. });
  2005. return;
  2006. }
  2007. // Call back with current user token.
  2008. [strongSelf->_currentUser
  2009. internalGetTokenForcingRefresh:forceRefresh
  2010. callback:^(NSString *_Nullable token, NSError *_Nullable error) {
  2011. dispatch_async(dispatch_get_main_queue(), ^{
  2012. callback(token, error);
  2013. });
  2014. }];
  2015. });
  2016. }
  2017. - (nullable NSString *)getUserID {
  2018. return _currentUser.uid;
  2019. }
  2020. #pragma mark - Keychain sharing
  2021. - (BOOL)internalUseUserAccessGroup:(NSString *_Nullable)accessGroup
  2022. error:(NSError *_Nullable *_Nullable)outError {
  2023. BOOL success;
  2024. success = [self.storedUserManager setStoredUserAccessGroup:accessGroup error:outError];
  2025. if (!success) {
  2026. return NO;
  2027. }
  2028. FIRUser *user = [self getStoredUserForAccessGroup:accessGroup error:outError];
  2029. if (!user && outError && *outError) {
  2030. return NO;
  2031. }
  2032. success = [self updateCurrentUser:user byForce:NO savingToDisk:NO error:outError];
  2033. if (!success) {
  2034. return NO;
  2035. }
  2036. if (_userAccessGroup == nil && accessGroup != nil) {
  2037. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  2038. [_keychainServices removeDataForKey:userKey error:outError];
  2039. }
  2040. _userAccessGroup = accessGroup;
  2041. self->_lastNotifiedUserToken = user.rawAccessToken;
  2042. return YES;
  2043. }
  2044. - (BOOL)useUserAccessGroup:(NSString *_Nullable)accessGroup
  2045. error:(NSError *_Nullable *_Nullable)outError {
  2046. // self.storedUserManager is initialized asynchronously. Make sure it is done.
  2047. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  2048. });
  2049. return [self internalUseUserAccessGroup:accessGroup error:outError];
  2050. }
  2051. - (nullable FIRUser *)getStoredUserForAccessGroup:(NSString *_Nullable)accessGroup
  2052. error:(NSError *_Nullable *_Nullable)outError {
  2053. FIRUser *user;
  2054. if (!accessGroup) {
  2055. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  2056. NSData *encodedUserData = [_keychainServices dataForKey:userKey error:outError];
  2057. if (!encodedUserData) {
  2058. return nil;
  2059. }
  2060. #if TARGET_OS_WATCH
  2061. NSKeyedUnarchiver *unarchiver =
  2062. [[NSKeyedUnarchiver alloc] initForReadingFromData:encodedUserData error:outError];
  2063. if (outError && *outError) {
  2064. return nil;
  2065. }
  2066. #else
  2067. // iOS 12 deprecation
  2068. #pragma clang diagnostic push
  2069. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2070. NSKeyedUnarchiver *unarchiver =
  2071. [[NSKeyedUnarchiver alloc] initForReadingWithData:encodedUserData];
  2072. #pragma clang diagnostic pop
  2073. #endif // TARGET_OS_WATCH
  2074. user = [unarchiver decodeObjectOfClass:[FIRUser class] forKey:userKey];
  2075. } else {
  2076. user = [self.storedUserManager getStoredUserForAccessGroup:accessGroup
  2077. shareAuthStateAcrossDevices:self.shareAuthStateAcrossDevices
  2078. projectIdentifier:self.app.options.APIKey
  2079. error:outError];
  2080. }
  2081. user.auth = self;
  2082. return user;
  2083. }
  2084. @end
  2085. NS_ASSUME_NONNULL_END