FIRUser.m 74 KB

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