FIRAuth.m 98 KB

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