FIRUser.m 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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. callInMainThreadWithAuthDataResultAndError(completion, authResult, nil);
  1039. }];
  1040. }];
  1041. }
  1042. };
  1043. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  1044. if ([[FIRAuthRecaptchaVerifier sharedRecaptchaVerifier:self.auth]
  1045. enablementStatusForProvider:FIRAuthRecaptchaProviderPassword]) {
  1046. [[FIRAuthRecaptchaVerifier sharedRecaptchaVerifier:self.auth]
  1047. injectRecaptchaFields:request
  1048. provider:FIRAuthRecaptchaProviderPassword
  1049. action:FIRAuthRecaptchaActionSignUpPassword
  1050. completion:^(
  1051. FIRIdentityToolkitRequest<FIRAuthRPCRequest> *requestWithRecaptchaToken) {
  1052. [FIRAuthBackend
  1053. signUpNewUser:(FIRSignUpNewUserRequest *)requestWithRecaptchaToken
  1054. callback:signUpNewUserCallback];
  1055. }];
  1056. } else {
  1057. [FIRAuthBackend
  1058. signUpNewUser:request
  1059. callback:^(FIRSignUpNewUserResponse *_Nullable response, NSError *_Nullable error) {
  1060. if (!error) {
  1061. signUpNewUserCallback(response, nil);
  1062. return;
  1063. }
  1064. NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey];
  1065. if (error.code == FIRAuthErrorCodeInternalError &&
  1066. [[underlyingError.userInfo
  1067. objectForKey:FIRAuthErrorUserInfoDeserializedResponseKey][@"message"]
  1068. hasPrefix:kMissingRecaptchaTokenErrorPrefix]) {
  1069. [[FIRAuthRecaptchaVerifier sharedRecaptchaVerifier:self.auth]
  1070. injectRecaptchaFields:request
  1071. provider:FIRAuthRecaptchaProviderPassword
  1072. action:FIRAuthRecaptchaActionSignUpPassword
  1073. completion:^(FIRIdentityToolkitRequest<FIRAuthRPCRequest>
  1074. *requestWithRecaptchaToken) {
  1075. [FIRAuthBackend signUpNewUser:(FIRSignUpNewUserRequest *)
  1076. requestWithRecaptchaToken
  1077. callback:signUpNewUserCallback];
  1078. }];
  1079. } else {
  1080. signUpNewUserCallback(nil, error);
  1081. }
  1082. }];
  1083. }
  1084. #else
  1085. [FIRAuthBackend signUpNewUser:request callback:signUpNewUserCallback];
  1086. #endif
  1087. }];
  1088. }
  1089. - (void)linkWithCredential:(FIRAuthCredential *)credential
  1090. completion:(nullable FIRAuthDataResultCallback)completion {
  1091. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1092. if (self->_providerData[credential.provider]) {
  1093. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1094. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  1095. return;
  1096. }
  1097. FIRAuthDataResult *result = [[FIRAuthDataResult alloc] initWithUser:self
  1098. additionalUserInfo:nil];
  1099. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  1100. if (self->_hasEmailPasswordCredential) {
  1101. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1102. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  1103. return;
  1104. }
  1105. FIREmailPasswordAuthCredential *emailPasswordCredential =
  1106. (FIREmailPasswordAuthCredential *)credential;
  1107. if (emailPasswordCredential.password) {
  1108. [self linkWithEmailPassword:emailPasswordCredential
  1109. authResult:result
  1110. completion:completion];
  1111. } else {
  1112. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1113. NSError *_Nullable error) {
  1114. NSDictionary<NSString *, NSString *> *queryItems =
  1115. [FIRAuthWebUtils parseURL:emailPasswordCredential.link];
  1116. if (![queryItems count]) {
  1117. NSURLComponents *urlComponents =
  1118. [NSURLComponents componentsWithString:emailPasswordCredential.link];
  1119. queryItems = [FIRAuthWebUtils parseURL:urlComponents.query];
  1120. }
  1121. NSString *actionCode = queryItems[@"oobCode"];
  1122. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  1123. FIREmailLinkSignInRequest *request =
  1124. [[FIREmailLinkSignInRequest alloc] initWithEmail:emailPasswordCredential.email
  1125. oobCode:actionCode
  1126. requestConfiguration:requestConfiguration];
  1127. request.IDToken = accessToken;
  1128. [FIRAuthBackend
  1129. emailLinkSignin:request
  1130. callback:^(FIREmailLinkSignInResponse *_Nullable response,
  1131. NSError *_Nullable error) {
  1132. if (error) {
  1133. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1134. } else {
  1135. // Update the new token and refresh user info again.
  1136. self->_tokenService = [[FIRSecureTokenService alloc]
  1137. initWithRequestConfiguration:requestConfiguration
  1138. accessToken:response.IDToken
  1139. accessTokenExpirationDate:response.approximateExpirationDate
  1140. refreshToken:response.refreshToken];
  1141. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1142. NSError *_Nullable error) {
  1143. if (error) {
  1144. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1145. return;
  1146. }
  1147. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1148. [[FIRGetAccountInfoRequest alloc]
  1149. initWithAccessToken:accessToken
  1150. requestConfiguration:requestConfiguration];
  1151. [FIRAuthBackend
  1152. getAccountInfo:getAccountInfoRequest
  1153. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1154. NSError *_Nullable error) {
  1155. if (error) {
  1156. [self signOutIfTokenIsInvalidWithError:error];
  1157. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1158. error);
  1159. return;
  1160. }
  1161. self.anonymous = NO;
  1162. [self updateWithGetAccountInfoResponse:response];
  1163. if (![self updateKeychain:&error]) {
  1164. callInMainThreadWithAuthDataResultAndError(completion, nil,
  1165. error);
  1166. return;
  1167. }
  1168. callInMainThreadWithAuthDataResultAndError(completion,
  1169. result, nil);
  1170. }];
  1171. }];
  1172. }
  1173. }];
  1174. }];
  1175. }
  1176. return;
  1177. }
  1178. if ([credential isKindOfClass:[FIRGameCenterAuthCredential class]]) {
  1179. FIRGameCenterAuthCredential *gameCenterCredential = (FIRGameCenterAuthCredential *)credential;
  1180. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1181. NSError *_Nullable error) {
  1182. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  1183. FIRSignInWithGameCenterRequest *gameCenterRequest = [[FIRSignInWithGameCenterRequest alloc]
  1184. initWithPlayerID:gameCenterCredential.playerID
  1185. teamPlayerID:gameCenterCredential.teamPlayerID
  1186. gamePlayerID:gameCenterCredential.gamePlayerID
  1187. publicKeyURL:gameCenterCredential.publicKeyURL
  1188. signature:gameCenterCredential.signature
  1189. salt:gameCenterCredential.salt
  1190. timestamp:gameCenterCredential.timestamp
  1191. displayName:gameCenterCredential.displayName
  1192. requestConfiguration:requestConfiguration];
  1193. gameCenterRequest.accessToken = accessToken;
  1194. [FIRAuthBackend
  1195. signInWithGameCenter:gameCenterRequest
  1196. callback:^(FIRSignInWithGameCenterResponse *_Nullable response,
  1197. NSError *_Nullable error) {
  1198. if (error) {
  1199. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1200. } else {
  1201. // Update the new token and refresh user info again.
  1202. self->_tokenService = [[FIRSecureTokenService alloc]
  1203. initWithRequestConfiguration:requestConfiguration
  1204. accessToken:response.IDToken
  1205. accessTokenExpirationDate:response.approximateExpirationDate
  1206. refreshToken:response.refreshToken];
  1207. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1208. NSError *_Nullable error) {
  1209. if (error) {
  1210. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1211. return;
  1212. }
  1213. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1214. [[FIRGetAccountInfoRequest alloc]
  1215. initWithAccessToken:accessToken
  1216. requestConfiguration:requestConfiguration];
  1217. [FIRAuthBackend
  1218. getAccountInfo:getAccountInfoRequest
  1219. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1220. NSError *_Nullable error) {
  1221. if (error) {
  1222. [self signOutIfTokenIsInvalidWithError:error];
  1223. callInMainThreadWithAuthDataResultAndError(completion,
  1224. nil, error);
  1225. return;
  1226. }
  1227. self.anonymous = NO;
  1228. [self updateWithGetAccountInfoResponse:response];
  1229. if (![self updateKeychain:&error]) {
  1230. callInMainThreadWithAuthDataResultAndError(completion,
  1231. nil, error);
  1232. return;
  1233. }
  1234. callInMainThreadWithAuthDataResultAndError(completion,
  1235. result, nil);
  1236. }];
  1237. }];
  1238. }
  1239. }];
  1240. }];
  1241. return;
  1242. }
  1243. #if TARGET_OS_IOS
  1244. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  1245. FIRPhoneAuthCredential *phoneAuthCredential = (FIRPhoneAuthCredential *)credential;
  1246. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  1247. isLinkOperation:YES
  1248. completion:^(NSError *_Nullable error) {
  1249. if (error) {
  1250. callInMainThreadWithAuthDataResultAndError(
  1251. completion, nil, error);
  1252. } else {
  1253. callInMainThreadWithAuthDataResultAndError(
  1254. completion, result, nil);
  1255. }
  1256. }];
  1257. return;
  1258. }
  1259. #endif
  1260. [self->_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  1261. CallbackWithAuthDataResultAndError completeWithError =
  1262. ^(FIRAuthDataResult *result, NSError *error) {
  1263. complete();
  1264. callInMainThreadWithAuthDataResultAndError(completion, result, error);
  1265. };
  1266. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1267. NSError *_Nullable error) {
  1268. if (error) {
  1269. completeWithError(nil, error);
  1270. return;
  1271. }
  1272. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  1273. FIRVerifyAssertionRequest *request =
  1274. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  1275. requestConfiguration:requestConfiguration];
  1276. [credential prepareVerifyAssertionRequest:request];
  1277. request.accessToken = accessToken;
  1278. [FIRAuthBackend
  1279. verifyAssertion:request
  1280. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  1281. if (error) {
  1282. [self signOutIfTokenIsInvalidWithError:error];
  1283. completeWithError(nil, error);
  1284. return;
  1285. }
  1286. FIRAdditionalUserInfo *additionalUserInfo =
  1287. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  1288. FIROAuthCredential *updatedOAuthCredential =
  1289. [[FIROAuthCredential alloc] initWithVerifyAssertionResponse:response];
  1290. FIRAuthDataResult *result =
  1291. [[FIRAuthDataResult alloc] initWithUser:self
  1292. additionalUserInfo:additionalUserInfo
  1293. credential:updatedOAuthCredential];
  1294. // Update the new token and refresh user info again.
  1295. self->_tokenService = [[FIRSecureTokenService alloc]
  1296. initWithRequestConfiguration:requestConfiguration
  1297. accessToken:response.IDToken
  1298. accessTokenExpirationDate:response.approximateExpirationDate
  1299. refreshToken:response.refreshToken];
  1300. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1301. NSError *_Nullable error) {
  1302. if (error) {
  1303. completeWithError(nil, error);
  1304. return;
  1305. }
  1306. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1307. [[FIRGetAccountInfoRequest alloc]
  1308. initWithAccessToken:accessToken
  1309. requestConfiguration:requestConfiguration];
  1310. [FIRAuthBackend
  1311. getAccountInfo:getAccountInfoRequest
  1312. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1313. NSError *_Nullable error) {
  1314. if (error) {
  1315. [self signOutIfTokenIsInvalidWithError:error];
  1316. completeWithError(nil, error);
  1317. return;
  1318. }
  1319. self.anonymous = NO;
  1320. [self updateWithGetAccountInfoResponse:response];
  1321. if (![self updateKeychain:&error]) {
  1322. completeWithError(nil, error);
  1323. return;
  1324. }
  1325. completeWithError(result, nil);
  1326. }];
  1327. }];
  1328. }];
  1329. }];
  1330. }];
  1331. });
  1332. }
  1333. - (void)linkWithProvider:(id<FIRFederatedAuthProvider>)provider
  1334. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  1335. completion:(nullable FIRAuthDataResultCallback)completion {
  1336. #if TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  1337. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1338. [provider getCredentialWithUIDelegate:UIDelegate
  1339. completion:^(FIRAuthCredential *_Nullable credential,
  1340. NSError *_Nullable error) {
  1341. if (error) {
  1342. completion(nil, error);
  1343. return;
  1344. }
  1345. [self linkWithCredential:credential completion:completion];
  1346. }];
  1347. });
  1348. #endif // TARGET_OS_IOS && (!defined(TARGET_OS_VISION) || !TARGET_OS_VISION)
  1349. }
  1350. - (void)unlinkFromProvider:(NSString *)provider
  1351. completion:(nullable FIRAuthResultCallback)completion {
  1352. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  1353. CallbackWithError completeAndCallbackWithError = ^(NSError *error) {
  1354. complete();
  1355. callInMainThreadWithUserAndError(completion, self, error);
  1356. };
  1357. [self
  1358. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1359. if (error) {
  1360. completeAndCallbackWithError(error);
  1361. return;
  1362. }
  1363. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  1364. FIRSetAccountInfoRequest *setAccountInfoRequest =
  1365. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:requestConfiguration];
  1366. setAccountInfoRequest.accessToken = accessToken;
  1367. if (!self->_providerData[provider]) {
  1368. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  1369. return;
  1370. }
  1371. setAccountInfoRequest.deleteProviders = @[ provider ];
  1372. [FIRAuthBackend
  1373. setAccountInfo:setAccountInfoRequest
  1374. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  1375. NSError *_Nullable error) {
  1376. if (error) {
  1377. [self signOutIfTokenIsInvalidWithError:error];
  1378. completeAndCallbackWithError(error);
  1379. return;
  1380. }
  1381. // We can't just use the provider info objects in FIRSetAccountInfoResponse
  1382. // because they don't have localID and email fields. Remove the specific
  1383. // provider manually.
  1384. NSMutableDictionary *mutableProviderData = [self->_providerData mutableCopy];
  1385. [mutableProviderData removeObjectForKey:provider];
  1386. self->_providerData = [mutableProviderData copy];
  1387. if ([provider isEqualToString:FIREmailAuthProviderID]) {
  1388. self->_hasEmailPasswordCredential = NO;
  1389. }
  1390. #if TARGET_OS_IOS
  1391. // After successfully unlinking a phone auth provider, remove the phone number
  1392. // from the cached user info.
  1393. if ([provider isEqualToString:FIRPhoneAuthProviderID]) {
  1394. self->_phoneNumber = nil;
  1395. }
  1396. #endif
  1397. if (response.IDToken && response.refreshToken) {
  1398. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  1399. initWithRequestConfiguration:requestConfiguration
  1400. accessToken:response.IDToken
  1401. accessTokenExpirationDate:response.approximateExpirationDate
  1402. refreshToken:response.refreshToken];
  1403. [self setTokenService:tokenService
  1404. callback:^(NSError *_Nullable error) {
  1405. completeAndCallbackWithError(error);
  1406. }];
  1407. return;
  1408. }
  1409. if (![self updateKeychain:&error]) {
  1410. completeAndCallbackWithError(error);
  1411. return;
  1412. }
  1413. completeAndCallbackWithError(nil);
  1414. }];
  1415. }];
  1416. }];
  1417. }
  1418. - (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion {
  1419. [self sendEmailVerificationWithNullableActionCodeSettings:nil completion:completion];
  1420. }
  1421. - (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1422. completion:
  1423. (nullable FIRSendEmailVerificationCallback)completion {
  1424. [self sendEmailVerificationWithNullableActionCodeSettings:actionCodeSettings
  1425. completion:completion];
  1426. }
  1427. /** @fn sendEmailVerificationWithNullableActionCodeSettings:completion:
  1428. @brief Initiates email verification for the user.
  1429. @param actionCodeSettings Optionally, a @c FIRActionCodeSettings object containing settings
  1430. related to the handling action codes.
  1431. */
  1432. - (void)sendEmailVerificationWithNullableActionCodeSettings:
  1433. (nullable FIRActionCodeSettings *)actionCodeSettings
  1434. completion:
  1435. (nullable FIRSendEmailVerificationCallback)
  1436. completion {
  1437. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1438. [self
  1439. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1440. if (error) {
  1441. callInMainThreadWithError(completion, error);
  1442. return;
  1443. }
  1444. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  1445. FIRGetOOBConfirmationCodeRequest *request =
  1446. [FIRGetOOBConfirmationCodeRequest verifyEmailRequestWithAccessToken:accessToken
  1447. actionCodeSettings:actionCodeSettings
  1448. requestConfiguration:configuration];
  1449. [FIRAuthBackend
  1450. getOOBConfirmationCode:request
  1451. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1452. NSError *_Nullable error) {
  1453. [self signOutIfTokenIsInvalidWithError:error];
  1454. callInMainThreadWithError(completion, error);
  1455. }];
  1456. }];
  1457. });
  1458. }
  1459. - (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1460. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1461. [self
  1462. internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  1463. if (error) {
  1464. callInMainThreadWithError(completion, error);
  1465. return;
  1466. }
  1467. FIRDeleteAccountRequest *deleteUserRequest =
  1468. [[FIRDeleteAccountRequest alloc] initWitLocalID:self->_userID
  1469. accessToken:accessToken
  1470. requestConfiguration:self->_auth.requestConfiguration];
  1471. [FIRAuthBackend deleteAccount:deleteUserRequest
  1472. callback:^(NSError *_Nullable error) {
  1473. if (error) {
  1474. callInMainThreadWithError(completion, error);
  1475. return;
  1476. }
  1477. if (![self->_auth signOutByForceWithUserID:self->_userID
  1478. error:&error]) {
  1479. callInMainThreadWithError(completion, error);
  1480. return;
  1481. }
  1482. callInMainThreadWithError(completion, error);
  1483. }];
  1484. }];
  1485. });
  1486. }
  1487. /** @fn signOutIfTokenIsInvalidWithError:
  1488. @brief Signs out this user if the user or the token is invalid.
  1489. @param error The error from the server.
  1490. */
  1491. - (void)signOutIfTokenIsInvalidWithError:(nullable NSError *)error {
  1492. NSInteger errorCode = error.code;
  1493. if (errorCode == FIRAuthErrorCodeUserNotFound || errorCode == FIRAuthErrorCodeUserDisabled ||
  1494. errorCode == FIRAuthErrorCodeInvalidUserToken ||
  1495. errorCode == FIRAuthErrorCodeUserTokenExpired) {
  1496. FIRLogNotice(kFIRLoggerAuth, @"I-AUT000016",
  1497. @"Invalid user token detected, user is automatically signed out.");
  1498. [_auth signOutByForceWithUserID:_userID error:NULL];
  1499. }
  1500. }
  1501. @end
  1502. @implementation FIRUserProfileChangeRequest {
  1503. /** @var _user
  1504. @brief The user associated with the change request.
  1505. */
  1506. FIRUser *_user;
  1507. /** @var _displayName
  1508. @brief The display name value to set if @c _displayNameSet is YES.
  1509. */
  1510. NSString *_displayName;
  1511. /** @var _displayNameSet
  1512. @brief Indicates the display name should be part of the change request.
  1513. */
  1514. BOOL _displayNameSet;
  1515. /** @var _photoURL
  1516. @brief The photo URL value to set if @c _displayNameSet is YES.
  1517. */
  1518. NSURL *_photoURL;
  1519. /** @var _photoURLSet
  1520. @brief Indicates the photo URL should be part of the change request.
  1521. */
  1522. BOOL _photoURLSet;
  1523. /** @var _consumed
  1524. @brief Indicates the @c commitChangesWithCallback: method has already been invoked.
  1525. */
  1526. BOOL _consumed;
  1527. }
  1528. - (nullable instancetype)initWithUser:(FIRUser *)user {
  1529. self = [super init];
  1530. if (self) {
  1531. _user = user;
  1532. }
  1533. return self;
  1534. }
  1535. - (nullable NSString *)displayName {
  1536. return _displayName;
  1537. }
  1538. - (void)setDisplayName:(nullable NSString *)displayName {
  1539. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1540. if (self->_consumed) {
  1541. [NSException
  1542. raise:NSInternalInconsistencyException
  1543. format:@"%@", @"Invalid call to setDisplayName: after commitChangesWithCallback:."];
  1544. return;
  1545. }
  1546. self->_displayNameSet = YES;
  1547. self->_displayName = [displayName copy];
  1548. });
  1549. }
  1550. - (nullable NSURL *)photoURL {
  1551. return _photoURL;
  1552. }
  1553. - (void)setPhotoURL:(nullable NSURL *)photoURL {
  1554. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1555. if (self->_consumed) {
  1556. [NSException raise:NSInternalInconsistencyException
  1557. format:@"%@", @"Invalid call to setPhotoURL: after commitChangesWithCallback:."];
  1558. return;
  1559. }
  1560. self->_photoURLSet = YES;
  1561. self->_photoURL = [photoURL copy];
  1562. });
  1563. }
  1564. /** @fn hasUpdates
  1565. @brief Indicates at least one field has a value which needs to be committed.
  1566. */
  1567. - (BOOL)hasUpdates {
  1568. return _displayNameSet || _photoURLSet;
  1569. }
  1570. - (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1571. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1572. if (self->_consumed) {
  1573. [NSException raise:NSInternalInconsistencyException
  1574. format:@"%@", @"commitChangesWithCallback: should only be called once."];
  1575. return;
  1576. }
  1577. self->_consumed = YES;
  1578. // Return fast if there is nothing to update:
  1579. if (![self hasUpdates]) {
  1580. callInMainThreadWithError(completion, nil);
  1581. return;
  1582. }
  1583. NSString *displayName = [self->_displayName copy];
  1584. BOOL displayNameWasSet = self->_displayNameSet;
  1585. NSURL *photoURL = [self->_photoURL copy];
  1586. BOOL photoURLWasSet = self->_photoURLSet;
  1587. [self->_user
  1588. executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  1589. FIRSetAccountInfoRequest *request) {
  1590. if (photoURLWasSet) {
  1591. request.photoURL = photoURL;
  1592. }
  1593. if (displayNameWasSet) {
  1594. request.displayName = displayName;
  1595. }
  1596. }
  1597. callback:^(NSError *_Nullable error) {
  1598. if (error) {
  1599. callInMainThreadWithError(completion, error);
  1600. return;
  1601. }
  1602. if (displayNameWasSet) {
  1603. [self->_user setDisplayName:displayName];
  1604. }
  1605. if (photoURLWasSet) {
  1606. [self->_user setPhotoURL:photoURL];
  1607. }
  1608. if (![self->_user updateKeychain:&error]) {
  1609. callInMainThreadWithError(completion, error);
  1610. return;
  1611. }
  1612. callInMainThreadWithError(completion, nil);
  1613. }];
  1614. });
  1615. }
  1616. @end
  1617. NS_ASSUME_NONNULL_END