FIRAuth.m 80 KB

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