FIRUser.m 72 KB

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