FIRAuth.m 101 KB

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