FIRAuth.m 97 KB

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