FIRUser.m 75 KB

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