FIRAuth.m 102 KB

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