FIRUser.m 74 KB

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