FIRAuth.m 101 KB

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