FIRUser.m 74 KB

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