FIRAuth.m 98 KB

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