FIRAuth.m 97 KB

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