FIRUser.m 81 KB

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