FIRAuth.m 98 KB

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