FIRUser.m 84 KB

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