FIRAuth.m 101 KB

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