FIRAuth.m 100 KB

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