FIRAuth.m 97 KB

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