FIRUser.m 73 KB

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