FIRUser.m 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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 "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuth.h"
  17. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIREmailAuthProvider.h"
  18. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRFederatedAuthProvider.h"
  19. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  20. #import "FirebaseAuth/Sources/Auth/FIRAuthDataResult_Internal.h"
  21. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  22. #import "FirebaseAuth/Sources/Auth/FIRAuthOperationType.h"
  23. #import "FirebaseAuth/Sources/Auth/FIRAuthSerialTaskQueue.h"
  24. #import "FirebaseAuth/Sources/Auth/FIRAuthTokenResult_Internal.h"
  25. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  26. #import "FirebaseAuth/Sources/AuthProvider/Email/FIREmailPasswordAuthCredential.h"
  27. #import "FirebaseAuth/Sources/AuthProvider/FIRAuthCredential_Internal.h"
  28. #import "FirebaseAuth/Sources/AuthProvider/GameCenter/FIRGameCenterAuthCredential.h"
  29. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  30. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  31. #import "FirebaseAuth/Sources/Backend/FIRAuthRequestConfiguration.h"
  32. #import "FirebaseAuth/Sources/Backend/RPC/FIRDeleteAccountRequest.h"
  33. #import "FirebaseAuth/Sources/Backend/RPC/FIRDeleteAccountResponse.h"
  34. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
  35. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
  36. #import "FirebaseAuth/Sources/Backend/RPC/FIRFinalizePasskeyEnrollmentRequest.h"
  37. #import "FirebaseAuth/Sources/Backend/RPC/FIRFinalizePasskeyEnrollmentResponse.h"
  38. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoRequest.h"
  39. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoResponse.h"
  40. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
  41. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
  42. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
  43. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
  44. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterRequest.h"
  45. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterResponse.h"
  46. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
  47. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
  48. #import "FirebaseAuth/Sources/Backend/RPC/FIRStartPasskeyEnrollmentRequest.h"
  49. #import "FirebaseAuth/Sources/Backend/RPC/FIRStartPasskeyEnrollmentResponse.h"
  50. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
  51. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
  52. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
  53. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
  54. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
  55. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
  56. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
  57. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
  58. #import "FirebaseAuth/Sources/MultiFactor/FIRMultiFactor+Internal.h"
  59. #import "FirebaseAuth/Sources/SystemService/FIRSecureTokenService.h"
  60. #import "FirebaseAuth/Sources/User/FIRAdditionalUserInfo_Internal.h"
  61. #import "FirebaseAuth/Sources/User/FIRUserInfoImpl.h"
  62. #import "FirebaseAuth/Sources/User/FIRUserMetadata_Internal.h"
  63. #import "FirebaseAuth/Sources/User/FIRUser_Internal.h"
  64. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  65. #import "FirebaseAuth/Sources/Utilities/FIRAuthWebUtils.h"
  66. #if TARGET_OS_IOS
  67. #import "FirebaseAuth/Sources/AuthProvider/Phone/FIRPhoneAuthCredential_Internal.h"
  68. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
  69. #import "FirebaseAuth/Sources/Utilities/FIRAuthRecaptchaVerifier.h"
  70. #endif
  71. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  72. #import <AuthenticationServices/AuthenticationServices.h>
  73. #endif
  74. NS_ASSUME_NONNULL_BEGIN
  75. /** @var kUserIDCodingKey
  76. @brief The key used to encode the user ID for NSSecureCoding.
  77. */
  78. static NSString *const kUserIDCodingKey = @"userID";
  79. /** @var kHasEmailPasswordCredentialCodingKey
  80. @brief The key used to encode the hasEmailPasswordCredential property for NSSecureCoding.
  81. */
  82. static NSString *const kHasEmailPasswordCredentialCodingKey = @"hasEmailPassword";
  83. /** @var kAnonymousCodingKey
  84. @brief The key used to encode the anonymous property for NSSecureCoding.
  85. */
  86. static NSString *const kAnonymousCodingKey = @"anonymous";
  87. /** @var kEmailCodingKey
  88. @brief The key used to encode the email property for NSSecureCoding.
  89. */
  90. static NSString *const kEmailCodingKey = @"email";
  91. /** @var kPhoneNumberCodingKey
  92. @brief The key used to encode the phoneNumber property for NSSecureCoding.
  93. */
  94. static NSString *const kPhoneNumberCodingKey = @"phoneNumber";
  95. /** @var kEmailVerifiedCodingKey
  96. @brief The key used to encode the isEmailVerified property for NSSecureCoding.
  97. */
  98. static NSString *const kEmailVerifiedCodingKey = @"emailVerified";
  99. /** @var kDisplayNameCodingKey
  100. @brief The key used to encode the displayName property for NSSecureCoding.
  101. */
  102. static NSString *const kDisplayNameCodingKey = @"displayName";
  103. /** @var kPhotoURLCodingKey
  104. @brief The key used to encode the photoURL property for NSSecureCoding.
  105. */
  106. static NSString *const kPhotoURLCodingKey = @"photoURL";
  107. /** @var kProviderDataKey
  108. @brief The key used to encode the providerData instance variable for NSSecureCoding.
  109. */
  110. static NSString *const kProviderDataKey = @"providerData";
  111. /** @var kAPIKeyCodingKey
  112. @brief The key used to encode the APIKey instance variable for NSSecureCoding.
  113. */
  114. static NSString *const kAPIKeyCodingKey = @"APIKey";
  115. /** @var kFirebaseAppIDCodingKey
  116. @brief The key used to encode the appID instance variable for NSSecureCoding.
  117. */
  118. static NSString *const kFirebaseAppIDCodingKey = @"firebaseAppID";
  119. /** @var kTokenServiceCodingKey
  120. @brief The key used to encode the tokenService instance variable for NSSecureCoding.
  121. */
  122. static NSString *const kTokenServiceCodingKey = @"tokenService";
  123. /** @var kMetadataCodingKey
  124. @brief The key used to encode the metadata instance variable for NSSecureCoding.
  125. */
  126. static NSString *const kMetadataCodingKey = @"metadata";
  127. static NSString *const kMultiFactorCodingKey = @"multiFactor";
  128. /** @var kTenantIDKey
  129. @brief The key used to encode the tenantID instance variable for NSSecureCoding.
  130. */
  131. static NSString *const kTenantIDCodingKey = @"tenantID";
  132. /** @var kMissingUsersErrorMessage
  133. @brief The error message when there is no users array in the getAccountInfo response.
  134. */
  135. static NSString *const kMissingUsersErrorMessage = @"users";
  136. /** @typedef CallbackWithError
  137. @brief The type for a callback block that only takes an error parameter.
  138. */
  139. typedef void (^CallbackWithError)(NSError *_Nullable);
  140. /** @typedef CallbackWithUserAndError
  141. @brief The type for a callback block that takes a user parameter and an error parameter.
  142. */
  143. typedef void (^CallbackWithUserAndError)(FIRUser *_Nullable, NSError *_Nullable);
  144. /** @typedef CallbackWithUserAndError
  145. @brief The type for a callback block that takes a user parameter and an error parameter.
  146. */
  147. typedef void (^CallbackWithAuthDataResultAndError)(FIRAuthDataResult *_Nullable,
  148. NSError *_Nullable);
  149. /** @var kMissingPasswordReason
  150. @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown.
  151. @remarks This error message will be localized in the future.
  152. */
  153. static NSString *const kMissingPasswordReason = @"Missing Password";
  154. /** @fn callInMainThreadWithError
  155. @brief Calls a callback in main thread with error.
  156. @param callback The callback to be called in main thread.
  157. @param error The error to pass to callback.
  158. */
  159. static void callInMainThreadWithError(_Nullable CallbackWithError callback,
  160. NSError *_Nullable error) {
  161. if (callback) {
  162. dispatch_async(dispatch_get_main_queue(), ^{
  163. callback(error);
  164. });
  165. }
  166. }
  167. /** @fn callInMainThreadWithUserAndError
  168. @brief Calls a callback in main thread with user and error.
  169. @param callback The callback to be called in main thread.
  170. @param user The user to pass to callback if there is no error.
  171. @param error The error to pass to callback.
  172. */
  173. static void callInMainThreadWithUserAndError(_Nullable CallbackWithUserAndError callback,
  174. FIRUser *_Nonnull user,
  175. NSError *_Nullable error) {
  176. if (callback) {
  177. dispatch_async(dispatch_get_main_queue(), ^{
  178. callback(error ? nil : user, error);
  179. });
  180. }
  181. }
  182. /** @fn callInMainThreadWithUserAndError
  183. @brief Calls a callback in main thread with user and error.
  184. @param callback The callback to be called in main thread.
  185. @param result The result to pass to callback if there is no error.
  186. @param error The error to pass to callback.
  187. */
  188. static void callInMainThreadWithAuthDataResultAndError(
  189. _Nullable CallbackWithAuthDataResultAndError callback,
  190. FIRAuthDataResult *_Nullable result,
  191. NSError *_Nullable error) {
  192. if (callback) {
  193. dispatch_async(dispatch_get_main_queue(), ^{
  194. callback(result, error);
  195. });
  196. }
  197. }
  198. @interface FIRUserProfileChangeRequest ()
  199. /** @fn initWithUser:
  200. @brief Designated initializer.
  201. @param user The user for which we are updating profile information.
  202. */
  203. - (nullable instancetype)initWithUser:(FIRUser *)user NS_DESIGNATED_INITIALIZER;
  204. @end
  205. @interface FIRUser ()
  206. /** @property anonymous
  207. @brief Whether the current user is anonymous.
  208. */
  209. @property(nonatomic, readwrite) BOOL anonymous;
  210. /** @property tenantID
  211. @brief The tenant ID of the current user. nil if none is available.
  212. */
  213. @property(nonatomic, readwrite, nullable) NSString *tenantID;
  214. @end
  215. @implementation FIRUser {
  216. /** @var _hasEmailPasswordCredential
  217. @brief Whether or not the user can be authenticated by using Firebase email and password.
  218. */
  219. BOOL _hasEmailPasswordCredential;
  220. /** @var _providerData
  221. @brief Provider specific user data.
  222. */
  223. NSDictionary<NSString *, FIRUserInfoImpl *> *_providerData;
  224. /** @var _taskQueue
  225. @brief Used to serialize the update profile calls.
  226. */
  227. FIRAuthSerialTaskQueue *_taskQueue;
  228. /** @var _tokenService
  229. @brief A secure token service associated with this user. For performing token exchanges and
  230. refreshing access tokens.
  231. */
  232. FIRSecureTokenService *_tokenService;
  233. }
  234. #pragma mark - Properties
  235. // Explicitly @synthesize because these properties are defined in FIRUserInfo protocol.
  236. @synthesize uid = _userID;
  237. @synthesize displayName = _displayName;
  238. @synthesize photoURL = _photoURL;
  239. @synthesize email = _email;
  240. @synthesize phoneNumber = _phoneNumber;
  241. #pragma mark -
  242. + (void)retrieveUserWithAuth:(FIRAuth *)auth
  243. accessToken:(nullable NSString *)accessToken
  244. accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate
  245. refreshToken:(nullable NSString *)refreshToken
  246. anonymous:(BOOL)anonymous
  247. callback:(FIRRetrieveUserCallback)callback {
  248. FIRSecureTokenService *tokenService =
  249. [[FIRSecureTokenService alloc] initWithRequestConfiguration:auth.requestConfiguration
  250. accessToken:accessToken
  251. accessTokenExpirationDate:accessTokenExpirationDate
  252. refreshToken:refreshToken];
  253. FIRUser *user = [[self alloc] initWithTokenService:tokenService];
  254. user.auth = auth;
  255. user.tenantID = auth.tenantID;
  256. user.requestConfiguration = auth.requestConfiguration;
  257. [user internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  258. if (error) {
  259. callback(nil, error);
  260. return;
  261. }
  262. FIRGetAccountInfoRequest *getAccountInfoRequest =
  263. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  264. requestConfiguration:auth.requestConfiguration];
  265. [FIRAuthBackend
  266. getAccountInfo:getAccountInfoRequest
  267. callback:^(FIRGetAccountInfoResponse *_Nullable response, NSError *_Nullable error) {
  268. if (error) {
  269. // No need to sign out user here for errors because the user hasn't been signed in
  270. // yet.
  271. callback(nil, error);
  272. return;
  273. }
  274. user.anonymous = anonymous;
  275. [user updateWithGetAccountInfoResponse:response];
  276. callback(user, nil);
  277. }];
  278. }];
  279. }
  280. - (instancetype)initWithTokenService:(FIRSecureTokenService *)tokenService {
  281. self = [super init];
  282. if (self) {
  283. _providerData = @{};
  284. _taskQueue = [[FIRAuthSerialTaskQueue alloc] init];
  285. _tokenService = tokenService;
  286. }
  287. return self;
  288. }
  289. #pragma mark - NSSecureCoding
  290. + (BOOL)supportsSecureCoding {
  291. return YES;
  292. }
  293. - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
  294. NSString *userID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserIDCodingKey];
  295. BOOL hasAnonymousKey = [aDecoder containsValueForKey:kAnonymousCodingKey];
  296. BOOL anonymous = [aDecoder decodeBoolForKey:kAnonymousCodingKey];
  297. BOOL hasEmailPasswordCredential =
  298. [aDecoder decodeBoolForKey:kHasEmailPasswordCredentialCodingKey];
  299. NSString *displayName = [aDecoder decodeObjectOfClass:[NSString class]
  300. forKey:kDisplayNameCodingKey];
  301. NSURL *photoURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kPhotoURLCodingKey];
  302. NSString *email = [aDecoder decodeObjectOfClass:[NSString class] forKey:kEmailCodingKey];
  303. NSString *phoneNumber = [aDecoder decodeObjectOfClass:[NSString class]
  304. forKey:kPhoneNumberCodingKey];
  305. BOOL emailVerified = [aDecoder decodeBoolForKey:kEmailVerifiedCodingKey];
  306. NSSet *providerDataClasses =
  307. [NSSet setWithArray:@[ [NSDictionary class], [NSString class], [FIRUserInfoImpl class] ]];
  308. NSDictionary<NSString *, FIRUserInfoImpl *> *providerData =
  309. [aDecoder decodeObjectOfClasses:providerDataClasses forKey:kProviderDataKey];
  310. FIRSecureTokenService *tokenService = [aDecoder decodeObjectOfClass:[FIRSecureTokenService class]
  311. forKey:kTokenServiceCodingKey];
  312. FIRUserMetadata *metadata = [aDecoder decodeObjectOfClass:[FIRUserMetadata class]
  313. forKey:kMetadataCodingKey];
  314. NSString *tenantID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kTenantIDCodingKey];
  315. NSString *APIKey = [aDecoder decodeObjectOfClass:[NSString class] forKey:kAPIKeyCodingKey];
  316. NSString *appID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kFirebaseAppIDCodingKey];
  317. #if TARGET_OS_IOS
  318. FIRMultiFactor *multiFactor = [aDecoder decodeObjectOfClass:[FIRMultiFactor class]
  319. forKey:kMultiFactorCodingKey];
  320. #endif
  321. if (!userID || !tokenService) {
  322. return nil;
  323. }
  324. self = [self initWithTokenService:tokenService];
  325. if (self) {
  326. _userID = userID;
  327. // Previous version of this code didn't save 'anonymous' bit directly but deduced it from
  328. // 'hasEmailPasswordCredential' and 'providerData' instead, so here backward compatibility is
  329. // provided to read old format data.
  330. _anonymous = hasAnonymousKey ? anonymous : (!hasEmailPasswordCredential && !providerData.count);
  331. _hasEmailPasswordCredential = hasEmailPasswordCredential;
  332. _email = email;
  333. _emailVerified = emailVerified;
  334. _displayName = displayName;
  335. _photoURL = photoURL;
  336. _providerData = providerData;
  337. _phoneNumber = phoneNumber;
  338. _metadata = metadata ?: [[FIRUserMetadata alloc] initWithCreationDate:nil lastSignInDate:nil];
  339. _tenantID = tenantID;
  340. // The `heartbeatLogger` and `appCheck` will be set later via a property update.
  341. _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey
  342. appID:appID
  343. auth:_auth
  344. heartbeatLogger:nil
  345. appCheck:nil];
  346. #if TARGET_OS_IOS
  347. _multiFactor = multiFactor ?: [[FIRMultiFactor alloc] init];
  348. _multiFactor.user = self;
  349. #endif
  350. }
  351. return self;
  352. }
  353. - (void)encodeWithCoder:(NSCoder *)aCoder {
  354. [aCoder encodeObject:_userID forKey:kUserIDCodingKey];
  355. [aCoder encodeBool:self.anonymous forKey:kAnonymousCodingKey];
  356. [aCoder encodeBool:_hasEmailPasswordCredential forKey:kHasEmailPasswordCredentialCodingKey];
  357. [aCoder encodeObject:_providerData forKey:kProviderDataKey];
  358. [aCoder encodeObject:_email forKey:kEmailCodingKey];
  359. [aCoder encodeObject:_phoneNumber forKey:kPhoneNumberCodingKey];
  360. [aCoder encodeBool:_emailVerified forKey:kEmailVerifiedCodingKey];
  361. [aCoder encodeObject:_photoURL forKey:kPhotoURLCodingKey];
  362. [aCoder encodeObject:_displayName forKey:kDisplayNameCodingKey];
  363. [aCoder encodeObject:_metadata forKey:kMetadataCodingKey];
  364. [aCoder encodeObject:_tenantID forKey:kTenantIDCodingKey];
  365. [aCoder encodeObject:_auth.requestConfiguration.APIKey forKey:kAPIKeyCodingKey];
  366. [aCoder encodeObject:_auth.requestConfiguration.appID forKey:kFirebaseAppIDCodingKey];
  367. [aCoder encodeObject:_tokenService forKey:kTokenServiceCodingKey];
  368. #if TARGET_OS_IOS
  369. [aCoder encodeObject:_multiFactor forKey:kMultiFactorCodingKey];
  370. #endif
  371. }
  372. #pragma mark -
  373. - (void)setAuth:(nullable FIRAuth *)auth {
  374. _auth = auth;
  375. _tokenService.requestConfiguration = auth.requestConfiguration;
  376. _requestConfiguration = auth.requestConfiguration;
  377. }
  378. - (NSString *)providerID {
  379. return @"Firebase";
  380. }
  381. - (NSArray<id<FIRUserInfo>> *)providerData {
  382. return _providerData.allValues;
  383. }
  384. /** @fn getAccountInfoRefreshingCache:
  385. @brief Gets the users's account data from the server, updating our local values.
  386. @param callback Invoked when the request to getAccountInfo has completed, or when an error has
  387. been detected. Invoked asynchronously on the auth global work queue in the future.
  388. */
  389. - (void)getAccountInfoRefreshingCache:(void (^)(FIRGetAccountInfoResponseUser *_Nullable user,
  390. NSError *_Nullable error))callback {
  391. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  392. if (error) {
  393. callback(nil, error);
  394. return;
  395. }
  396. FIRGetAccountInfoRequest *getAccountInfoRequest =
  397. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  398. requestConfiguration:self->_auth.requestConfiguration];
  399. [FIRAuthBackend
  400. getAccountInfo:getAccountInfoRequest
  401. callback:^(FIRGetAccountInfoResponse *_Nullable response, NSError *_Nullable error) {
  402. if (error) {
  403. [self signOutIfTokenIsInvalidWithError:error];
  404. callback(nil, error);
  405. return;
  406. }
  407. [self updateWithGetAccountInfoResponse:response];
  408. if (![self updateKeychain:&error]) {
  409. callback(nil, error);
  410. return;
  411. }
  412. callback(response.users.firstObject, nil);
  413. }];
  414. }];
  415. }
  416. - (void)updateWithGetAccountInfoResponse:(FIRGetAccountInfoResponse *)response {
  417. FIRGetAccountInfoResponseUser *user = response.users.firstObject;
  418. _userID = user.localID;
  419. _email = user.email;
  420. _emailVerified = user.emailVerified;
  421. _displayName = user.displayName;
  422. _photoURL = user.photoURL;
  423. _phoneNumber = user.phoneNumber;
  424. _hasEmailPasswordCredential = user.passwordHash.length > 0;
  425. _metadata = [[FIRUserMetadata alloc] initWithCreationDate:user.creationDate
  426. lastSignInDate:user.lastLoginDate];
  427. NSMutableDictionary<NSString *, FIRUserInfoImpl *> *providerData =
  428. [NSMutableDictionary dictionary];
  429. for (FIRGetAccountInfoResponseProviderUserInfo *providerUserInfo in user.providerUserInfo) {
  430. FIRUserInfoImpl *userInfo =
  431. [FIRUserInfoImpl userInfoWithGetAccountInfoResponseProviderUserInfo:providerUserInfo];
  432. if (userInfo) {
  433. providerData[providerUserInfo.providerID] = userInfo;
  434. }
  435. }
  436. _providerData = [providerData copy];
  437. #if TARGET_OS_IOS
  438. _multiFactor = [[FIRMultiFactor alloc] initWithMFAEnrollments:user.MFAEnrollments];
  439. _multiFactor.user = self;
  440. #endif
  441. }
  442. /** @fn executeUserUpdateWithChanges:callback:
  443. @brief Performs a setAccountInfo request by mutating the results of a getAccountInfo response,
  444. atomically in regards to other calls to this method.
  445. @param changeBlock A block responsible for mutating a template @c FIRSetAccountInfoRequest
  446. @param callback A block to invoke when the change is complete. Invoked asynchronously on the
  447. auth global work queue in the future.
  448. */
  449. - (void)executeUserUpdateWithChanges:(void (^)(FIRGetAccountInfoResponseUser *,
  450. FIRSetAccountInfoRequest *))changeBlock
  451. callback:(nonnull FIRUserProfileChangeCallback)callback {
  452. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  453. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  454. NSError *_Nullable error) {
  455. if (error) {
  456. complete();
  457. callback(error);
  458. return;
  459. }
  460. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  461. NSError *_Nullable error) {
  462. if (error) {
  463. complete();
  464. callback(error);
  465. return;
  466. }
  467. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  468. // Mutate setAccountInfoRequest in block:
  469. FIRSetAccountInfoRequest *setAccountInfoRequest =
  470. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:configuration];
  471. setAccountInfoRequest.accessToken = accessToken;
  472. changeBlock(user, setAccountInfoRequest);
  473. // Execute request:
  474. [FIRAuthBackend
  475. setAccountInfo:setAccountInfoRequest
  476. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  477. NSError *_Nullable error) {
  478. if (error) {
  479. [self signOutIfTokenIsInvalidWithError:error];
  480. complete();
  481. callback(error);
  482. return;
  483. }
  484. if (response.IDToken && response.refreshToken) {
  485. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  486. initWithRequestConfiguration:configuration
  487. accessToken:response.IDToken
  488. accessTokenExpirationDate:response.approximateExpirationDate
  489. refreshToken:response.refreshToken];
  490. [self setTokenService:tokenService
  491. callback:^(NSError *_Nullable error) {
  492. complete();
  493. callback(error);
  494. }];
  495. return;
  496. }
  497. complete();
  498. callback(nil);
  499. }];
  500. }];
  501. }];
  502. }];
  503. }
  504. /** @fn updateKeychain:
  505. @brief Updates the keychain for user token or info changes.
  506. @param error The error if NO is returned.
  507. @return Whether the operation is successful.
  508. */
  509. - (BOOL)updateKeychain:(NSError *_Nullable *_Nullable)error {
  510. return [_auth updateKeychainWithUser:self error:error];
  511. }
  512. /** @fn setTokenService:callback:
  513. @brief Sets a new token service for the @c FIRUser instance.
  514. @param tokenService The new token service object.
  515. @param callback The block to be called in the global auth working queue once finished.
  516. @remarks The method makes sure the token service has access and refresh token and the new tokens
  517. are saved in the keychain before calling back.
  518. */
  519. - (void)setTokenService:(FIRSecureTokenService *)tokenService
  520. callback:(nonnull CallbackWithError)callback {
  521. [tokenService fetchAccessTokenForcingRefresh:NO
  522. callback:^(NSString *_Nullable token,
  523. NSError *_Nullable error, BOOL tokenUpdated) {
  524. if (error) {
  525. callback(error);
  526. return;
  527. }
  528. self->_tokenService = tokenService;
  529. if (![self updateKeychain:&error]) {
  530. callback(error);
  531. return;
  532. }
  533. callback(nil);
  534. }];
  535. }
  536. #pragma mark -
  537. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  538. - (void)startPasskeyEnrollmentWithName:(nullable NSString *)name
  539. completion:
  540. (nullable void (^)(
  541. ASAuthorizationPlatformPublicKeyCredentialRegistrationRequest
  542. *_Nullable request,
  543. NSError *_Nullable error))completion {
  544. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  545. FIRStartPasskeyEnrollmentRequest *request =
  546. [[FIRStartPasskeyEnrollmentRequest alloc] initWithIDToken:self.rawAccessToken
  547. requestConfiguration:requestConfiguration];
  548. [FIRAuthBackend
  549. startPasskeyEnrollment:request
  550. callback:^(FIRStartPasskeyEnrollmentResponse *_Nullable response,
  551. NSError *_Nullable error) {
  552. if (error) {
  553. completion(nil, error);
  554. return;
  555. } else {
  556. // cached the passkey name. This is needed when calling
  557. // finalizePasskeyEnrollment
  558. self.passkeyName = name;
  559. NSData *challengeInData =
  560. [[NSData alloc] initWithBase64EncodedString:response.challenge
  561. options:0];
  562. NSData *userIdInData =
  563. [[NSData alloc] initWithBase64EncodedString:response.userID options:0];
  564. ASAuthorizationPlatformPublicKeyCredentialProvider *provider =
  565. [[ASAuthorizationPlatformPublicKeyCredentialProvider alloc]
  566. initWithRelyingPartyIdentifier:response.rpID];
  567. ASAuthorizationPlatformPublicKeyCredentialRegistrationRequest *request =
  568. [provider
  569. createCredentialRegistrationRequestWithChallenge:challengeInData
  570. name:name
  571. userID:userIdInData];
  572. completion(request, nil);
  573. }
  574. }];
  575. }
  576. - (void)finalizePasskeyEnrollmentWithPlatformCredential:
  577. (ASAuthorizationPlatformPublicKeyCredentialRegistration *)platformCredential
  578. completion:(nullable void (^)(
  579. FIRAuthDataResult *_Nullable authResult,
  580. NSError *_Nullable error))completion {
  581. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  582. FIRAuthDataResultCallback decoratedCallback =
  583. [FIRAuth.auth signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  584. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  585. NSString *credentialID = [platformCredential.credentialID base64EncodedStringWithOptions:0];
  586. NSString *clientDataJson =
  587. [platformCredential.rawClientDataJSON base64EncodedStringWithOptions:0];
  588. NSString *attestationObject =
  589. [platformCredential.rawAttestationObject base64EncodedStringWithOptions:0];
  590. // If passkey name is not provided, we will provide a firebase formatted default name.
  591. if (self.passkeyName != nil || [self.passkeyName isEqual:@""]) {
  592. self.passkeyName = @"Unnamed account (Apple)";
  593. }
  594. FIRFinalizePasskeyEnrollmentRequest *request =
  595. [[FIRFinalizePasskeyEnrollmentRequest alloc] initWithIDToken:self.rawAccessToken
  596. name:self.passkeyName
  597. credentialID:credentialID
  598. clientDataJson:clientDataJson
  599. attestationObject:attestationObject
  600. requestConfiguration:requestConfiguration];
  601. [FIRAuthBackend
  602. finalizePasskeyEnrollment:request
  603. callback:^(FIRFinalizePasskeyEnrollmentResponse *_Nullable response,
  604. NSError *_Nullable error) {
  605. if (error) {
  606. decoratedCallback(nil, error);
  607. } else {
  608. [FIRAuth.auth
  609. completeSignInWithAccessToken:response.idToken
  610. accessTokenExpirationDate:nil
  611. refreshToken:response.refreshToken
  612. anonymous:NO
  613. callback:^(FIRUser *_Nullable user,
  614. NSError *_Nullable error) {
  615. if (error) {
  616. completion(nil, error);
  617. return;
  618. }
  619. FIRAuthDataResult *authDataResult =
  620. user ? [[FIRAuthDataResult alloc]
  621. initWithUser:user
  622. additionalUserInfo:nil]
  623. : nil;
  624. decoratedCallback(authDataResult, error);
  625. }];
  626. }
  627. }];
  628. });
  629. }
  630. #endif // #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  631. /** @fn updateEmail:password:callback:
  632. @brief Updates email address and/or password for the current user.
  633. @remarks May fail if there is already an email/password-based account for the same email
  634. address.
  635. @param email The email address for the user, if to be updated.
  636. @param password The new password for the user, if to be updated.
  637. @param callback The block called when the user profile change has finished. Invoked
  638. asynchronously on the auth global work queue in the future.
  639. @remarks May fail with a @c FIRAuthErrorCodeRequiresRecentLogin error code.
  640. Call @c reauthentateWithCredential:completion: beforehand to avoid this error case.
  641. */
  642. - (void)updateEmail:(nullable NSString *)email
  643. password:(nullable NSString *)password
  644. callback:(nonnull FIRUserProfileChangeCallback)callback {
  645. if (password && ![password length]) {
  646. callback([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]);
  647. return;
  648. }
  649. BOOL hadEmailPasswordCredential = _hasEmailPasswordCredential;
  650. [self
  651. executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  652. FIRSetAccountInfoRequest *request) {
  653. if (email) {
  654. request.email = email;
  655. }
  656. if (password) {
  657. request.password = password;
  658. }
  659. }
  660. callback:^(NSError *error) {
  661. if (error) {
  662. callback(error);
  663. return;
  664. }
  665. if (email) {
  666. self->_email = [email copy];
  667. }
  668. if (self->_email) {
  669. if (!hadEmailPasswordCredential) {
  670. // The list of providers need to be updated for the newly added email-password provider.
  671. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  672. NSError *_Nullable error) {
  673. if (error) {
  674. callback(error);
  675. return;
  676. }
  677. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  678. FIRGetAccountInfoRequest *getAccountInfoRequest =
  679. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  680. requestConfiguration:requestConfiguration];
  681. [FIRAuthBackend
  682. getAccountInfo:getAccountInfoRequest
  683. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  684. NSError *_Nullable error) {
  685. if (error) {
  686. [self signOutIfTokenIsInvalidWithError:error];
  687. callback(error);
  688. return;
  689. }
  690. for (FIRGetAccountInfoResponseUser *userAccountInfo in response.users) {
  691. // Set the account to non-anonymous if there are any providers, even if
  692. // they're not email/password ones.
  693. if (userAccountInfo.providerUserInfo.count > 0) {
  694. self.anonymous = NO;
  695. }
  696. for (FIRGetAccountInfoResponseProviderUserInfo
  697. *providerUserInfo in userAccountInfo.providerUserInfo) {
  698. if ([providerUserInfo.providerID
  699. isEqualToString:FIREmailAuthProviderID]) {
  700. self->_hasEmailPasswordCredential = YES;
  701. break;
  702. }
  703. }
  704. }
  705. [self updateWithGetAccountInfoResponse:response];
  706. if (![self updateKeychain:&error]) {
  707. callback(error);
  708. return;
  709. }
  710. callback(nil);
  711. }];
  712. }];
  713. return;
  714. }
  715. }
  716. if (![self updateKeychain:&error]) {
  717. callback(error);
  718. return;
  719. }
  720. callback(nil);
  721. }];
  722. }
  723. - (void)updateEmail:(NSString *)email completion:(nullable FIRUserProfileChangeCallback)completion {
  724. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  725. [self updateEmail:email
  726. password:nil
  727. callback:^(NSError *_Nullable error) {
  728. callInMainThreadWithError(completion, error);
  729. }];
  730. });
  731. }
  732. - (void)updatePassword:(NSString *)password
  733. completion:(nullable FIRUserProfileChangeCallback)completion {
  734. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  735. [self updateEmail:nil
  736. password:password
  737. callback:^(NSError *_Nullable error) {
  738. callInMainThreadWithError(completion, error);
  739. }];
  740. });
  741. }
  742. #if TARGET_OS_IOS
  743. /** @fn internalUpdateOrLinkPhoneNumberCredential:completion:
  744. @brief Updates the phone number for the user. On success, the cached user profile data is
  745. updated.
  746. @param phoneAuthCredential The new phone number credential corresponding to the phone number
  747. to be added to the Firebase account, if a phone number is already linked to the account this
  748. new phone number will replace it.
  749. @param isLinkOperation Boolean value indicating whether or not this is a link operation.
  750. @param completion Optionally; the block invoked when the user profile change has finished.
  751. Invoked asynchronously on the global work queue in the future.
  752. */
  753. - (void)internalUpdateOrLinkPhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential
  754. isLinkOperation:(BOOL)isLinkOperation
  755. completion:(FIRUserProfileChangeCallback)completion {
  756. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  757. if (error) {
  758. completion(error);
  759. return;
  760. }
  761. FIRAuthOperationType operation =
  762. isLinkOperation ? FIRAuthOperationTypeLink : FIRAuthOperationTypeUpdate;
  763. FIRVerifyPhoneNumberRequest *request = [[FIRVerifyPhoneNumberRequest alloc]
  764. initWithVerificationID:phoneAuthCredential.verificationID
  765. verificationCode:phoneAuthCredential.verificationCode
  766. operation:operation
  767. requestConfiguration:self->_auth.requestConfiguration];
  768. request.accessToken = accessToken;
  769. [FIRAuthBackend verifyPhoneNumber:request
  770. callback:^(FIRVerifyPhoneNumberResponse *_Nullable response,
  771. NSError *_Nullable error) {
  772. if (error) {
  773. [self signOutIfTokenIsInvalidWithError:error];
  774. completion(error);
  775. return;
  776. }
  777. FIRAuthRequestConfiguration *requestConfiguration =
  778. self.auth.requestConfiguration;
  779. // Update the new token and refresh user info again.
  780. self->_tokenService = [[FIRSecureTokenService alloc]
  781. initWithRequestConfiguration:requestConfiguration
  782. accessToken:response.IDToken
  783. accessTokenExpirationDate:response.approximateExpirationDate
  784. refreshToken:response.refreshToken];
  785. // Get account info to update cached user info.
  786. [self getAccountInfoRefreshingCache:^(
  787. FIRGetAccountInfoResponseUser *_Nullable user,
  788. NSError *_Nullable error) {
  789. if (error) {
  790. [self signOutIfTokenIsInvalidWithError:error];
  791. completion(error);
  792. return;
  793. }
  794. self.anonymous = NO;
  795. if (![self updateKeychain:&error]) {
  796. completion(error);
  797. return;
  798. }
  799. completion(nil);
  800. }];
  801. }];
  802. }];
  803. }
  804. - (void)updatePhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential
  805. completion:(nullable FIRUserProfileChangeCallback)completion {
  806. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  807. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  808. isLinkOperation:NO
  809. completion:^(NSError *_Nullable error) {
  810. callInMainThreadWithError(completion, error);
  811. }];
  812. });
  813. }
  814. #endif
  815. - (FIRUserProfileChangeRequest *)profileChangeRequest {
  816. __block FIRUserProfileChangeRequest *result;
  817. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  818. result = [[FIRUserProfileChangeRequest alloc] initWithUser:self];
  819. });
  820. return result;
  821. }
  822. - (void)setDisplayName:(NSString *)displayName {
  823. _displayName = [displayName copy];
  824. }
  825. - (void)setPhotoURL:(NSURL *)photoURL {
  826. _photoURL = [photoURL copy];
  827. }
  828. - (NSString *)rawAccessToken {
  829. return _tokenService.rawAccessToken;
  830. }
  831. - (NSDate *)accessTokenExpirationDate {
  832. return _tokenService.accessTokenExpirationDate;
  833. }
  834. #pragma mark -
  835. - (void)reloadWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  836. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  837. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  838. NSError *_Nullable error) {
  839. callInMainThreadWithError(completion, error);
  840. }];
  841. });
  842. }
  843. #pragma mark -
  844. - (void)reauthenticateWithCredential:(FIRAuthCredential *)credential
  845. completion:(nullable FIRAuthDataResultCallback)completion {
  846. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  847. [self->_auth
  848. internalSignInAndRetrieveDataWithCredential:credential
  849. isReauthentication:YES
  850. callback:^(FIRAuthDataResult *_Nullable authResult,
  851. NSError *_Nullable error) {
  852. if (error) {
  853. // If "user not found" error returned by backend,
  854. // translate to user mismatch error which is more
  855. // accurate.
  856. if (error.code == FIRAuthErrorCodeUserNotFound) {
  857. error = [FIRAuthErrorUtils userMismatchError];
  858. }
  859. callInMainThreadWithAuthDataResultAndError(
  860. completion, authResult, error);
  861. return;
  862. }
  863. if (![authResult.user.uid
  864. isEqual:[self->_auth getUserID]]) {
  865. callInMainThreadWithAuthDataResultAndError(
  866. completion, authResult,
  867. [FIRAuthErrorUtils userMismatchError]);
  868. return;
  869. }
  870. // Successful reauthenticate
  871. [self
  872. setTokenService:authResult.user->_tokenService
  873. callback:^(NSError *_Nullable error) {
  874. callInMainThreadWithAuthDataResultAndError(
  875. completion, authResult, error);
  876. }];
  877. }];
  878. });
  879. }
  880. - (void)reauthenticateWithProvider:(id<FIRFederatedAuthProvider>)provider
  881. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  882. completion:(nullable FIRAuthDataResultCallback)completion {
  883. #if TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  884. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  885. [provider getCredentialWithUIDelegate:UIDelegate
  886. completion:^(FIRAuthCredential *_Nullable credential,
  887. NSError *_Nullable error) {
  888. if (error) {
  889. completion(nil, error);
  890. return;
  891. }
  892. [self reauthenticateWithCredential:credential
  893. completion:completion];
  894. }];
  895. });
  896. #endif // TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  897. }
  898. - (nullable NSString *)refreshToken {
  899. __block NSString *result;
  900. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  901. result = self->_tokenService.refreshToken;
  902. });
  903. return result;
  904. }
  905. - (void)getIDTokenWithCompletion:(nullable FIRAuthTokenCallback)completion {
  906. // |getIDTokenForcingRefresh:completion:| is also a public API so there is no need to dispatch to
  907. // global work queue here.
  908. [self getIDTokenForcingRefresh:NO completion:completion];
  909. }
  910. - (void)getIDTokenForcingRefresh:(BOOL)forceRefresh
  911. completion:(nullable FIRAuthTokenCallback)completion {
  912. [self getIDTokenResultForcingRefresh:forceRefresh
  913. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  914. NSError *_Nullable error) {
  915. if (completion) {
  916. dispatch_async(dispatch_get_main_queue(), ^{
  917. completion(tokenResult.token, error);
  918. });
  919. }
  920. }];
  921. }
  922. - (void)getIDTokenResultWithCompletion:(nullable FIRAuthTokenResultCallback)completion {
  923. [self getIDTokenResultForcingRefresh:NO
  924. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  925. NSError *_Nullable error) {
  926. if (completion) {
  927. dispatch_async(dispatch_get_main_queue(), ^{
  928. completion(tokenResult, error);
  929. });
  930. }
  931. }];
  932. }
  933. - (void)getIDTokenResultForcingRefresh:(BOOL)forceRefresh
  934. completion:(nullable FIRAuthTokenResultCallback)completion {
  935. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  936. [self
  937. internalGetTokenForcingRefresh:forceRefresh
  938. callback:^(NSString *_Nullable token, NSError *_Nullable error) {
  939. FIRAuthTokenResult *tokenResult;
  940. if (token) {
  941. tokenResult = [FIRAuthTokenResult tokenResultWithToken:token];
  942. FIRLogDebug(kFIRLoggerAuth, @"I-AUT000017",
  943. @"Actual token expiration date: %@, current date: %@",
  944. tokenResult.expirationDate, [NSDate date]);
  945. }
  946. if (completion) {
  947. dispatch_async(dispatch_get_main_queue(), ^{
  948. completion(tokenResult, error);
  949. });
  950. }
  951. }];
  952. });
  953. }
  954. /** @fn parseIDToken:error:
  955. @brief Parses the provided IDToken and returns an instance of FIRAuthTokenResult containing
  956. claims obtained from the IDToken.
  957. @param token The raw text of the Firebase IDToken encoded in base64.
  958. @param error An out parameter which would contain any error that occurs during parsing.
  959. @return An instance of FIRAuthTokenResult containing claims obtained from the IDToken.
  960. @remarks IDToken returned from the backend in some cases is of a length that is not a multiple
  961. of 4. In these cases this function pads the token with as many "=" characters as needed and
  962. then attempts to parse the token. If the token cannot be parsed an error is returned via the
  963. "error" out parameter.
  964. */
  965. - (nullable FIRAuthTokenResult *)parseIDToken:(NSString *)token error:(NSError **)error {
  966. // Though this is an internal method, errors returned here are surfaced in user-visible
  967. // callbacks.
  968. if (error) {
  969. *error = nil;
  970. }
  971. NSArray *tokenStringArray = [token componentsSeparatedByString:@"."];
  972. // The JWT should have three parts, though we only use the second in this method.
  973. if (tokenStringArray.count != 3) {
  974. if (error) {
  975. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil];
  976. }
  977. return nil;
  978. }
  979. // The token payload is always the second index of the array.
  980. NSString *IDToken = tokenStringArray[1];
  981. // Convert the base64URL encoded string to a base64 encoded string.
  982. // Replace "_" with "/"
  983. NSMutableString *tokenPayload = [[IDToken stringByReplacingOccurrencesOfString:@"_"
  984. withString:@"/"] mutableCopy];
  985. // Replace "-" with "+"
  986. [tokenPayload replaceOccurrencesOfString:@"-"
  987. withString:@"+"
  988. options:kNilOptions
  989. range:NSMakeRange(0, tokenPayload.length)];
  990. // Pad the token payload with "=" signs if the payload's length is not a multiple of 4.
  991. while ((tokenPayload.length % 4) != 0) {
  992. [tokenPayload appendFormat:@"="];
  993. }
  994. NSData *decodedTokenPayloadData =
  995. [[NSData alloc] initWithBase64EncodedString:tokenPayload
  996. options:NSDataBase64DecodingIgnoreUnknownCharacters];
  997. if (!decodedTokenPayloadData) {
  998. if (error) {
  999. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil];
  1000. }
  1001. return nil;
  1002. }
  1003. NSError *jsonError = nil;
  1004. NSJSONReadingOptions options = NSJSONReadingMutableContainers | NSJSONReadingAllowFragments;
  1005. NSDictionary *tokenPayloadDictionary =
  1006. [NSJSONSerialization JSONObjectWithData:decodedTokenPayloadData
  1007. options:options
  1008. error:&jsonError];
  1009. if (jsonError != nil) {
  1010. if (error) {
  1011. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:jsonError];
  1012. }
  1013. return nil;
  1014. }
  1015. if (!tokenPayloadDictionary) {
  1016. if (error) {
  1017. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil];
  1018. }
  1019. return nil;
  1020. }
  1021. FIRAuthTokenResult *result = [FIRAuthTokenResult tokenResultWithToken:token];
  1022. return result;
  1023. }
  1024. /** @fn internalGetTokenForcingRefresh:callback:
  1025. @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1026. @param callback The block to invoke when the token is available. Invoked asynchronously on the
  1027. global work thread in the future.
  1028. */
  1029. - (void)internalGetTokenWithCallback:(nonnull FIRAuthTokenCallback)callback {
  1030. [self internalGetTokenForcingRefresh:NO callback:callback];
  1031. }
  1032. - (void)internalGetTokenForcingRefresh:(BOOL)forceRefresh
  1033. callback:(nonnull FIRAuthTokenCallback)callback {
  1034. [_tokenService fetchAccessTokenForcingRefresh:forceRefresh
  1035. callback:^(NSString *_Nullable token,
  1036. NSError *_Nullable error, BOOL tokenUpdated) {
  1037. if (error) {
  1038. [self signOutIfTokenIsInvalidWithError:error];
  1039. callback(nil, error);
  1040. return;
  1041. }
  1042. if (tokenUpdated) {
  1043. if (![self updateKeychain:&error]) {
  1044. callback(nil, error);
  1045. return;
  1046. }
  1047. }
  1048. callback(token, nil);
  1049. }];
  1050. }
  1051. - (void)sendEmailVerificationBeforeUpdatingEmail:(nonnull NSString *)email
  1052. completion:(nullable FIRAuthVoidErrorCallback)completion {
  1053. [self internalVerifyBeforeUpdateEmailWithNewEmail:email
  1054. actionCodeSettings:nil
  1055. completion:completion];
  1056. }
  1057. - (void)sendEmailVerificationBeforeUpdatingEmail:(nonnull NSString *)email
  1058. actionCodeSettings:(nonnull FIRActionCodeSettings *)actionCodeSettings
  1059. completion:(nullable FIRAuthVoidErrorCallback)completion {
  1060. [self internalVerifyBeforeUpdateEmailWithNewEmail:email
  1061. actionCodeSettings:actionCodeSettings
  1062. completion:completion];
  1063. }
  1064. - (void)internalVerifyBeforeUpdateEmailWithNewEmail:(NSString *)newEmail
  1065. actionCodeSettings:
  1066. (nullable FIRActionCodeSettings *)actionCodeSettings
  1067. completion:(FIRVerifyBeforeUpdateEmailCallback)completion {
  1068. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1069. [self
  1070. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1071. if (error) {
  1072. callInMainThreadWithError(completion, error);
  1073. return;
  1074. }
  1075. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  1076. FIRActionCodeSettings *settings = actionCodeSettings;
  1077. FIRGetOOBConfirmationCodeRequest *request = [FIRGetOOBConfirmationCodeRequest
  1078. verifyBeforeUpdateEmailWithAccessToken:accessToken
  1079. newEmail:newEmail
  1080. actionCodeSettings:settings
  1081. requestConfiguration:configuration];
  1082. [FIRAuthBackend
  1083. getOOBConfirmationCode:request
  1084. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1085. NSError *_Nullable error) {
  1086. callInMainThreadWithError(completion, error);
  1087. }];
  1088. }];
  1089. });
  1090. }
  1091. - (void)linkWithEmailPassword:(FIREmailPasswordAuthCredential *)credential
  1092. authResult:(FIRAuthDataResult *)authResult
  1093. completion:(nullable FIRAuthDataResultCallback)completion {
  1094. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1095. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  1096. FIRSignUpNewUserRequest *request =
  1097. [[FIRSignUpNewUserRequest alloc] initWithEmail:credential.email
  1098. password:credential.password
  1099. displayName:nil
  1100. idToken:accessToken
  1101. requestConfiguration:requestConfiguration];
  1102. FIRSignupNewUserCallback signUpNewUserCallback = ^(FIRSignUpNewUserResponse *_Nullable response,
  1103. NSError *_Nullable error) {
  1104. if (error) {
  1105. [self signOutIfTokenIsInvalidWithError:error];
  1106. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1107. } else {
  1108. // Update the new token and refresh user info again.
  1109. self->_tokenService = [[FIRSecureTokenService alloc]
  1110. initWithRequestConfiguration:requestConfiguration
  1111. accessToken:response.IDToken
  1112. accessTokenExpirationDate:response.approximateExpirationDate
  1113. refreshToken:response.refreshToken];
  1114. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1115. NSError *_Nullable error) {
  1116. if (error) {
  1117. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1118. return;
  1119. }
  1120. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1121. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  1122. requestConfiguration:requestConfiguration];
  1123. [FIRAuthBackend
  1124. getAccountInfo:getAccountInfoRequest
  1125. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1126. NSError *_Nullable error) {
  1127. if (error) {
  1128. [self signOutIfTokenIsInvalidWithError:error];
  1129. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1130. return;
  1131. }
  1132. self.anonymous = NO;
  1133. [self updateWithGetAccountInfoResponse:response];
  1134. NSError *keychainError;
  1135. if (![self updateKeychain:&keychainError]) {
  1136. callInMainThreadWithAuthDataResultAndError(completion, nil, keychainError);
  1137. return;
  1138. }
  1139. callInMainThreadWithAuthDataResultAndError(completion, authResult, nil);
  1140. }];
  1141. }];
  1142. }
  1143. };
  1144. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  1145. if ([[FIRAuthRecaptchaVerifier sharedRecaptchaVerifier:self.auth]
  1146. enablementStatusForProvider:FIRAuthRecaptchaProviderPassword]) {
  1147. [[FIRAuthRecaptchaVerifier sharedRecaptchaVerifier:self.auth]
  1148. injectRecaptchaFields:request
  1149. provider:FIRAuthRecaptchaProviderPassword
  1150. action:FIRAuthRecaptchaActionSignUpPassword
  1151. completion:^(
  1152. FIRIdentityToolkitRequest<FIRAuthRPCRequest> *requestWithRecaptchaToken) {
  1153. [FIRAuthBackend
  1154. signUpNewUser:(FIRSignUpNewUserRequest *)requestWithRecaptchaToken
  1155. callback:signUpNewUserCallback];
  1156. }];
  1157. } else {
  1158. [FIRAuthBackend
  1159. signUpNewUser:request
  1160. callback:^(FIRSignUpNewUserResponse *_Nullable response, NSError *_Nullable error) {
  1161. if (!error) {
  1162. signUpNewUserCallback(response, nil);
  1163. return;
  1164. }
  1165. NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey];
  1166. if (error.code == FIRAuthErrorCodeInternalError &&
  1167. [[underlyingError.userInfo
  1168. objectForKey:FIRAuthErrorUserInfoDeserializedResponseKey][@"message"]
  1169. hasPrefix:kMissingRecaptchaTokenErrorPrefix]) {
  1170. [[FIRAuthRecaptchaVerifier sharedRecaptchaVerifier:self.auth]
  1171. injectRecaptchaFields:request
  1172. provider:FIRAuthRecaptchaProviderPassword
  1173. action:FIRAuthRecaptchaActionSignUpPassword
  1174. completion:^(FIRIdentityToolkitRequest<FIRAuthRPCRequest>
  1175. *requestWithRecaptchaToken) {
  1176. [FIRAuthBackend signUpNewUser:(FIRSignUpNewUserRequest *)
  1177. requestWithRecaptchaToken
  1178. callback:signUpNewUserCallback];
  1179. }];
  1180. } else {
  1181. signUpNewUserCallback(nil, error);
  1182. }
  1183. }];
  1184. }
  1185. #else
  1186. [FIRAuthBackend signUpNewUser:request callback:signUpNewUserCallback];
  1187. #endif
  1188. }];
  1189. }
  1190. - (void)linkWithCredential:(FIRAuthCredential *)credential
  1191. completion:(nullable FIRAuthDataResultCallback)completion {
  1192. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1193. if (self->_providerData[credential.provider]) {
  1194. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1195. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  1196. return;
  1197. }
  1198. FIRAuthDataResult *result = [[FIRAuthDataResult alloc] initWithUser:self
  1199. additionalUserInfo:nil];
  1200. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  1201. if (self->_hasEmailPasswordCredential) {
  1202. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1203. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  1204. return;
  1205. }
  1206. FIREmailPasswordAuthCredential *emailPasswordCredential =
  1207. (FIREmailPasswordAuthCredential *)credential;
  1208. if (emailPasswordCredential.password) {
  1209. [self linkWithEmailPassword:emailPasswordCredential
  1210. authResult:result
  1211. completion:completion];
  1212. } else {
  1213. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1214. NSError *_Nullable error) {
  1215. NSDictionary<NSString *, NSString *> *queryItems =
  1216. [FIRAuthWebUtils parseURL:emailPasswordCredential.link];
  1217. if (![queryItems count]) {
  1218. NSURLComponents *urlComponents =
  1219. [NSURLComponents componentsWithString:emailPasswordCredential.link];
  1220. queryItems = [FIRAuthWebUtils parseURL:urlComponents.query];
  1221. }
  1222. NSString *actionCode = queryItems[@"oobCode"];
  1223. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  1224. FIREmailLinkSignInRequest *request =
  1225. [[FIREmailLinkSignInRequest alloc] initWithEmail:emailPasswordCredential.email
  1226. oobCode:actionCode
  1227. requestConfiguration:requestConfiguration];
  1228. request.IDToken = accessToken;
  1229. [FIRAuthBackend
  1230. emailLinkSignin:request
  1231. callback:^(FIREmailLinkSignInResponse *_Nullable response,
  1232. NSError *_Nullable error) {
  1233. if (error) {
  1234. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1235. } else {
  1236. // Update the new token and refresh user info again.
  1237. self->_tokenService = [[FIRSecureTokenService alloc]
  1238. initWithRequestConfiguration:requestConfiguration
  1239. accessToken:response.IDToken
  1240. accessTokenExpirationDate:response.approximateExpirationDate
  1241. refreshToken:response.refreshToken];
  1242. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1243. NSError *_Nullable error) {
  1244. if (error) {
  1245. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1246. return;
  1247. }
  1248. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1249. [[FIRGetAccountInfoRequest alloc]
  1250. initWithAccessToken:accessToken
  1251. requestConfiguration:requestConfiguration];
  1252. [FIRAuthBackend
  1253. getAccountInfo:getAccountInfoRequest
  1254. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1255. NSError *_Nullable error) {
  1256. if (error) {
  1257. [self signOutIfTokenIsInvalidWithError:error];
  1258. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1259. error);
  1260. return;
  1261. }
  1262. self.anonymous = NO;
  1263. [self updateWithGetAccountInfoResponse:response];
  1264. if (![self updateKeychain:&error]) {
  1265. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1266. error);
  1267. return;
  1268. }
  1269. callInMainThreadWithAuthDataResultAndError(completion,
  1270. result, nil);
  1271. }];
  1272. }];
  1273. }
  1274. }];
  1275. }];
  1276. }
  1277. return;
  1278. }
  1279. if ([credential isKindOfClass:[FIRGameCenterAuthCredential class]]) {
  1280. FIRGameCenterAuthCredential *gameCenterCredential = (FIRGameCenterAuthCredential *)credential;
  1281. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1282. NSError *_Nullable error) {
  1283. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  1284. FIRSignInWithGameCenterRequest *gameCenterRequest = [[FIRSignInWithGameCenterRequest alloc]
  1285. initWithPlayerID:gameCenterCredential.playerID
  1286. teamPlayerID:gameCenterCredential.teamPlayerID
  1287. gamePlayerID:gameCenterCredential.gamePlayerID
  1288. publicKeyURL:gameCenterCredential.publicKeyURL
  1289. signature:gameCenterCredential.signature
  1290. salt:gameCenterCredential.salt
  1291. timestamp:gameCenterCredential.timestamp
  1292. displayName:gameCenterCredential.displayName
  1293. requestConfiguration:requestConfiguration];
  1294. gameCenterRequest.accessToken = accessToken;
  1295. [FIRAuthBackend
  1296. signInWithGameCenter:gameCenterRequest
  1297. callback:^(FIRSignInWithGameCenterResponse *_Nullable response,
  1298. NSError *_Nullable error) {
  1299. if (error) {
  1300. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1301. } else {
  1302. // Update the new token and refresh user info again.
  1303. self->_tokenService = [[FIRSecureTokenService alloc]
  1304. initWithRequestConfiguration:requestConfiguration
  1305. accessToken:response.IDToken
  1306. accessTokenExpirationDate:response.approximateExpirationDate
  1307. refreshToken:response.refreshToken];
  1308. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1309. NSError *_Nullable error) {
  1310. if (error) {
  1311. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1312. return;
  1313. }
  1314. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1315. [[FIRGetAccountInfoRequest alloc]
  1316. initWithAccessToken:accessToken
  1317. requestConfiguration:requestConfiguration];
  1318. [FIRAuthBackend
  1319. getAccountInfo:getAccountInfoRequest
  1320. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1321. NSError *_Nullable error) {
  1322. if (error) {
  1323. [self signOutIfTokenIsInvalidWithError:error];
  1324. callInMainThreadWithAuthDataResultAndError(completion,
  1325. nil, error);
  1326. return;
  1327. }
  1328. self.anonymous = NO;
  1329. [self updateWithGetAccountInfoResponse:response];
  1330. if (![self updateKeychain:&error]) {
  1331. callInMainThreadWithAuthDataResultAndError(completion,
  1332. nil, error);
  1333. return;
  1334. }
  1335. callInMainThreadWithAuthDataResultAndError(completion,
  1336. result, nil);
  1337. }];
  1338. }];
  1339. }
  1340. }];
  1341. }];
  1342. return;
  1343. }
  1344. #if TARGET_OS_IOS
  1345. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  1346. FIRPhoneAuthCredential *phoneAuthCredential = (FIRPhoneAuthCredential *)credential;
  1347. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  1348. isLinkOperation:YES
  1349. completion:^(NSError *_Nullable error) {
  1350. if (error) {
  1351. callInMainThreadWithAuthDataResultAndError(
  1352. completion, nil, error);
  1353. } else {
  1354. callInMainThreadWithAuthDataResultAndError(
  1355. completion, result, nil);
  1356. }
  1357. }];
  1358. return;
  1359. }
  1360. #endif
  1361. [self->_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  1362. CallbackWithAuthDataResultAndError completeWithError =
  1363. ^(FIRAuthDataResult *result, NSError *error) {
  1364. complete();
  1365. callInMainThreadWithAuthDataResultAndError(completion, result, error);
  1366. };
  1367. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1368. NSError *_Nullable error) {
  1369. if (error) {
  1370. completeWithError(nil, error);
  1371. return;
  1372. }
  1373. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  1374. FIRVerifyAssertionRequest *request =
  1375. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  1376. requestConfiguration:requestConfiguration];
  1377. [credential prepareVerifyAssertionRequest:request];
  1378. request.accessToken = accessToken;
  1379. [FIRAuthBackend
  1380. verifyAssertion:request
  1381. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  1382. if (error) {
  1383. [self signOutIfTokenIsInvalidWithError:error];
  1384. completeWithError(nil, error);
  1385. return;
  1386. }
  1387. FIRAdditionalUserInfo *additionalUserInfo =
  1388. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  1389. FIROAuthCredential *updatedOAuthCredential =
  1390. [[FIROAuthCredential alloc] initWithVerifyAssertionResponse:response];
  1391. FIRAuthDataResult *result =
  1392. [[FIRAuthDataResult alloc] initWithUser:self
  1393. additionalUserInfo:additionalUserInfo
  1394. credential:updatedOAuthCredential];
  1395. // Update the new token and refresh user info again.
  1396. self->_tokenService = [[FIRSecureTokenService alloc]
  1397. initWithRequestConfiguration:requestConfiguration
  1398. accessToken:response.IDToken
  1399. accessTokenExpirationDate:response.approximateExpirationDate
  1400. refreshToken:response.refreshToken];
  1401. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1402. NSError *_Nullable error) {
  1403. if (error) {
  1404. completeWithError(nil, error);
  1405. return;
  1406. }
  1407. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1408. [[FIRGetAccountInfoRequest alloc]
  1409. initWithAccessToken:accessToken
  1410. requestConfiguration:requestConfiguration];
  1411. [FIRAuthBackend
  1412. getAccountInfo:getAccountInfoRequest
  1413. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1414. NSError *_Nullable error) {
  1415. if (error) {
  1416. [self signOutIfTokenIsInvalidWithError:error];
  1417. completeWithError(nil, error);
  1418. return;
  1419. }
  1420. self.anonymous = NO;
  1421. [self updateWithGetAccountInfoResponse:response];
  1422. if (![self updateKeychain:&error]) {
  1423. completeWithError(nil, error);
  1424. return;
  1425. }
  1426. completeWithError(result, nil);
  1427. }];
  1428. }];
  1429. }];
  1430. }];
  1431. }];
  1432. });
  1433. }
  1434. - (void)linkWithProvider:(id<FIRFederatedAuthProvider>)provider
  1435. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  1436. completion:(nullable FIRAuthDataResultCallback)completion {
  1437. #if TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  1438. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1439. [provider getCredentialWithUIDelegate:UIDelegate
  1440. completion:^(FIRAuthCredential *_Nullable credential,
  1441. NSError *_Nullable error) {
  1442. if (error) {
  1443. completion(nil, error);
  1444. return;
  1445. }
  1446. [self linkWithCredential:credential completion:completion];
  1447. }];
  1448. });
  1449. #endif // TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  1450. }
  1451. - (void)unlinkFromProvider:(NSString *)provider
  1452. completion:(nullable FIRAuthResultCallback)completion {
  1453. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  1454. CallbackWithError completeAndCallbackWithError = ^(NSError *error) {
  1455. complete();
  1456. callInMainThreadWithUserAndError(completion, self, error);
  1457. };
  1458. [self
  1459. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1460. if (error) {
  1461. completeAndCallbackWithError(error);
  1462. return;
  1463. }
  1464. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  1465. FIRSetAccountInfoRequest *setAccountInfoRequest =
  1466. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:requestConfiguration];
  1467. setAccountInfoRequest.accessToken = accessToken;
  1468. if (!self->_providerData[provider]) {
  1469. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  1470. return;
  1471. }
  1472. setAccountInfoRequest.deleteProviders = @[ provider ];
  1473. [FIRAuthBackend
  1474. setAccountInfo:setAccountInfoRequest
  1475. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  1476. NSError *_Nullable error) {
  1477. if (error) {
  1478. [self signOutIfTokenIsInvalidWithError:error];
  1479. completeAndCallbackWithError(error);
  1480. return;
  1481. }
  1482. // We can't just use the provider info objects in FIRSetAccountInfoResponse
  1483. // because they don't have localID and email fields. Remove the specific
  1484. // provider manually.
  1485. NSMutableDictionary *mutableProviderData = [self->_providerData mutableCopy];
  1486. [mutableProviderData removeObjectForKey:provider];
  1487. self->_providerData = [mutableProviderData copy];
  1488. if ([provider isEqualToString:FIREmailAuthProviderID]) {
  1489. self->_hasEmailPasswordCredential = NO;
  1490. }
  1491. #if TARGET_OS_IOS
  1492. // After successfully unlinking a phone auth provider, remove the phone number
  1493. // from the cached user info.
  1494. if ([provider isEqualToString:FIRPhoneAuthProviderID]) {
  1495. self->_phoneNumber = nil;
  1496. }
  1497. #endif
  1498. if (response.IDToken && response.refreshToken) {
  1499. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  1500. initWithRequestConfiguration:requestConfiguration
  1501. accessToken:response.IDToken
  1502. accessTokenExpirationDate:response.approximateExpirationDate
  1503. refreshToken:response.refreshToken];
  1504. [self setTokenService:tokenService
  1505. callback:^(NSError *_Nullable error) {
  1506. completeAndCallbackWithError(error);
  1507. }];
  1508. return;
  1509. }
  1510. if (![self updateKeychain:&error]) {
  1511. completeAndCallbackWithError(error);
  1512. return;
  1513. }
  1514. completeAndCallbackWithError(nil);
  1515. }];
  1516. }];
  1517. }];
  1518. }
  1519. - (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion {
  1520. [self sendEmailVerificationWithNullableActionCodeSettings:nil completion:completion];
  1521. }
  1522. - (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1523. completion:
  1524. (nullable FIRSendEmailVerificationCallback)completion {
  1525. [self sendEmailVerificationWithNullableActionCodeSettings:actionCodeSettings
  1526. completion:completion];
  1527. }
  1528. /** @fn sendEmailVerificationWithNullableActionCodeSettings:completion:
  1529. @brief Initiates email verification for the user.
  1530. @param actionCodeSettings Optionally, a @c FIRActionCodeSettings object containing settings
  1531. related to the handling action codes.
  1532. */
  1533. - (void)sendEmailVerificationWithNullableActionCodeSettings:
  1534. (nullable FIRActionCodeSettings *)actionCodeSettings
  1535. completion:
  1536. (nullable FIRSendEmailVerificationCallback)
  1537. completion {
  1538. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1539. [self
  1540. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1541. if (error) {
  1542. callInMainThreadWithError(completion, error);
  1543. return;
  1544. }
  1545. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  1546. FIRGetOOBConfirmationCodeRequest *request =
  1547. [FIRGetOOBConfirmationCodeRequest verifyEmailRequestWithAccessToken:accessToken
  1548. actionCodeSettings:actionCodeSettings
  1549. requestConfiguration:configuration];
  1550. [FIRAuthBackend
  1551. getOOBConfirmationCode:request
  1552. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1553. NSError *_Nullable error) {
  1554. [self signOutIfTokenIsInvalidWithError:error];
  1555. callInMainThreadWithError(completion, error);
  1556. }];
  1557. }];
  1558. });
  1559. }
  1560. - (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1561. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1562. [self
  1563. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1564. if (error) {
  1565. callInMainThreadWithError(completion, error);
  1566. return;
  1567. }
  1568. FIRDeleteAccountRequest *deleteUserRequest =
  1569. [[FIRDeleteAccountRequest alloc] initWitLocalID:self->_userID
  1570. accessToken:accessToken
  1571. requestConfiguration:self->_auth.requestConfiguration];
  1572. [FIRAuthBackend deleteAccount:deleteUserRequest
  1573. callback:^(NSError *_Nullable error) {
  1574. if (error) {
  1575. callInMainThreadWithError(completion, error);
  1576. return;
  1577. }
  1578. if (![self->_auth signOutByForceWithUserID:self->_userID
  1579. error:&error]) {
  1580. callInMainThreadWithError(completion, error);
  1581. return;
  1582. }
  1583. callInMainThreadWithError(completion, error);
  1584. }];
  1585. }];
  1586. });
  1587. }
  1588. /** @fn signOutIfTokenIsInvalidWithError:
  1589. @brief Signs out this user if the user or the token is invalid.
  1590. @param error The error from the server.
  1591. */
  1592. - (void)signOutIfTokenIsInvalidWithError:(nullable NSError *)error {
  1593. NSInteger errorCode = error.code;
  1594. if (errorCode == FIRAuthErrorCodeUserNotFound || errorCode == FIRAuthErrorCodeUserDisabled ||
  1595. errorCode == FIRAuthErrorCodeInvalidUserToken ||
  1596. errorCode == FIRAuthErrorCodeUserTokenExpired) {
  1597. FIRLogNotice(kFIRLoggerAuth, @"I-AUT000016",
  1598. @"Invalid user token detected, user is automatically signed out.");
  1599. [_auth signOutByForceWithUserID:_userID error:NULL];
  1600. }
  1601. }
  1602. @end
  1603. @implementation FIRUserProfileChangeRequest {
  1604. /** @var _user
  1605. @brief The user associated with the change request.
  1606. */
  1607. FIRUser *_user;
  1608. /** @var _displayName
  1609. @brief The display name value to set if @c _displayNameSet is YES.
  1610. */
  1611. NSString *_displayName;
  1612. /** @var _displayNameSet
  1613. @brief Indicates the display name should be part of the change request.
  1614. */
  1615. BOOL _displayNameSet;
  1616. /** @var _photoURL
  1617. @brief The photo URL value to set if @c _displayNameSet is YES.
  1618. */
  1619. NSURL *_photoURL;
  1620. /** @var _photoURLSet
  1621. @brief Indicates the photo URL should be part of the change request.
  1622. */
  1623. BOOL _photoURLSet;
  1624. /** @var _consumed
  1625. @brief Indicates the @c commitChangesWithCallback: method has already been invoked.
  1626. */
  1627. BOOL _consumed;
  1628. }
  1629. - (nullable instancetype)initWithUser:(FIRUser *)user {
  1630. self = [super init];
  1631. if (self) {
  1632. _user = user;
  1633. }
  1634. return self;
  1635. }
  1636. - (nullable NSString *)displayName {
  1637. return _displayName;
  1638. }
  1639. - (void)setDisplayName:(nullable NSString *)displayName {
  1640. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1641. if (self->_consumed) {
  1642. [NSException
  1643. raise:NSInternalInconsistencyException
  1644. format:@"%@", @"Invalid call to setDisplayName: after commitChangesWithCallback:."];
  1645. return;
  1646. }
  1647. self->_displayNameSet = YES;
  1648. self->_displayName = [displayName copy];
  1649. });
  1650. }
  1651. - (nullable NSURL *)photoURL {
  1652. return _photoURL;
  1653. }
  1654. - (void)setPhotoURL:(nullable NSURL *)photoURL {
  1655. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1656. if (self->_consumed) {
  1657. [NSException raise:NSInternalInconsistencyException
  1658. format:@"%@", @"Invalid call to setPhotoURL: after commitChangesWithCallback:."];
  1659. return;
  1660. }
  1661. self->_photoURLSet = YES;
  1662. self->_photoURL = [photoURL copy];
  1663. });
  1664. }
  1665. /** @fn hasUpdates
  1666. @brief Indicates at least one field has a value which needs to be committed.
  1667. */
  1668. - (BOOL)hasUpdates {
  1669. return _displayNameSet || _photoURLSet;
  1670. }
  1671. - (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1672. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1673. if (self->_consumed) {
  1674. [NSException raise:NSInternalInconsistencyException
  1675. format:@"%@", @"commitChangesWithCallback: should only be called once."];
  1676. return;
  1677. }
  1678. self->_consumed = YES;
  1679. // Return fast if there is nothing to update:
  1680. if (![self hasUpdates]) {
  1681. callInMainThreadWithError(completion, nil);
  1682. return;
  1683. }
  1684. NSString *displayName = [self->_displayName copy];
  1685. BOOL displayNameWasSet = self->_displayNameSet;
  1686. NSURL *photoURL = [self->_photoURL copy];
  1687. BOOL photoURLWasSet = self->_photoURLSet;
  1688. [self->_user
  1689. executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  1690. FIRSetAccountInfoRequest *request) {
  1691. if (photoURLWasSet) {
  1692. request.photoURL = photoURL;
  1693. }
  1694. if (displayNameWasSet) {
  1695. request.displayName = displayName;
  1696. }
  1697. }
  1698. callback:^(NSError *_Nullable error) {
  1699. if (error) {
  1700. callInMainThreadWithError(completion, error);
  1701. return;
  1702. }
  1703. if (displayNameWasSet) {
  1704. [self->_user setDisplayName:displayName];
  1705. }
  1706. if (photoURLWasSet) {
  1707. [self->_user setPhotoURL:photoURL];
  1708. }
  1709. if (![self->_user updateKeychain:&error]) {
  1710. callInMainThreadWithError(completion, error);
  1711. return;
  1712. }
  1713. callInMainThreadWithError(completion, nil);
  1714. }];
  1715. });
  1716. }
  1717. @end
  1718. NS_ASSUME_NONNULL_END