FIRAuth.m 98 KB

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