FIRAuth.m 103 KB

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