FIRAuth.m 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  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 "FIRAuth_Internal.h"
  18. #import <FirebaseCore/FIRAppAssociationRegistration.h>
  19. #import <FirebaseCore/FIRAppEnvironmentUtil.h>
  20. #import <FirebaseCore/FIRAppInternal.h>
  21. #import <FirebaseCore/FIRLogger.h>
  22. #import <FirebaseCore/FIROptions.h>
  23. #import "AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h"
  24. #import "FIRAdditionalUserInfo_Internal.h"
  25. #import "FIRAuthCredential_Internal.h"
  26. #import "FIRAuthDataResult_Internal.h"
  27. #import "FIRAuthDispatcher.h"
  28. #import "FIRAuthErrorUtils.h"
  29. #import "FIRAuthExceptionUtils.h"
  30. #import "FIRAuthGlobalWorkQueue.h"
  31. #import "FIRAuthKeychain.h"
  32. #import "FIRAuthOperationType.h"
  33. #import "FIRAuthSettings.h"
  34. #import "FIRUser_Internal.h"
  35. #import "FirebaseAuth.h"
  36. #import "FIRAuthBackend.h"
  37. #import "FIRAuthRequestConfiguration.h"
  38. #import "FIRCreateAuthURIRequest.h"
  39. #import "FIRCreateAuthURIResponse.h"
  40. #import "FIREmailLinkSignInRequest.h"
  41. #import "FIREmailLinkSignInResponse.h"
  42. #import "FIRGetOOBConfirmationCodeRequest.h"
  43. #import "FIRGetOOBConfirmationCodeResponse.h"
  44. #import "FIRResetPasswordRequest.h"
  45. #import "FIRResetPasswordResponse.h"
  46. #import "FIRSendVerificationCodeRequest.h"
  47. #import "FIRSendVerificationCodeResponse.h"
  48. #import "FIRSetAccountInfoRequest.h"
  49. #import "FIRSetAccountInfoResponse.h"
  50. #import "FIRSignUpNewUserRequest.h"
  51. #import "FIRSignUpNewUserResponse.h"
  52. #import "FIRVerifyAssertionRequest.h"
  53. #import "FIRVerifyAssertionResponse.h"
  54. #import "FIRVerifyCustomTokenRequest.h"
  55. #import "FIRVerifyCustomTokenResponse.h"
  56. #import "FIRVerifyPasswordRequest.h"
  57. #import "FIRVerifyPasswordResponse.h"
  58. #import "FIRVerifyPhoneNumberRequest.h"
  59. #import "FIRVerifyPhoneNumberResponse.h"
  60. #if TARGET_OS_IOS
  61. #import <UIKit/UIKit.h>
  62. #import "FIRAuthAPNSToken.h"
  63. #import "FIRAuthAPNSTokenManager.h"
  64. #import "FIRAuthAppCredentialManager.h"
  65. #import "FIRAuthAppDelegateProxy.h"
  66. #import "AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h"
  67. #import "FIRAuthNotificationManager.h"
  68. #import "FIRAuthURLPresenter.h"
  69. #endif
  70. #pragma mark - Constants
  71. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  72. const NSNotificationName FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification";
  73. #else
  74. NSString *const FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification";
  75. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  76. /** @var kMaxWaitTimeForBackoff
  77. @brief The maximum wait time before attempting to retry auto refreshing tokens after a failed
  78. attempt.
  79. @remarks This is the upper limit (in seconds) of the exponential backoff used for retrying
  80. token refresh.
  81. */
  82. static NSTimeInterval kMaxWaitTimeForBackoff = 16 * 60;
  83. /** @var kTokenRefreshHeadStart
  84. @brief The amount of time before the token expires that proactive refresh should be attempted.
  85. */
  86. NSTimeInterval kTokenRefreshHeadStart = 5 * 60;
  87. /** @var kUserKey
  88. @brief Key of user stored in the keychain. Prefixed with a Firebase app name.
  89. */
  90. static NSString *const kUserKey = @"%@_firebase_user";
  91. /** @var kMissingEmailInvalidParameterExceptionReason
  92. @brief The reason for @c invalidParameterException when the email used to initiate password
  93. reset is nil.
  94. */
  95. static NSString *const kMissingEmailInvalidParameterExceptionReason =
  96. @"The email used to initiate password reset cannot be nil.";
  97. /** @var kHandleCodeInAppFalseExceptionReason
  98. @brief The reason for @c invalidParameterException when the handleCodeInApp parameter is false
  99. on the ActionCodeSettings object used to send the link for Email-link Authentication.
  100. */
  101. static NSString *const kHandleCodeInAppFalseExceptionReason =
  102. @"You must set handleCodeInApp in your ActionCodeSettings to true for Email-link "
  103. "Authentication.";
  104. static NSString *const kInvalidEmailSignInLinkExceptionMessage =
  105. @"The link provided is not valid for email/link sign-in. Please check the link by calling "
  106. "isSignInWithEmailLink:link: on Auth before attempting to use it for email/link sign-in.";
  107. /** @var kPasswordResetRequestType
  108. @brief The action code type value for resetting password in the check action code response.
  109. */
  110. static NSString *const kPasswordResetRequestType = @"PASSWORD_RESET";
  111. /** @var kVerifyEmailRequestType
  112. @brief The action code type value for verifying email in the check action code response.
  113. */
  114. static NSString *const kVerifyEmailRequestType = @"VERIFY_EMAIL";
  115. /** @var kRecoverEmailRequestType
  116. @brief The action code type value for recovering email in the check action code response.
  117. */
  118. static NSString *const kRecoverEmailRequestType = @"RECOVER_EMAIL";
  119. /** @var kEmailLinkSignInRequestType
  120. @brief The action code type value for an email sign-in link in the check action code response.
  121. */
  122. static NSString *const kEmailLinkSignInRequestType = @"EMAIL_SIGNIN";
  123. /** @var kMissingPasswordReason
  124. @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown.
  125. @remarks This error message will be localized in the future.
  126. */
  127. static NSString *const kMissingPasswordReason = @"Missing Password";
  128. /** @var gKeychainServiceNameForAppName
  129. @brief A map from Firebase app name to keychain service names.
  130. @remarks This map is needed for looking up the keychain service name after the FIRApp instance
  131. is deleted, to remove the associated keychain item. Accessing should occur within a
  132. @syncronized([FIRAuth class]) context.
  133. */
  134. static NSMutableDictionary *gKeychainServiceNameForAppName;
  135. #pragma mark - FIRActionCodeInfo
  136. @implementation FIRActionCodeInfo {
  137. /** @var _email
  138. @brief The email address to which the code was sent. The new email address in the case of
  139. FIRActionCodeOperationRecoverEmail.
  140. */
  141. NSString *_email;
  142. /** @var _fromEmail
  143. @brief The current email address in the case of FIRActionCodeOperationRecoverEmail.
  144. */
  145. NSString *_fromEmail;
  146. }
  147. - (NSString *)dataForKey:(FIRActionDataKey)key{
  148. switch (key) {
  149. case FIRActionCodeEmailKey:
  150. return _email;
  151. case FIRActionCodeFromEmailKey:
  152. return _fromEmail;
  153. }
  154. }
  155. - (instancetype)initWithOperation:(FIRActionCodeOperation)operation
  156. email:(NSString *)email
  157. newEmail:(nullable NSString *)newEmail {
  158. self = [super init];
  159. if (self) {
  160. _operation = operation;
  161. if (newEmail) {
  162. _email = [newEmail copy];
  163. _fromEmail = [email copy];
  164. } else {
  165. _email = [email copy];
  166. }
  167. }
  168. return self;
  169. }
  170. /** @fn actionCodeOperationForRequestType:
  171. @brief Returns the corresponding operation type per provided request type string.
  172. @param requestType Request type returned in in the server response.
  173. @return The corresponding FIRActionCodeOperation for the supplied request type.
  174. */
  175. + (FIRActionCodeOperation)actionCodeOperationForRequestType:(NSString *)requestType {
  176. if ([requestType isEqualToString:kPasswordResetRequestType]) {
  177. return FIRActionCodeOperationPasswordReset;
  178. }
  179. if ([requestType isEqualToString:kVerifyEmailRequestType]) {
  180. return FIRActionCodeOperationVerifyEmail;
  181. }
  182. if ([requestType isEqualToString:kRecoverEmailRequestType]) {
  183. return FIRActionCodeOperationRecoverEmail;
  184. }
  185. if ([requestType isEqualToString:kEmailLinkSignInRequestType]) {
  186. return FIRActionCodeOperationEmailLink;
  187. }
  188. return FIRActionCodeOperationUnknown;
  189. }
  190. @end
  191. #pragma mark - FIRAuth
  192. #if TARGET_OS_IOS
  193. @interface FIRAuth () <FIRAuthAppDelegateHandler>
  194. #else
  195. @interface FIRAuth ()
  196. #endif
  197. /** @property firebaseAppId
  198. @brief The Firebase app ID.
  199. */
  200. @property(nonatomic, copy, readonly) NSString *firebaseAppId;
  201. /** @property additionalFrameworkMarker
  202. @brief Additional framework marker that will be added as part of the header of every request.
  203. */
  204. @property(nonatomic, copy, nullable) NSString *additionalFrameworkMarker;
  205. /** @fn initWithApp:
  206. @brief Creates a @c FIRAuth instance associated with the provided @c FIRApp instance.
  207. @param app The application to associate the auth instance with.
  208. */
  209. - (instancetype)initWithApp:(FIRApp *)app;
  210. @end
  211. @implementation FIRAuth {
  212. /** @var _currentUser
  213. @brief The current user.
  214. */
  215. FIRUser *_currentUser;
  216. /** @var _firebaseAppName
  217. @brief The Firebase app name.
  218. */
  219. NSString *_firebaseAppName;
  220. /** @var _listenerHandles
  221. @brief Handles returned from @c NSNotificationCenter for blocks which are "auth state did
  222. change" notification listeners.
  223. @remarks Mutations should occur within a @syncronized(self) context.
  224. */
  225. NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_listenerHandles;
  226. /** @var _keychain
  227. @brief The keychain service.
  228. */
  229. FIRAuthKeychain *_keychain;
  230. /** @var _lastNotifiedUserToken
  231. @brief The user access (ID) token used last time for posting auth state changed notification.
  232. */
  233. NSString *_lastNotifiedUserToken;
  234. /** @var _autoRefreshTokens
  235. @brief This flag denotes whether or not tokens should be automatically refreshed.
  236. @remarks Will only be set to @YES if the another Firebase service is included (additionally to
  237. Firebase Auth).
  238. */
  239. BOOL _autoRefreshTokens;
  240. /** @var _autoRefreshScheduled
  241. @brief Whether or not token auto-refresh is currently scheduled.
  242. */
  243. BOOL _autoRefreshScheduled;
  244. /** @var _isAppInBackground
  245. @brief A flag that is set to YES if the app is put in the background and no when the app is
  246. returned to the foreground.
  247. */
  248. BOOL _isAppInBackground;
  249. /** @var _applicationDidBecomeActiveObserver
  250. @brief An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification.
  251. */
  252. id<NSObject> _applicationDidBecomeActiveObserver;
  253. /** @var _applicationDidBecomeActiveObserver
  254. @brief An opaque object to act as the observer for
  255. UIApplicationDidEnterBackgroundNotification.
  256. */
  257. id<NSObject> _applicationDidEnterBackgroundObserver;
  258. }
  259. + (void)load {
  260. static dispatch_once_t onceToken;
  261. dispatch_once(&onceToken, ^{
  262. gKeychainServiceNameForAppName = [[NSMutableDictionary alloc] init];
  263. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  264. // Ensures the @c FIRAuth instance for a given app gets loaded as soon as the app is ready.
  265. [defaultCenter addObserverForName:kFIRAppReadyToConfigureSDKNotification
  266. object:[FIRApp class]
  267. queue:nil
  268. usingBlock:^(NSNotification *notification) {
  269. [FIRAuth authWithApp:[FIRApp appNamed:notification.userInfo[kFIRAppNameKey]]];
  270. }];
  271. // Ensures the saved user is cleared when the app is deleted.
  272. [defaultCenter addObserverForName:kFIRAppDeleteNotification
  273. object:[FIRApp class]
  274. queue:nil
  275. usingBlock:^(NSNotification *notification) {
  276. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  277. // This doesn't stop any request already issued, see b/27704535 .
  278. NSString *appName = notification.userInfo[kFIRAppNameKey];
  279. NSString *keychainServiceName = [FIRAuth keychainServiceNameForAppName:appName];
  280. if (keychainServiceName) {
  281. [self deleteKeychainServiceNameForAppName:appName];
  282. FIRAuthKeychain *keychain = [[FIRAuthKeychain alloc] initWithService:keychainServiceName];
  283. NSString *userKey = [NSString stringWithFormat:kUserKey, appName];
  284. [keychain removeDataForKey:userKey error:NULL];
  285. }
  286. dispatch_async(dispatch_get_main_queue(), ^{
  287. [[NSNotificationCenter defaultCenter]
  288. postNotificationName:FIRAuthStateDidChangeNotification
  289. object:nil];
  290. });
  291. });
  292. }];
  293. });
  294. }
  295. + (FIRAuth *)auth {
  296. FIRApp *defaultApp = [FIRApp defaultApp];
  297. if (!defaultApp) {
  298. [NSException raise:NSInternalInconsistencyException
  299. format:@"The default FIRApp instance must be configured before the default FIRAuth"
  300. @"instance can be initialized. One way to ensure that is to call "
  301. @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App "
  302. @"Delegate's `application:didFinishLaunchingWithOptions:` "
  303. @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];
  304. }
  305. return [self authWithApp:defaultApp];
  306. }
  307. + (FIRAuth *)authWithApp:(FIRApp *)app {
  308. return [FIRAppAssociationRegistration registeredObjectWithHost:app
  309. key:NSStringFromClass(self)
  310. creationBlock:^FIRAuth *_Nullable() {
  311. return [[FIRAuth alloc] initWithApp:app];
  312. }];
  313. }
  314. - (instancetype)initWithApp:(FIRApp *)app {
  315. [FIRAuth setKeychainServiceNameForApp:app];
  316. self = [self initWithAPIKey:app.options.APIKey appName:app.name];
  317. if (self) {
  318. _app = app;
  319. __weak FIRAuth *weakSelf = self;
  320. app.getTokenImplementation = ^(BOOL forceRefresh, FIRTokenCallback callback) {
  321. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  322. FIRAuth *strongSelf = weakSelf;
  323. // Enable token auto-refresh if not aleady enabled.
  324. if (strongSelf && !strongSelf->_autoRefreshTokens) {
  325. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000002", @"Token auto-refresh enabled.");
  326. strongSelf->_autoRefreshTokens = YES;
  327. [strongSelf scheduleAutoTokenRefresh];
  328. #if TARGET_OS_IOS // TODO: Is a similar mechanism needed on macOS?
  329. strongSelf->_applicationDidBecomeActiveObserver = [[NSNotificationCenter defaultCenter]
  330. addObserverForName:UIApplicationDidBecomeActiveNotification
  331. object:nil
  332. queue:nil
  333. usingBlock:^(NSNotification *notification) {
  334. FIRAuth *strongSelf = weakSelf;
  335. if (strongSelf) {
  336. strongSelf->_isAppInBackground = NO;
  337. if (!strongSelf->_autoRefreshScheduled) {
  338. [weakSelf scheduleAutoTokenRefresh];
  339. }
  340. }
  341. }];
  342. strongSelf->_applicationDidEnterBackgroundObserver = [[NSNotificationCenter defaultCenter]
  343. addObserverForName:UIApplicationDidEnterBackgroundNotification
  344. object:nil
  345. queue:nil
  346. usingBlock:^(NSNotification *notification) {
  347. FIRAuth *strongSelf = weakSelf;
  348. if (strongSelf) {
  349. strongSelf->_isAppInBackground = YES;
  350. }
  351. }];
  352. #endif
  353. }
  354. // Call back with 'nil' if there is no current user.
  355. if (!strongSelf || !strongSelf->_currentUser) {
  356. dispatch_async(dispatch_get_main_queue(), ^{
  357. callback(nil, nil);
  358. });
  359. return;
  360. }
  361. // Call back with current user token.
  362. [strongSelf->_currentUser internalGetTokenForcingRefresh:forceRefresh
  363. callback:^(NSString *_Nullable token,
  364. NSError *_Nullable error) {
  365. dispatch_async(dispatch_get_main_queue(), ^{
  366. callback(token, error);
  367. });
  368. }];
  369. });
  370. };
  371. app.getUIDImplementation = ^NSString *_Nullable() {
  372. __block NSString *uid;
  373. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  374. uid = [weakSelf getUID];
  375. });
  376. return uid;
  377. };
  378. #if TARGET_OS_IOS
  379. _authURLPresenter = [[FIRAuthURLPresenter alloc] init];
  380. #endif
  381. }
  382. return self;
  383. }
  384. - (instancetype)initWithAPIKey:(NSString *)APIKey appName:(NSString *)appName {
  385. self = [super init];
  386. if (self) {
  387. _listenerHandles = [NSMutableArray array];
  388. _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey];
  389. _settings = [[FIRAuthSettings alloc] init];
  390. _firebaseAppName = [appName copy];
  391. #if TARGET_OS_IOS
  392. static Class applicationClass = nil;
  393. // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication
  394. // responds to it.
  395. if (![FIRAppEnvironmentUtil isAppExtension]) {
  396. Class cls = NSClassFromString(@"UIApplication");
  397. if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) {
  398. applicationClass = cls;
  399. }
  400. }
  401. UIApplication *application = [applicationClass sharedApplication];
  402. // Initialize the shared FIRAuthAppDelegateProxy instance in the main thread if not already.
  403. [FIRAuthAppDelegateProxy sharedInstance];
  404. #endif
  405. // Continue with the rest of initialization in the work thread.
  406. __weak FIRAuth *weakSelf = self;
  407. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  408. // Load current user from Keychain.
  409. FIRAuth *strongSelf = weakSelf;
  410. if (!strongSelf) {
  411. return;
  412. }
  413. NSString *keychainServiceName =
  414. [FIRAuth keychainServiceNameForAppName:strongSelf->_firebaseAppName];
  415. if (keychainServiceName) {
  416. strongSelf->_keychain = [[FIRAuthKeychain alloc] initWithService:keychainServiceName];
  417. }
  418. FIRUser *user;
  419. NSError *error;
  420. if ([strongSelf getUser:&user error:&error]) {
  421. [strongSelf updateCurrentUser:user byForce:NO savingToDisk:NO error:&error];
  422. self->_lastNotifiedUserToken = user.rawAccessToken;
  423. } else {
  424. FIRLogError(kFIRLoggerAuth, @"I-AUT000001",
  425. @"Error loading saved user when starting up: %@", error);
  426. }
  427. #if TARGET_OS_IOS
  428. // Initialize for phone number auth.
  429. strongSelf->_tokenManager =
  430. [[FIRAuthAPNSTokenManager alloc] initWithApplication:application];
  431. strongSelf->_appCredentialManager =
  432. [[FIRAuthAppCredentialManager alloc] initWithKeychain:strongSelf->_keychain];
  433. strongSelf->_notificationManager = [[FIRAuthNotificationManager alloc]
  434. initWithApplication:application
  435. appCredentialManager:strongSelf->_appCredentialManager];
  436. [[FIRAuthAppDelegateProxy sharedInstance] addHandler:strongSelf];
  437. #endif
  438. });
  439. }
  440. return self;
  441. }
  442. - (void)dealloc {
  443. @synchronized (self) {
  444. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  445. while (_listenerHandles.count != 0) {
  446. FIRAuthStateDidChangeListenerHandle handleToRemove = _listenerHandles.lastObject;
  447. [defaultCenter removeObserver:handleToRemove];
  448. [_listenerHandles removeLastObject];
  449. }
  450. #if TARGET_OS_IOS
  451. [defaultCenter removeObserver:_applicationDidBecomeActiveObserver
  452. name:UIApplicationDidBecomeActiveNotification
  453. object:nil];
  454. [defaultCenter removeObserver:_applicationDidEnterBackgroundObserver
  455. name:UIApplicationDidEnterBackgroundNotification
  456. object:nil];
  457. #endif
  458. }
  459. }
  460. #pragma mark - Public API
  461. - (FIRUser *)currentUser {
  462. __block FIRUser *result;
  463. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  464. result = self->_currentUser;
  465. });
  466. return result;
  467. }
  468. - (void)fetchProvidersForEmail:(NSString *)email
  469. completion:(FIRProviderQueryCallback)completion {
  470. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  471. FIRCreateAuthURIRequest *request =
  472. [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email
  473. continueURI:@"http://www.google.com/"
  474. requestConfiguration:self->_requestConfiguration];
  475. [FIRAuthBackend createAuthURI:request callback:^(FIRCreateAuthURIResponse *_Nullable response,
  476. NSError *_Nullable error) {
  477. if (completion) {
  478. dispatch_async(dispatch_get_main_queue(), ^{
  479. completion(response.allProviders, error);
  480. });
  481. }
  482. }];
  483. });
  484. }
  485. - (void)fetchSignInMethodsForEmail:(nonnull NSString *)email
  486. completion:(nullable FIRSignInMethodQueryCallback)completion {
  487. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  488. FIRCreateAuthURIRequest *request =
  489. [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email
  490. continueURI:@"http://www.google.com/"
  491. requestConfiguration:self->_requestConfiguration];
  492. [FIRAuthBackend createAuthURI:request callback:^(FIRCreateAuthURIResponse *_Nullable response,
  493. NSError *_Nullable error) {
  494. if (completion) {
  495. dispatch_async(dispatch_get_main_queue(), ^{
  496. completion(response.signinMethods, error);
  497. });
  498. }
  499. }];
  500. });
  501. }
  502. - (void)signInWithEmail:(NSString *)email
  503. password:(NSString *)password
  504. completion:(FIRAuthDataResultCallback)completion {
  505. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  506. FIRAuthDataResultCallback decoratedCallback =
  507. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  508. [self internalSignInAndRetrieveDataWithEmail:email
  509. password:password
  510. completion:^(FIRAuthDataResult *_Nullable authResult,
  511. NSError *_Nullable error) {
  512. decoratedCallback(authResult, error);
  513. }];
  514. });
  515. }
  516. - (void)signInWithEmail:(NSString *)email
  517. link:(NSString *)link
  518. completion:(FIRAuthDataResultCallback)completion {
  519. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  520. FIRAuthDataResultCallback decoratedCallback =
  521. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  522. FIREmailPasswordAuthCredential *credential =
  523. [[FIREmailPasswordAuthCredential alloc] initWithEmail:email link:link];
  524. [self internalSignInAndRetrieveDataWithCredential:credential
  525. isReauthentication:NO
  526. callback:^(FIRAuthDataResult *_Nullable authResult,
  527. NSError *_Nullable error) {
  528. decoratedCallback(authResult, error);
  529. }];
  530. });
  531. }
  532. /** @fn signInWithEmail:password:callback:
  533. @brief Signs in using an email address and password.
  534. @param email The user's email address.
  535. @param password The user's password.
  536. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  537. asynchronously on the global auth work queue in the future.
  538. @remarks This is the internal counterpart of this method, which uses a callback that does not
  539. update the current user.
  540. */
  541. - (void)signInWithEmail:(NSString *)email
  542. password:(NSString *)password
  543. callback:(FIRAuthResultCallback)callback {
  544. FIRVerifyPasswordRequest *request =
  545. [[FIRVerifyPasswordRequest alloc] initWithEmail:email
  546. password:password
  547. requestConfiguration:_requestConfiguration];
  548. if (![request.password length]) {
  549. callback(nil, [FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  550. return;
  551. }
  552. [FIRAuthBackend verifyPassword:request
  553. callback:^(FIRVerifyPasswordResponse *_Nullable response,
  554. NSError *_Nullable error) {
  555. if (error) {
  556. callback(nil, error);
  557. return;
  558. }
  559. [self completeSignInWithAccessToken:response.IDToken
  560. accessTokenExpirationDate:response.approximateExpirationDate
  561. refreshToken:response.refreshToken
  562. anonymous:NO
  563. callback:callback];
  564. }];
  565. }
  566. - (void)signInAndRetrieveDataWithEmail:(NSString *)email
  567. password:(NSString *)password
  568. completion:(FIRAuthDataResultCallback)completion {
  569. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  570. FIRAuthDataResultCallback decoratedCallback =
  571. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  572. [self internalSignInAndRetrieveDataWithEmail:email
  573. password:password
  574. completion:decoratedCallback];
  575. });
  576. }
  577. /** @fn internalSignInAndRetrieveDataWithEmail:password:callback:
  578. @brief Signs in using an email address and password.
  579. @param email The user's email address.
  580. @param password The user's password.
  581. @param completion A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  582. asynchronously on the global auth work queue in the future.
  583. @remarks This is the internal counterpart of this method, which uses a callback that does not
  584. update the current user.
  585. */
  586. - (void)internalSignInAndRetrieveDataWithEmail:(NSString *)email
  587. password:(NSString *)password
  588. completion:(FIRAuthDataResultCallback)completion {
  589. FIREmailPasswordAuthCredential *credentail =
  590. [[FIREmailPasswordAuthCredential alloc] initWithEmail:email password:password];
  591. [self internalSignInAndRetrieveDataWithCredential:credentail
  592. isReauthentication:NO
  593. callback:completion];
  594. }
  595. /** @fn internalSignInWithEmail:link:completion:
  596. @brief Signs in using an email and email sign-in link.
  597. @param email The user's email address.
  598. @param link The email sign-in link.
  599. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  600. asynchronously on the global auth work queue in the future.
  601. */
  602. - (void)internalSignInWithEmail:(nonnull NSString *)email
  603. link:(nonnull NSString *)link
  604. callback:(nullable FIRAuthResultCallback)callback {
  605. if (![self isSignInWithEmailLink:link]) {
  606. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  607. kInvalidEmailSignInLinkExceptionMessage];
  608. return;
  609. }
  610. NSDictionary<NSString *, NSString *> *queryItems = FIRAuthParseURL(link);
  611. if (![queryItems count]) {
  612. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  613. queryItems = FIRAuthParseURL(urlComponents.query);
  614. }
  615. NSString *actionCode = queryItems[@"oobCode"];
  616. FIREmailLinkSignInRequest *request =
  617. [[FIREmailLinkSignInRequest alloc] initWithEmail:email
  618. oobCode:actionCode
  619. requestConfiguration:_requestConfiguration];
  620. [FIRAuthBackend emailLinkSignin:request
  621. callback:^(FIREmailLinkSignInResponse *_Nullable response,
  622. NSError *_Nullable error) {
  623. if (error) {
  624. callback(nil, error);
  625. return;
  626. }
  627. [self completeSignInWithAccessToken:response.IDToken
  628. accessTokenExpirationDate:response.approximateExpirationDate
  629. refreshToken:response.refreshToken
  630. anonymous:NO
  631. callback:callback];
  632. }];
  633. }
  634. - (void)signInWithCredential:(FIRAuthCredential *)credential
  635. completion:(FIRAuthResultCallback)completion {
  636. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  637. FIRAuthResultCallback callback =
  638. [self signInFlowAuthResultCallbackByDecoratingCallback:completion];
  639. [self internalSignInWithCredential:credential callback:callback];
  640. });
  641. }
  642. - (void)signInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  643. completion:(nullable FIRAuthDataResultCallback)completion {
  644. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  645. FIRAuthDataResultCallback callback =
  646. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  647. [self internalSignInAndRetrieveDataWithCredential:credential
  648. isReauthentication:NO
  649. callback:callback];
  650. });
  651. }
  652. - (void)internalSignInWithCredential:(FIRAuthCredential *)credential
  653. callback:(FIRAuthResultCallback)callback {
  654. [self internalSignInAndRetrieveDataWithCredential:credential
  655. isReauthentication:NO
  656. callback:^(FIRAuthDataResult *_Nullable authResult,
  657. NSError *_Nullable error) {
  658. callback(authResult.user, error);
  659. }];
  660. }
  661. - (void)internalSignInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  662. isReauthentication:(BOOL)isReauthentication
  663. callback:(nullable FIRAuthDataResultCallback)callback {
  664. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  665. // Special case for email/password credentials
  666. FIREmailPasswordAuthCredential *emailPasswordCredential =
  667. (FIREmailPasswordAuthCredential *)credential;
  668. FIRAuthResultCallback completeEmailSignIn = ^(FIRUser *user, NSError *error) {
  669. if (callback) {
  670. if (error) {
  671. callback(nil, error);
  672. return;
  673. }
  674. FIRAdditionalUserInfo *additionalUserInfo =
  675. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  676. profile:nil
  677. username:nil
  678. isNewUser:NO];
  679. FIRAuthDataResult *result = [[FIRAuthDataResult alloc] initWithUser:user
  680. additionalUserInfo:additionalUserInfo];
  681. callback(result, error);
  682. }
  683. };
  684. if (emailPasswordCredential.link) {
  685. [self internalSignInWithEmail:emailPasswordCredential.email
  686. link:emailPasswordCredential.link
  687. callback:completeEmailSignIn];
  688. } else {
  689. [self signInWithEmail:emailPasswordCredential.email
  690. password:emailPasswordCredential.password
  691. callback:completeEmailSignIn];
  692. }
  693. return;
  694. }
  695. #if TARGET_OS_IOS
  696. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  697. // Special case for phone auth credentials
  698. FIRPhoneAuthCredential *phoneCredential = (FIRPhoneAuthCredential *)credential;
  699. FIRAuthOperationType operation =
  700. isReauthentication ? FIRAuthOperationTypeReauth : FIRAuthOperationTypeSignUpOrSignIn;
  701. [self signInWithPhoneCredential:phoneCredential
  702. operation:operation
  703. callback:^(FIRVerifyPhoneNumberResponse *_Nullable response,
  704. NSError *_Nullable error) {
  705. if (callback) {
  706. if (error) {
  707. callback(nil, error);
  708. return;
  709. }
  710. [self completeSignInWithAccessToken:response.IDToken
  711. accessTokenExpirationDate:response.approximateExpirationDate
  712. refreshToken:response.refreshToken
  713. anonymous:NO
  714. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  715. FIRAdditionalUserInfo *additionalUserInfo =
  716. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIRPhoneAuthProviderID
  717. profile:nil
  718. username:nil
  719. isNewUser:response.isNewUser];
  720. FIRAuthDataResult *result = user ?
  721. [[FIRAuthDataResult alloc] initWithUser:user
  722. additionalUserInfo:additionalUserInfo] : nil;
  723. callback(result, error);
  724. }];
  725. }
  726. }];
  727. return;
  728. }
  729. #endif
  730. FIRVerifyAssertionRequest *request =
  731. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  732. requestConfiguration:_requestConfiguration];
  733. request.autoCreate = !isReauthentication;
  734. [credential prepareVerifyAssertionRequest:request];
  735. [FIRAuthBackend verifyAssertion:request
  736. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  737. if (error) {
  738. if (callback) {
  739. callback(nil, error);
  740. }
  741. return;
  742. }
  743. if (response.needConfirmation) {
  744. if (callback) {
  745. NSString *email = response.email;
  746. callback(nil, [FIRAuthErrorUtils accountExistsWithDifferentCredentialErrorWithEmail:email]);
  747. }
  748. return;
  749. }
  750. if (!response.providerID.length) {
  751. if (callback) {
  752. callback(nil, [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:response]);
  753. }
  754. return;
  755. }
  756. [self completeSignInWithAccessToken:response.IDToken
  757. accessTokenExpirationDate:response.approximateExpirationDate
  758. refreshToken:response.refreshToken
  759. anonymous:NO
  760. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  761. if (callback) {
  762. FIRAdditionalUserInfo *additionalUserInfo =
  763. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  764. FIRAuthDataResult *result = user ?
  765. [[FIRAuthDataResult alloc] initWithUser:user
  766. additionalUserInfo:additionalUserInfo] : nil;
  767. callback(result, error);
  768. }
  769. }];
  770. }];
  771. }
  772. - (void)signInWithCredential:(FIRAuthCredential *)credential
  773. callback:(FIRAuthResultCallback)callback {
  774. [self signInAndRetrieveDataWithCredential:credential
  775. completion:^(FIRAuthDataResult *_Nullable authResult,
  776. NSError *_Nullable error) {
  777. callback(authResult.user, error);
  778. }];
  779. }
  780. - (void)signInAnonymouslyAndRetrieveDataWithCompletion:(FIRAuthDataResultCallback)completion {
  781. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  782. FIRAuthDataResultCallback decoratedCallback =
  783. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  784. if (self->_currentUser.anonymous) {
  785. FIRAdditionalUserInfo *additionalUserInfo =
  786. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  787. profile:nil
  788. username:nil
  789. isNewUser:NO];
  790. FIRAuthDataResult *authDataResult =
  791. [[FIRAuthDataResult alloc] initWithUser:self->_currentUser
  792. additionalUserInfo:additionalUserInfo];
  793. decoratedCallback(authDataResult, nil);
  794. return;
  795. }
  796. [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response,
  797. NSError *_Nullable error) {
  798. if (error) {
  799. decoratedCallback(nil, error);
  800. return;
  801. }
  802. [self completeSignInWithAccessToken:response.IDToken
  803. accessTokenExpirationDate:response.approximateExpirationDate
  804. refreshToken:response.refreshToken
  805. anonymous:YES
  806. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  807. FIRAdditionalUserInfo *additionalUserInfo =
  808. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  809. profile:nil
  810. username:nil
  811. isNewUser:YES];
  812. FIRAuthDataResult *authDataResult =
  813. [[FIRAuthDataResult alloc] initWithUser:user
  814. additionalUserInfo:additionalUserInfo];
  815. decoratedCallback(authDataResult, nil);
  816. }];
  817. }];
  818. });
  819. }
  820. - (void)signInAnonymouslyWithCompletion:(FIRAuthDataResultCallback)completion {
  821. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  822. FIRAuthDataResultCallback decoratedCallback =
  823. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  824. if (self->_currentUser.anonymous) {
  825. FIRAuthDataResult *result =
  826. [[FIRAuthDataResult alloc] initWithUser:self->_currentUser additionalUserInfo:nil];
  827. decoratedCallback(result, nil);
  828. return;
  829. }
  830. [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response,
  831. NSError *_Nullable error) {
  832. if (error) {
  833. decoratedCallback(nil, error);
  834. return;
  835. }
  836. [self completeSignInWithAccessToken:response.IDToken
  837. accessTokenExpirationDate:response.approximateExpirationDate
  838. refreshToken:response.refreshToken
  839. anonymous:YES
  840. callback:^(FIRUser * _Nullable user, NSError * _Nullable error) {
  841. FIRAdditionalUserInfo *additionalUserInfo =
  842. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  843. profile:nil
  844. username:nil
  845. isNewUser:YES];
  846. FIRAuthDataResult *authDataResult =
  847. [[FIRAuthDataResult alloc] initWithUser:user
  848. additionalUserInfo:additionalUserInfo];
  849. decoratedCallback(authDataResult, nil);
  850. }];
  851. }];
  852. });
  853. }
  854. - (void)signInWithCustomToken:(NSString *)token
  855. completion:(nullable FIRAuthDataResultCallback)completion {
  856. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  857. FIRAuthDataResultCallback decoratedCallback =
  858. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  859. [self internalSignInAndRetrieveDataWithCustomToken:token
  860. completion:^(FIRAuthDataResult *_Nullable authResult,
  861. NSError *_Nullable error) {
  862. decoratedCallback(authResult, error);
  863. }];
  864. });
  865. }
  866. - (void)signInAndRetrieveDataWithCustomToken:(NSString *)token
  867. completion:(nullable FIRAuthDataResultCallback)completion {
  868. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  869. FIRAuthDataResultCallback decoratedCallback =
  870. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  871. [self internalSignInAndRetrieveDataWithCustomToken:token completion:decoratedCallback];
  872. });
  873. }
  874. - (void)createUserWithEmail:(NSString *)email
  875. password:(NSString *)password
  876. completion:(nullable FIRAuthDataResultCallback)completion {
  877. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  878. FIRAuthDataResultCallback decoratedCallback =
  879. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  880. [self internalCreateUserWithEmail:email
  881. password:password
  882. completion:^(FIRSignUpNewUserResponse *_Nullable response,
  883. NSError *_Nullable error) {
  884. if (error) {
  885. decoratedCallback(nil, error);
  886. return;
  887. }
  888. [self completeSignInWithAccessToken:response.IDToken
  889. accessTokenExpirationDate:response.approximateExpirationDate
  890. refreshToken:response.refreshToken
  891. anonymous:NO
  892. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  893. FIRAdditionalUserInfo *additionalUserInfo =
  894. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  895. profile:nil
  896. username:nil
  897. isNewUser:YES];
  898. FIRAuthDataResult *authDataResult =
  899. [[FIRAuthDataResult alloc] initWithUser:user
  900. additionalUserInfo:additionalUserInfo];
  901. decoratedCallback(authDataResult, nil);
  902. }];
  903. }];
  904. });
  905. }
  906. - (void)createUserAndRetrieveDataWithEmail:(NSString *)email
  907. password:(NSString *)password
  908. completion:(FIRAuthDataResultCallback)completion {
  909. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  910. FIRAuthDataResultCallback decoratedCallback =
  911. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  912. [self internalCreateUserWithEmail:email
  913. password:password
  914. completion:^(FIRSignUpNewUserResponse *_Nullable response,
  915. NSError *_Nullable error) {
  916. if (error) {
  917. decoratedCallback(nil, error);
  918. return;
  919. }
  920. [self completeSignInWithAccessToken:response.IDToken
  921. accessTokenExpirationDate:response.approximateExpirationDate
  922. refreshToken:response.refreshToken
  923. anonymous:NO
  924. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  925. FIRAdditionalUserInfo *additionalUserInfo =
  926. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  927. profile:nil
  928. username:nil
  929. isNewUser:YES];
  930. FIRAuthDataResult *authDataResult =
  931. [[FIRAuthDataResult alloc] initWithUser:user
  932. additionalUserInfo:additionalUserInfo];
  933. decoratedCallback(authDataResult, nil);
  934. }];
  935. }];
  936. });
  937. }
  938. - (void)confirmPasswordResetWithCode:(NSString *)code
  939. newPassword:(NSString *)newPassword
  940. completion:(FIRConfirmPasswordResetCallback)completion {
  941. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  942. FIRResetPasswordRequest *request =
  943. [[FIRResetPasswordRequest alloc] initWithOobCode:code
  944. newPassword:newPassword
  945. requestConfiguration:self->_requestConfiguration];
  946. [FIRAuthBackend resetPassword:request callback:^(FIRResetPasswordResponse *_Nullable response,
  947. NSError *_Nullable error) {
  948. if (completion) {
  949. dispatch_async(dispatch_get_main_queue(), ^{
  950. if (error) {
  951. completion(error);
  952. return;
  953. }
  954. completion(nil);
  955. });
  956. }
  957. }];
  958. });
  959. }
  960. - (void)checkActionCode:(NSString *)code completion:(FIRCheckActionCodeCallBack)completion {
  961. dispatch_async(FIRAuthGlobalWorkQueue(), ^ {
  962. FIRResetPasswordRequest *request =
  963. [[FIRResetPasswordRequest alloc] initWithOobCode:code
  964. newPassword:nil
  965. requestConfiguration:self->_requestConfiguration];
  966. [FIRAuthBackend resetPassword:request callback:^(FIRResetPasswordResponse *_Nullable response,
  967. NSError *_Nullable error) {
  968. if (completion) {
  969. if (error) {
  970. dispatch_async(dispatch_get_main_queue(), ^{
  971. completion(nil, error);
  972. });
  973. return;
  974. }
  975. FIRActionCodeOperation operation =
  976. [FIRActionCodeInfo actionCodeOperationForRequestType:response.requestType];
  977. FIRActionCodeInfo *actionCodeInfo =
  978. [[FIRActionCodeInfo alloc] initWithOperation:operation
  979. email:response.email
  980. newEmail:response.verifiedEmail];
  981. dispatch_async(dispatch_get_main_queue(), ^{
  982. completion(actionCodeInfo, nil);
  983. });
  984. }
  985. }];
  986. });
  987. }
  988. - (void)verifyPasswordResetCode:(NSString *)code
  989. completion:(FIRVerifyPasswordResetCodeCallback)completion {
  990. [self checkActionCode:code completion:^(FIRActionCodeInfo *_Nullable info,
  991. NSError *_Nullable error) {
  992. if (completion) {
  993. if (error) {
  994. completion(nil, error);
  995. return;
  996. }
  997. completion([info dataForKey:FIRActionCodeEmailKey], nil);
  998. }
  999. }];
  1000. }
  1001. - (void)applyActionCode:(NSString *)code completion:(FIRApplyActionCodeCallback)completion {
  1002. dispatch_async(FIRAuthGlobalWorkQueue(), ^ {
  1003. FIRSetAccountInfoRequest *request =
  1004. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:self->_requestConfiguration];
  1005. request.OOBCode = code;
  1006. [FIRAuthBackend setAccountInfo:request callback:^(FIRSetAccountInfoResponse *_Nullable response,
  1007. NSError *_Nullable error) {
  1008. if (completion) {
  1009. dispatch_async(dispatch_get_main_queue(), ^{
  1010. completion(error);
  1011. });
  1012. }
  1013. }];
  1014. });
  1015. }
  1016. - (void)sendPasswordResetWithEmail:(NSString *)email
  1017. completion:(nullable FIRSendPasswordResetCallback)completion {
  1018. [self sendPasswordResetWithNullableActionCodeSettings:nil email:email completion:completion];
  1019. }
  1020. - (void)sendPasswordResetWithEmail:(NSString *)email
  1021. actionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1022. completion:(nullable FIRSendPasswordResetCallback)completion {
  1023. [self sendPasswordResetWithNullableActionCodeSettings:actionCodeSettings
  1024. email:email
  1025. completion:completion];
  1026. }
  1027. /** @fn sendPasswordResetWithNullableActionCodeSettings:actionCodeSetting:email:completion:
  1028. @brief Initiates a password reset for the given email address and @FIRActionCodeSettings object.
  1029. @param actionCodeSettings Optionally, An @c FIRActionCodeSettings object containing settings
  1030. related to the handling action codes.
  1031. @param email The email address of the user.
  1032. @param completion Optionally; a block which is invoked when the request finishes. Invoked
  1033. asynchronously on the main thread in the future.
  1034. */
  1035. - (void)sendPasswordResetWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *)
  1036. actionCodeSettings
  1037. email:(NSString *)email
  1038. completion:(nullable FIRSendPasswordResetCallback)
  1039. completion {
  1040. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1041. if (!email) {
  1042. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  1043. kMissingEmailInvalidParameterExceptionReason];
  1044. }
  1045. FIRGetOOBConfirmationCodeRequest *request =
  1046. [FIRGetOOBConfirmationCodeRequest passwordResetRequestWithEmail:email
  1047. actionCodeSettings:actionCodeSettings
  1048. requestConfiguration:self->_requestConfiguration
  1049. ];
  1050. [FIRAuthBackend getOOBConfirmationCode:request
  1051. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1052. NSError *_Nullable error) {
  1053. if (completion) {
  1054. dispatch_async(dispatch_get_main_queue(), ^{
  1055. completion(error);
  1056. });
  1057. }
  1058. }];
  1059. });
  1060. }
  1061. - (void)sendSignInLinkToEmail:(nonnull NSString *)email
  1062. actionCodeSettings:(nonnull FIRActionCodeSettings *)actionCodeSettings
  1063. completion:(nullable FIRSendSignInLinkToEmailCallback)completion {
  1064. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1065. if (!email) {
  1066. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  1067. kMissingEmailInvalidParameterExceptionReason];
  1068. }
  1069. if (!actionCodeSettings.handleCodeInApp) {
  1070. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  1071. kHandleCodeInAppFalseExceptionReason];
  1072. }
  1073. FIRGetOOBConfirmationCodeRequest *request =
  1074. [FIRGetOOBConfirmationCodeRequest signInWithEmailLinkRequest:email
  1075. actionCodeSettings:actionCodeSettings
  1076. requestConfiguration:self->_requestConfiguration];
  1077. [FIRAuthBackend getOOBConfirmationCode:request
  1078. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1079. NSError *_Nullable error) {
  1080. if (completion) {
  1081. dispatch_async(dispatch_get_main_queue(), ^{
  1082. completion(error);
  1083. });
  1084. }
  1085. }];
  1086. });
  1087. }
  1088. - (void)updateCurrentUser:(FIRUser *)user completion:(nullable FIRUserUpdateCallback)completion {
  1089. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1090. if (!user) {
  1091. if (completion) {
  1092. dispatch_async(dispatch_get_main_queue(), ^{
  1093. completion([FIRAuthErrorUtils nullUserErrorWithMessage:nil]);
  1094. });
  1095. }
  1096. return;
  1097. }
  1098. void (^updateUserBlock)(FIRUser *user) = ^(FIRUser *user) {
  1099. NSError *error;
  1100. [self updateCurrentUser:user byForce:YES savingToDisk:YES error:(&error)];
  1101. if (error) {
  1102. if (completion) {
  1103. dispatch_async(dispatch_get_main_queue(), ^{
  1104. completion(error);
  1105. });
  1106. }
  1107. return;
  1108. } if (completion) {
  1109. dispatch_async(dispatch_get_main_queue(), ^{
  1110. completion(nil);
  1111. });
  1112. }
  1113. };
  1114. if (![user.requestConfiguration.APIKey isEqualToString:self->_requestConfiguration.APIKey]) {
  1115. // If the API keys are different, then we need to confirm that the user belongs to the same
  1116. // project before proceeding.
  1117. user.requestConfiguration = self->_requestConfiguration;
  1118. [user reloadWithCompletion:^(NSError *_Nullable error) {
  1119. if (error) {
  1120. if (completion) {
  1121. dispatch_async(dispatch_get_main_queue(), ^{
  1122. completion(error);
  1123. });
  1124. }
  1125. return;
  1126. }
  1127. updateUserBlock(user);
  1128. }];
  1129. } else {
  1130. updateUserBlock(user);
  1131. }
  1132. });
  1133. }
  1134. - (BOOL)signOut:(NSError *_Nullable __autoreleasing *_Nullable)error {
  1135. __block BOOL result = YES;
  1136. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1137. if (!self->_currentUser) {
  1138. return;
  1139. }
  1140. result = [self updateCurrentUser:nil byForce:NO savingToDisk:YES error:error];
  1141. });
  1142. return result;
  1143. }
  1144. - (BOOL)signOutByForceWithUserID:(NSString *)userID error:(NSError *_Nullable *_Nullable)error {
  1145. if (_currentUser.uid != userID) {
  1146. return YES;
  1147. }
  1148. return [self updateCurrentUser:nil byForce:YES savingToDisk:YES error:error];
  1149. }
  1150. - (BOOL)isSignInWithEmailLink:(NSString *)link {
  1151. if (link.length == 0) {
  1152. return NO;
  1153. }
  1154. NSDictionary<NSString *, NSString *> *queryItems = FIRAuthParseURL(link);
  1155. if (![queryItems count]) {
  1156. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  1157. if (!urlComponents.query) {
  1158. return NO;
  1159. }
  1160. queryItems = FIRAuthParseURL(urlComponents.query);
  1161. }
  1162. if (![queryItems count]) {
  1163. return NO;
  1164. }
  1165. NSString *actionCode = queryItems[@"oobCode"];
  1166. NSString *mode = queryItems[@"mode"];
  1167. if (actionCode && [mode isEqualToString:@"signIn"]) {
  1168. return YES;
  1169. }
  1170. return NO;
  1171. }
  1172. /** @fn FIRAuthParseURL:NSString
  1173. @brief Parses an incoming URL into all available query items.
  1174. @param urlString The url to be parsed.
  1175. @return A dictionary of available query items in the target URL.
  1176. */
  1177. static NSDictionary<NSString *, NSString *> *FIRAuthParseURL(NSString *urlString) {
  1178. NSString *linkURL = [NSURLComponents componentsWithString:urlString].query;
  1179. if (!linkURL) {
  1180. return @{};
  1181. }
  1182. NSArray<NSString *> *URLComponents = [linkURL componentsSeparatedByString:@"&"];
  1183. NSMutableDictionary<NSString *, NSString *> *queryItems =
  1184. [[NSMutableDictionary alloc] initWithCapacity:URLComponents.count];
  1185. for (NSString *component in URLComponents) {
  1186. NSRange equalRange = [component rangeOfString:@"="];
  1187. if (equalRange.location != NSNotFound) {
  1188. NSString *queryItemKey =
  1189. [[component substringToIndex:equalRange.location] stringByRemovingPercentEncoding];
  1190. NSString *queryItemValue =
  1191. [[component substringFromIndex:equalRange.location + 1] stringByRemovingPercentEncoding];
  1192. if (queryItemKey && queryItemValue) {
  1193. queryItems[queryItemKey] = queryItemValue;
  1194. }
  1195. }
  1196. }
  1197. return queryItems;
  1198. }
  1199. - (FIRAuthStateDidChangeListenerHandle)addAuthStateDidChangeListener:
  1200. (FIRAuthStateDidChangeListenerBlock)listener {
  1201. __block BOOL firstInvocation = YES;
  1202. __block NSString *previousUserID;
  1203. return [self addIDTokenDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) {
  1204. BOOL shouldCallListener = firstInvocation ||
  1205. !(previousUserID == user.uid || [previousUserID isEqualToString:user.uid]);
  1206. firstInvocation = NO;
  1207. previousUserID = [user.uid copy];
  1208. if (shouldCallListener) {
  1209. listener(auth, user);
  1210. }
  1211. }];
  1212. }
  1213. - (void)removeAuthStateDidChangeListener:(FIRAuthStateDidChangeListenerHandle)listenerHandle {
  1214. [self removeIDTokenDidChangeListener:listenerHandle];
  1215. }
  1216. - (FIRIDTokenDidChangeListenerHandle)addIDTokenDidChangeListener:
  1217. (FIRIDTokenDidChangeListenerBlock)listener {
  1218. if (!listener) {
  1219. [NSException raise:NSInvalidArgumentException format:@"listener must not be nil."];
  1220. return nil;
  1221. }
  1222. FIRAuthStateDidChangeListenerHandle handle;
  1223. NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter];
  1224. handle = [notifications addObserverForName:FIRAuthStateDidChangeNotification
  1225. object:self
  1226. queue:[NSOperationQueue mainQueue]
  1227. usingBlock:^(NSNotification *_Nonnull notification) {
  1228. FIRAuth *auth = notification.object;
  1229. listener(auth, auth.currentUser);
  1230. }];
  1231. @synchronized (self) {
  1232. [_listenerHandles addObject:handle];
  1233. }
  1234. dispatch_async(dispatch_get_main_queue(), ^{
  1235. listener(self, self->_currentUser);
  1236. });
  1237. return handle;
  1238. }
  1239. - (void)removeIDTokenDidChangeListener:(FIRIDTokenDidChangeListenerHandle)listenerHandle {
  1240. [[NSNotificationCenter defaultCenter] removeObserver:listenerHandle];
  1241. @synchronized (self) {
  1242. [_listenerHandles removeObject:listenerHandle];
  1243. }
  1244. }
  1245. - (void)useAppLanguage {
  1246. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1247. self->_requestConfiguration.languageCode =
  1248. [NSBundle mainBundle].preferredLocalizations.firstObject;
  1249. });
  1250. }
  1251. - (nullable NSString *)languageCode {
  1252. return _requestConfiguration.languageCode;
  1253. }
  1254. - (void)setLanguageCode:(nullable NSString *)languageCode {
  1255. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1256. self->_requestConfiguration.languageCode = [languageCode copy];
  1257. });
  1258. }
  1259. - (NSString *)additionalFrameworkMarker {
  1260. return self->_requestConfiguration.additionalFrameworkMarker;
  1261. }
  1262. - (void)setAdditionalFrameworkMarker:(NSString *)additionalFrameworkMarker {
  1263. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1264. self->_requestConfiguration.additionalFrameworkMarker = [additionalFrameworkMarker copy];
  1265. });
  1266. }
  1267. #if TARGET_OS_IOS
  1268. - (NSData *)APNSToken {
  1269. __block NSData *result = nil;
  1270. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1271. result = self->_tokenManager.token.data;
  1272. });
  1273. return result;
  1274. }
  1275. - (void)setAPNSToken:(NSData *)APNSToken {
  1276. [self setAPNSToken:APNSToken type:FIRAuthAPNSTokenTypeUnknown];
  1277. }
  1278. - (void)setAPNSToken:(NSData *)token type:(FIRAuthAPNSTokenType)type {
  1279. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1280. self->_tokenManager.token = [[FIRAuthAPNSToken alloc] initWithData:token type:type];
  1281. });
  1282. }
  1283. - (void)handleAPNSTokenError:(NSError *)error {
  1284. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1285. [self->_tokenManager cancelWithError:error];
  1286. });
  1287. }
  1288. - (BOOL)canHandleNotification:(NSDictionary *)userInfo {
  1289. __block BOOL result = NO;
  1290. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1291. result = [self->_notificationManager canHandleNotification:userInfo];
  1292. });
  1293. return result;
  1294. }
  1295. - (BOOL)canHandleURL:(NSURL *)URL {
  1296. __block BOOL result = NO;
  1297. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1298. result = [self->_authURLPresenter canHandleURL:URL];
  1299. });
  1300. return result;
  1301. }
  1302. #endif
  1303. #pragma mark - Internal Methods
  1304. #if TARGET_OS_IOS
  1305. /** @fn signInWithPhoneCredential:callback:
  1306. @brief Signs in using a phone credential.
  1307. @param credential The Phone Auth credential used to sign in.
  1308. @param operation The type of operation for which this sign-in attempt is initiated.
  1309. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  1310. asynchronously on the global auth work queue in the future.
  1311. */
  1312. - (void)signInWithPhoneCredential:(FIRPhoneAuthCredential *)credential
  1313. operation:(FIRAuthOperationType)operation
  1314. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  1315. if (credential.temporaryProof.length && credential.phoneNumber.length) {
  1316. FIRVerifyPhoneNumberRequest *request =
  1317. [[FIRVerifyPhoneNumberRequest alloc] initWithTemporaryProof:credential.temporaryProof
  1318. phoneNumber:credential.phoneNumber
  1319. operation:operation
  1320. requestConfiguration:_requestConfiguration];
  1321. [FIRAuthBackend verifyPhoneNumber:request callback:callback];
  1322. return;
  1323. }
  1324. if (!credential.verificationID.length) {
  1325. callback(nil, [FIRAuthErrorUtils missingVerificationIDErrorWithMessage:nil]);
  1326. return;
  1327. }
  1328. if (!credential.verificationCode.length) {
  1329. callback(nil, [FIRAuthErrorUtils missingVerificationCodeErrorWithMessage:nil]);
  1330. return;
  1331. }
  1332. FIRVerifyPhoneNumberRequest *request =
  1333. [[FIRVerifyPhoneNumberRequest alloc]initWithVerificationID:credential.verificationID
  1334. verificationCode:credential.verificationCode
  1335. operation:operation
  1336. requestConfiguration:_requestConfiguration];
  1337. [FIRAuthBackend verifyPhoneNumber:request callback:callback];
  1338. }
  1339. #endif
  1340. /** @fn internalSignInAndRetrieveDataWithCustomToken:completion:
  1341. @brief Signs in a Firebase user given a custom token.
  1342. @param token A self-signed custom auth token.
  1343. @param completion A block which is invoked when the custom token sign in request completes.
  1344. */
  1345. - (void)internalSignInAndRetrieveDataWithCustomToken:(NSString *)token
  1346. completion:(nullable FIRAuthDataResultCallback)
  1347. completion {
  1348. FIRVerifyCustomTokenRequest *request =
  1349. [[FIRVerifyCustomTokenRequest alloc] initWithToken:token
  1350. requestConfiguration:_requestConfiguration];
  1351. [FIRAuthBackend verifyCustomToken:request
  1352. callback:^(FIRVerifyCustomTokenResponse *_Nullable response,
  1353. NSError *_Nullable error) {
  1354. if (error) {
  1355. if (completion) {
  1356. completion(nil, error);
  1357. return;
  1358. }
  1359. }
  1360. [self completeSignInWithAccessToken:response.IDToken
  1361. accessTokenExpirationDate:response.approximateExpirationDate
  1362. refreshToken:response.refreshToken
  1363. anonymous:NO
  1364. callback:^(FIRUser *_Nullable user,
  1365. NSError *_Nullable error) {
  1366. if (error) {
  1367. if (completion) {
  1368. completion(nil, error);
  1369. }
  1370. return;
  1371. }
  1372. FIRAdditionalUserInfo *additonalUserInfo =
  1373. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  1374. profile:nil
  1375. username:nil
  1376. isNewUser:response.isNewUser];
  1377. FIRAuthDataResult *result =
  1378. [[FIRAuthDataResult alloc] initWithUser:user additionalUserInfo:additonalUserInfo];
  1379. if (completion) {
  1380. completion(result, nil);
  1381. }
  1382. }];
  1383. }];
  1384. }
  1385. /** @fn internalCreateUserWithEmail:password:completion:
  1386. @brief Makes a backend request attempting to create a new Firebase user given an email address
  1387. and password.
  1388. @param email The email address used to create the new Firebase user.
  1389. @param password The password used to create the new Firebase user.
  1390. @param completion Optionally; a block which is invoked when the request finishes.
  1391. */
  1392. - (void)internalCreateUserWithEmail:(NSString *)email
  1393. password:(NSString *)password
  1394. completion:(nullable FIRSignupNewUserCallback)completion {
  1395. FIRSignUpNewUserRequest *request =
  1396. [[FIRSignUpNewUserRequest alloc] initWithEmail:email
  1397. password:password
  1398. displayName:nil
  1399. requestConfiguration:_requestConfiguration];
  1400. if (![request.password length]) {
  1401. completion(nil, [FIRAuthErrorUtils
  1402. weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]);
  1403. return;
  1404. }
  1405. if (![request.email length]) {
  1406. completion(nil, [FIRAuthErrorUtils missingEmailErrorWithMessage:nil]);
  1407. return;
  1408. }
  1409. [FIRAuthBackend signUpNewUser:request callback:completion];
  1410. }
  1411. /** @fn internalSignInAnonymouslyWithCompletion:
  1412. @param completion A block which is invoked when the anonymous sign in request completes.
  1413. */
  1414. - (void)internalSignInAnonymouslyWithCompletion:(FIRSignupNewUserCallback)completion {
  1415. FIRSignUpNewUserRequest *request =
  1416. [[FIRSignUpNewUserRequest alloc]initWithRequestConfiguration:_requestConfiguration];
  1417. [FIRAuthBackend signUpNewUser:request
  1418. callback:completion];
  1419. }
  1420. /** @fn possiblyPostAuthStateChangeNotification
  1421. @brief Posts the auth state change notificaton if current user's token has been changed.
  1422. */
  1423. - (void)possiblyPostAuthStateChangeNotification {
  1424. NSString *token = _currentUser.rawAccessToken;
  1425. if (_lastNotifiedUserToken == token || [_lastNotifiedUserToken isEqualToString:token]) {
  1426. return;
  1427. }
  1428. _lastNotifiedUserToken = token;
  1429. if (_autoRefreshTokens) {
  1430. // Shedule new refresh task after successful attempt.
  1431. [self scheduleAutoTokenRefresh];
  1432. }
  1433. NSMutableDictionary *internalNotificationParameters = [NSMutableDictionary dictionary];
  1434. if (self.app) {
  1435. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationAppKey] = self.app;
  1436. }
  1437. if (token.length) {
  1438. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationTokenKey] = token;
  1439. }
  1440. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationUIDKey] = _currentUser.uid;
  1441. NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter];
  1442. dispatch_async(dispatch_get_main_queue(), ^{
  1443. [notifications postNotificationName:FIRAuthStateDidChangeInternalNotification
  1444. object:self
  1445. userInfo:internalNotificationParameters];
  1446. [notifications postNotificationName:FIRAuthStateDidChangeNotification
  1447. object:self];
  1448. });
  1449. }
  1450. - (BOOL)updateKeychainWithUser:(FIRUser *)user error:(NSError *_Nullable *_Nullable)error {
  1451. if (user != _currentUser) {
  1452. // No-op if the user is no longer signed in. This is not considered an error as we don't check
  1453. // whether the user is still current on other callbacks of user operations either.
  1454. return YES;
  1455. }
  1456. if ([self saveUser:user error:error]) {
  1457. [self possiblyPostAuthStateChangeNotification];
  1458. return YES;
  1459. }
  1460. return NO;
  1461. }
  1462. /** @fn setKeychainServiceNameForApp
  1463. @brief Sets the keychain service name global data for the particular app.
  1464. @param app The Firebase app to set keychain service name for.
  1465. */
  1466. + (void)setKeychainServiceNameForApp:(FIRApp *)app {
  1467. @synchronized (self) {
  1468. gKeychainServiceNameForAppName[app.name] =
  1469. [@"firebase_auth_" stringByAppendingString:app.options.googleAppID];
  1470. }
  1471. }
  1472. /** @fn keychainServiceNameForAppName:
  1473. @brief Gets the keychain service name global data for the particular app by name.
  1474. @param appName The name of the Firebase app to get keychain service name for.
  1475. */
  1476. + (NSString *)keychainServiceNameForAppName:(NSString *)appName {
  1477. @synchronized (self) {
  1478. return gKeychainServiceNameForAppName[appName];
  1479. }
  1480. }
  1481. /** @fn deleteKeychainServiceNameForAppName:
  1482. @brief Deletes the keychain service name global data for the particular app by name.
  1483. @param appName The name of the Firebase app to delete keychain service name for.
  1484. */
  1485. + (void)deleteKeychainServiceNameForAppName:(NSString *)appName {
  1486. @synchronized (self) {
  1487. [gKeychainServiceNameForAppName removeObjectForKey:appName];
  1488. }
  1489. }
  1490. /** @fn scheduleAutoTokenRefreshWithDelay:
  1491. @brief Schedules a task to automatically refresh tokens on the current user. The token refresh
  1492. is scheduled 5 minutes before the scheduled expiration time.
  1493. @remarks If the token expires in less than 5 minutes, schedule the token refresh immediately.
  1494. */
  1495. - (void)scheduleAutoTokenRefresh {
  1496. NSTimeInterval tokenExpirationInterval =
  1497. [_currentUser.accessTokenExpirationDate timeIntervalSinceNow] - kTokenRefreshHeadStart;
  1498. [self scheduleAutoTokenRefreshWithDelay:MAX(tokenExpirationInterval, 0) retry:NO];
  1499. }
  1500. /** @fn scheduleAutoTokenRefreshWithDelay:
  1501. @brief Schedules a task to automatically refresh tokens on the current user.
  1502. @param delay The delay in seconds after which the token refresh task should be scheduled to be
  1503. executed.
  1504. @param retry Flag to determine whether the invocation is a retry attempt or not.
  1505. */
  1506. - (void)scheduleAutoTokenRefreshWithDelay:(NSTimeInterval)delay retry:(BOOL)retry {
  1507. NSString *accessToken = _currentUser.rawAccessToken;
  1508. if (!accessToken) {
  1509. return;
  1510. }
  1511. if (retry) {
  1512. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000003",
  1513. @"Token auto-refresh re-scheduled in %02d:%02d "
  1514. @"because of error on previous refresh attempt.",
  1515. (int)ceil(delay) / 60, (int)ceil(delay) % 60);
  1516. } else {
  1517. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000004",
  1518. @"Token auto-refresh scheduled in %02d:%02d for the new token.",
  1519. (int)ceil(delay) / 60, (int)ceil(delay) % 60);
  1520. }
  1521. _autoRefreshScheduled = YES;
  1522. __weak FIRAuth *weakSelf = self;
  1523. [[FIRAuthDispatcher sharedInstance] dispatchAfterDelay:delay
  1524. queue:FIRAuthGlobalWorkQueue()
  1525. task:^(void) {
  1526. FIRAuth *strongSelf = weakSelf;
  1527. if (!strongSelf) {
  1528. return;
  1529. }
  1530. if (![strongSelf->_currentUser.rawAccessToken isEqualToString:accessToken]) {
  1531. // Another auto refresh must have been scheduled, so keep _autoRefreshScheduled unchanged.
  1532. return;
  1533. }
  1534. strongSelf->_autoRefreshScheduled = NO;
  1535. if (strongSelf->_isAppInBackground) {
  1536. return;
  1537. }
  1538. NSString *uid = strongSelf->_currentUser.uid;
  1539. [strongSelf->_currentUser internalGetTokenForcingRefresh:YES
  1540. callback:^(NSString *_Nullable token,
  1541. NSError *_Nullable error) {
  1542. if (![strongSelf->_currentUser.uid isEqualToString:uid]) {
  1543. return;
  1544. }
  1545. if (error) {
  1546. // Kicks off exponential back off logic to retry failed attempt. Starts with one minute
  1547. // delay (60 seconds) if this is the first failed attempt.
  1548. NSTimeInterval rescheduleDelay;
  1549. if (retry) {
  1550. rescheduleDelay = MIN(delay * 2, kMaxWaitTimeForBackoff);
  1551. } else {
  1552. rescheduleDelay = 60;
  1553. }
  1554. [strongSelf scheduleAutoTokenRefreshWithDelay:rescheduleDelay retry:YES];
  1555. }
  1556. }];
  1557. }];
  1558. }
  1559. #pragma mark -
  1560. /** @fn completeSignInWithTokenService:callback:
  1561. @brief Completes a sign-in flow once we have access and refresh tokens for the user.
  1562. @param accessToken The STS access token.
  1563. @param accessTokenExpirationDate The approximate expiration date of the access token.
  1564. @param refreshToken The STS refresh token.
  1565. @param anonymous Whether or not the user is anonymous.
  1566. @param callback Called when the user has been signed in or when an error occurred. Invoked
  1567. asynchronously on the global auth work queue in the future.
  1568. */
  1569. - (void)completeSignInWithAccessToken:(NSString *)accessToken
  1570. accessTokenExpirationDate:(NSDate *)accessTokenExpirationDate
  1571. refreshToken:(NSString *)refreshToken
  1572. anonymous:(BOOL)anonymous
  1573. callback:(FIRAuthResultCallback)callback {
  1574. [FIRUser retrieveUserWithAuth:self
  1575. accessToken:accessToken
  1576. accessTokenExpirationDate:accessTokenExpirationDate
  1577. refreshToken:refreshToken
  1578. anonymous:anonymous
  1579. callback:callback];
  1580. }
  1581. /** @fn signInFlowAuthResultCallbackByDecoratingCallback:
  1582. @brief Creates a FIRAuthResultCallback block which wraps another FIRAuthResultCallback; trying
  1583. to update the current user before forwarding it's invocations along to a subject block
  1584. @param callback Called when the user has been updated or when an error has occurred. Invoked
  1585. asynchronously on the main thread in the future.
  1586. @return Returns a block that updates the current user.
  1587. @remarks Typically invoked as part of the complete sign-in flow. For any other uses please
  1588. consider alternative ways of updating the current user.
  1589. */
  1590. - (FIRAuthResultCallback)signInFlowAuthResultCallbackByDecoratingCallback:
  1591. (nullable FIRAuthResultCallback)callback {
  1592. return ^(FIRUser *_Nullable user, NSError *_Nullable error) {
  1593. if (error) {
  1594. if (callback) {
  1595. dispatch_async(dispatch_get_main_queue(), ^{
  1596. callback(nil, error);
  1597. });
  1598. }
  1599. return;
  1600. }
  1601. if (![self updateCurrentUser:user byForce:NO savingToDisk:YES error:&error]) {
  1602. if (callback) {
  1603. dispatch_async(dispatch_get_main_queue(), ^{
  1604. callback(nil, error);
  1605. });
  1606. }
  1607. return;
  1608. }
  1609. if (callback) {
  1610. dispatch_async(dispatch_get_main_queue(), ^{
  1611. callback(user, nil);
  1612. });
  1613. }
  1614. };
  1615. }
  1616. /** @fn signInFlowAuthDataResultCallbackByDecoratingCallback:
  1617. @brief Creates a FIRAuthDataResultCallback block which wraps another FIRAuthDataResultCallback;
  1618. trying to update the current user before forwarding it's invocations along to a subject
  1619. block.
  1620. @param callback Called when the user has been updated or when an error has occurred. Invoked
  1621. asynchronously on the main thread in the future.
  1622. @return Returns a block that updates the current user.
  1623. @remarks Typically invoked as part of the complete sign-in flow. For any other uses please
  1624. consider alternative ways of updating the current user.
  1625. */
  1626. - (FIRAuthDataResultCallback)signInFlowAuthDataResultCallbackByDecoratingCallback:
  1627. (nullable FIRAuthDataResultCallback)callback {
  1628. return ^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1629. if (error) {
  1630. if (callback) {
  1631. dispatch_async(dispatch_get_main_queue(), ^{
  1632. callback(nil, error);
  1633. });
  1634. }
  1635. return;
  1636. }
  1637. if (![self updateCurrentUser:authResult.user byForce:NO savingToDisk:YES error:&error]) {
  1638. if (callback) {
  1639. dispatch_async(dispatch_get_main_queue(), ^{
  1640. callback(nil, error);
  1641. });
  1642. }
  1643. return;
  1644. }
  1645. if (callback) {
  1646. dispatch_async(dispatch_get_main_queue(), ^{
  1647. callback(authResult, nil);
  1648. });
  1649. }
  1650. };
  1651. }
  1652. #pragma mark - User-Related Methods
  1653. /** @fn updateCurrentUser:savingToDisk:
  1654. @brief Update the current user; initializing the user's internal properties correctly, and
  1655. optionally saving the user to disk.
  1656. @remarks This method is called during: sign in and sign out events, as well as during class
  1657. initialization time. The only time the saveToDisk parameter should be set to NO is during
  1658. class initialization time because the user was just read from disk.
  1659. @param user The user to use as the current user (including nil, which is passed at sign out
  1660. time.)
  1661. @param saveToDisk Indicates the method should persist the user data to disk.
  1662. */
  1663. - (BOOL)updateCurrentUser:(FIRUser *)user
  1664. byForce:(BOOL)force
  1665. savingToDisk:(BOOL)saveToDisk
  1666. error:(NSError *_Nullable *_Nullable)error {
  1667. if (user == _currentUser) {
  1668. [self possiblyPostAuthStateChangeNotification];
  1669. return YES;
  1670. }
  1671. BOOL success = YES;
  1672. if (saveToDisk) {
  1673. success = [self saveUser:user error:error];
  1674. }
  1675. if (success || force) {
  1676. _currentUser = user;
  1677. [self possiblyPostAuthStateChangeNotification];
  1678. }
  1679. return success;
  1680. }
  1681. /** @fn saveUser:error:
  1682. @brief Persists user.
  1683. @param user The user to save.
  1684. @param error Return value for any error which occurs.
  1685. @return @YES on success, @NO otherwise.
  1686. */
  1687. - (BOOL)saveUser:(FIRUser *)user
  1688. error:(NSError *_Nullable *_Nullable)error {
  1689. BOOL success;
  1690. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  1691. if (!user) {
  1692. success = [_keychain removeDataForKey:userKey error:error];
  1693. } else {
  1694. // Encode the user object.
  1695. NSMutableData *archiveData = [NSMutableData data];
  1696. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData];
  1697. [archiver encodeObject:user forKey:userKey];
  1698. [archiver finishEncoding];
  1699. // Save the user object's encoded value.
  1700. success = [_keychain setData:archiveData forKey:userKey error:error];
  1701. }
  1702. return success;
  1703. }
  1704. /** @fn getUser:error:
  1705. @brief Retrieves the saved user associated, if one exists, from the keychain.
  1706. @param outUser An out parameter which is populated with the saved user, if one exists.
  1707. @param error Return value for any error which occurs.
  1708. @return YES if the operation was a success (irrespective of whether or not a saved user existed
  1709. for the given @c firebaseAppId,) NO if an error occurred.
  1710. */
  1711. - (BOOL)getUser:(FIRUser *_Nullable *)outUser
  1712. error:(NSError *_Nullable *_Nullable)error {
  1713. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  1714. NSError *keychainError;
  1715. NSData *encodedUserData = [_keychain dataForKey:userKey error:&keychainError];
  1716. if (keychainError) {
  1717. if (error) {
  1718. *error = keychainError;
  1719. }
  1720. return NO;
  1721. }
  1722. if (!encodedUserData) {
  1723. *outUser = nil;
  1724. return YES;
  1725. }
  1726. NSKeyedUnarchiver *unarchiver =
  1727. [[NSKeyedUnarchiver alloc] initForReadingWithData:encodedUserData];
  1728. FIRUser *user = [unarchiver decodeObjectOfClass:[FIRUser class] forKey:userKey];
  1729. user.auth = self;
  1730. *outUser = user;
  1731. return YES;
  1732. }
  1733. - (nullable NSString *)getUID {
  1734. return _currentUser.uid;
  1735. }
  1736. @end