FIRUser.m 75 KB

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