FIRUser.m 75 KB

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