FIRUser.m 80 KB

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