User.swift 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  16. extension User: NSSecureCoding {}
  17. /// Represents a user.
  18. ///
  19. /// Firebase Auth does not attempt to validate users
  20. /// when loading them from the keychain. Invalidated users (such as those
  21. /// whose passwords have been changed on another client) are automatically
  22. /// logged out when an auth-dependent operation is attempted or when the
  23. /// ID token is automatically refreshed.
  24. ///
  25. /// This class is thread-safe.
  26. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  27. @objc(FIRUser) open class User: NSObject, UserInfo {
  28. /// Indicates the user represents an anonymous user.
  29. @objc public internal(set) var isAnonymous: Bool
  30. /// Indicates the user represents an anonymous user.
  31. @objc open func anonymous() -> Bool { return isAnonymous }
  32. /// Indicates the email address associated with this user has been verified.
  33. @objc public private(set) var isEmailVerified: Bool
  34. /// Indicates the email address associated with this user has been verified.
  35. @objc open func emailVerified() -> Bool { return isEmailVerified }
  36. /// Profile data for each identity provider, if any.
  37. ///
  38. /// This data is cached on sign-in and updated when linking or unlinking.
  39. @objc open var providerData: [UserInfo] {
  40. return Array(providerDataRaw.values)
  41. }
  42. var providerDataRaw: [String: UserInfoImpl]
  43. /// The backend service for the given instance.
  44. private(set) var backend: AuthBackend
  45. /// Metadata associated with the Firebase user in question.
  46. @objc public private(set) var metadata: UserMetadata
  47. /// The tenant ID of the current user. `nil` if none is available.
  48. @objc public private(set) var tenantID: String?
  49. #if os(iOS)
  50. /// Multi factor object associated with the user.
  51. ///
  52. /// This property is available on iOS only.
  53. @objc public private(set) var multiFactor: MultiFactor
  54. #endif
  55. /// [Deprecated] Updates the email address for the user.
  56. ///
  57. /// On success, the cached user profile data is updated. Returns an error when
  58. /// [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  59. /// is enabled.
  60. ///
  61. /// May fail if there is already an account with this email address that was created using
  62. /// email and password authentication.
  63. ///
  64. /// Invoked asynchronously on the main thread in the future.
  65. ///
  66. /// Possible error codes:
  67. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  68. /// sent in the request.
  69. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  70. /// the console for this action.
  71. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  72. /// sending update email.
  73. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email is already in use by another
  74. /// account.
  75. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  76. /// * `AuthErrorCodeRequiresRecentLogin` - Updating a user’s email is a security
  77. /// sensitive operation that requires a recent login from the user. This error indicates
  78. /// the user has not signed in recently enough. To resolve, reauthenticate the user by
  79. /// calling `reauthenticate(with:)`.
  80. /// - Parameter email: The email address for the user.
  81. /// - Parameter completion: Optionally; the block invoked when the user profile change has
  82. /// finished.
  83. #if !FIREBASE_CI
  84. @available(
  85. *,
  86. deprecated,
  87. message: "`updateEmail` is deprecated and will be removed in a future release. Use sendEmailVerification(beforeUpdatingEmail:) instead."
  88. )
  89. #endif // !FIREBASE_CI
  90. @objc(updateEmail:completion:)
  91. open func updateEmail(to email: String, completion: ((Error?) -> Void)? = nil) {
  92. kAuthGlobalWorkQueue.async {
  93. self.updateEmail(email: email, password: nil) { error in
  94. User.callInMainThreadWithError(callback: completion, error: error)
  95. }
  96. }
  97. }
  98. /// [Deprecated] Updates the email address for the user.
  99. ///
  100. /// On success, the cached user profile data is updated. Throws when
  101. /// [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  102. /// is enabled.
  103. ///
  104. /// May fail if there is already an account with this email address that was created using
  105. /// email and password authentication.
  106. ///
  107. /// Invoked asynchronously on the main thread in the future.
  108. ///
  109. /// Possible error codes:
  110. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  111. /// sent in the request.
  112. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  113. /// the console for this action.
  114. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  115. /// sending update email.
  116. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email is already in use by another
  117. /// account.
  118. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  119. /// * `AuthErrorCodeRequiresRecentLogin` - Updating a user’s email is a security
  120. /// sensitive operation that requires a recent login from the user. This error indicates
  121. /// the user has not signed in recently enough. To resolve, reauthenticate the user by
  122. /// calling `reauthenticate(with:)`.
  123. /// - Parameter email: The email address for the user.
  124. #if !FIREBASE_CI
  125. @available(
  126. *,
  127. deprecated,
  128. message: "`updateEmail` is deprecated and will be removed in a future release. Use sendEmailVerification(beforeUpdatingEmail:) instead."
  129. )
  130. #endif // !FIREBASE_CI
  131. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  132. open func updateEmail(to email: String) async throws {
  133. return try await withCheckedThrowingContinuation { continuation in
  134. self.updateEmail(to: email) { error in
  135. if let error {
  136. continuation.resume(throwing: error)
  137. } else {
  138. continuation.resume()
  139. }
  140. }
  141. }
  142. }
  143. /// Updates the password for the user. On success, the cached user profile data is updated.
  144. ///
  145. /// Invoked asynchronously on the main thread in the future.
  146. ///
  147. /// Possible error codes:
  148. /// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled
  149. /// sign in with the specified identity provider.
  150. /// * `AuthErrorCodeRequiresRecentLogin` - Updating a user’s password is a security
  151. /// sensitive operation that requires a recent login from the user. This error indicates
  152. /// the user has not signed in recently enough. To resolve, reauthenticate the user by
  153. /// calling `reauthenticate(with:)`.
  154. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  155. /// considered too weak. The `NSLocalizedFailureReasonErrorKey` field in the `userInfo`
  156. /// dictionary object will contain more detailed explanation that can be shown to the user.
  157. /// - Parameter password: The new password for the user.
  158. /// - Parameter completion: Optionally; the block invoked when the user profile change has
  159. /// finished.
  160. @objc(updatePassword:completion:)
  161. open func updatePassword(to password: String, completion: ((Error?) -> Void)? = nil) {
  162. guard password.count > 0 else {
  163. if let completion {
  164. completion(AuthErrorUtils.weakPasswordError(serverResponseReason: "Missing Password"))
  165. }
  166. return
  167. }
  168. kAuthGlobalWorkQueue.async {
  169. self.updateEmail(email: nil, password: password) { error in
  170. User.callInMainThreadWithError(callback: completion, error: error)
  171. }
  172. }
  173. }
  174. /// Updates the password for the user. On success, the cached user profile data is updated.
  175. ///
  176. /// Invoked asynchronously on the main thread in the future.
  177. ///
  178. /// Possible error codes:
  179. /// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled
  180. /// sign in with the specified identity provider.
  181. /// * `AuthErrorCodeRequiresRecentLogin` - Updating a user’s password is a security
  182. /// sensitive operation that requires a recent login from the user. This error indicates
  183. /// the user has not signed in recently enough. To resolve, reauthenticate the user by
  184. /// calling `reauthenticate(with:)`.
  185. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  186. /// considered too weak. The `NSLocalizedFailureReasonErrorKey` field in the `userInfo`
  187. /// dictionary object will contain more detailed explanation that can be shown to the user.
  188. /// - Parameter password: The new password for the user.
  189. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  190. open func updatePassword(to password: String) async throws {
  191. return try await withCheckedThrowingContinuation { continuation in
  192. self.updatePassword(to: password) { error in
  193. if let error {
  194. continuation.resume(throwing: error)
  195. } else {
  196. continuation.resume()
  197. }
  198. }
  199. }
  200. }
  201. #if os(iOS)
  202. /// Updates the phone number for the user. On success, the cached user profile data is updated.
  203. ///
  204. /// Invoked asynchronously on the main thread in the future.
  205. ///
  206. /// This method is available on iOS only.
  207. ///
  208. /// Possible error codes:
  209. /// * `AuthErrorCodeRequiresRecentLogin` - Updating a user’s phone number is a security
  210. /// sensitive operation that requires a recent login from the user. This error indicates
  211. /// the user has not signed in recently enough. To resolve, reauthenticate the user by
  212. /// calling `reauthenticate(with:)`.
  213. /// - Parameter credential: The new phone number credential corresponding to the
  214. /// phone number to be added to the Firebase account, if a phone number is already linked to the
  215. /// account this new phone number will replace it.
  216. /// - Parameter completion: Optionally; the block invoked when the user profile change has
  217. /// finished.
  218. @objc(updatePhoneNumberCredential:completion:)
  219. open func updatePhoneNumber(_ credential: PhoneAuthCredential,
  220. completion: ((Error?) -> Void)? = nil) {
  221. kAuthGlobalWorkQueue.async {
  222. self.internalUpdateOrLinkPhoneNumber(credential: credential,
  223. isLinkOperation: false) { error in
  224. User.callInMainThreadWithError(callback: completion, error: error)
  225. }
  226. }
  227. }
  228. /// Updates the phone number for the user. On success, the cached user profile data is updated.
  229. ///
  230. /// Invoked asynchronously on the main thread in the future.
  231. ///
  232. /// This method is available on iOS only.
  233. ///
  234. /// Possible error codes:
  235. /// * `AuthErrorCodeRequiresRecentLogin` - Updating a user’s phone number is a security
  236. /// sensitive operation that requires a recent login from the user. This error indicates
  237. /// the user has not signed in recently enough. To resolve, reauthenticate the user by
  238. /// calling `reauthenticate(with:)`.
  239. /// - Parameter credential: The new phone number credential corresponding to the
  240. /// phone number to be added to the Firebase account, if a phone number is already linked to the
  241. /// account this new phone number will replace it.
  242. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  243. open func updatePhoneNumber(_ credential: PhoneAuthCredential) async throws {
  244. return try await withCheckedThrowingContinuation { continuation in
  245. self.updatePhoneNumber(credential) { error in
  246. if let error {
  247. continuation.resume(throwing: error)
  248. } else {
  249. continuation.resume()
  250. }
  251. }
  252. }
  253. }
  254. #endif
  255. /// Creates an object which may be used to change the user's profile data.
  256. ///
  257. /// Set the properties of the returned object, then call
  258. /// `UserProfileChangeRequest.commitChanges()` to perform the updates atomically.
  259. /// - Returns: An object which may be used to change the user's profile data atomically.
  260. @objc(profileChangeRequest)
  261. open func createProfileChangeRequest() -> UserProfileChangeRequest {
  262. var result: UserProfileChangeRequest!
  263. kAuthGlobalWorkQueue.sync {
  264. result = UserProfileChangeRequest(self)
  265. }
  266. return result
  267. }
  268. /// A refresh token; useful for obtaining new access tokens independently.
  269. ///
  270. /// This property should only be used for advanced scenarios, and is not typically needed.
  271. @objc open var refreshToken: String? {
  272. var result: String?
  273. kAuthGlobalWorkQueue.sync {
  274. result = self.tokenService.refreshToken
  275. }
  276. return result
  277. }
  278. /// Reloads the user's profile data from the server.
  279. ///
  280. /// May fail with an `AuthErrorCodeRequiresRecentLogin` error code. In this case
  281. /// you should call `reauthenticate(with:)` before re-invoking
  282. /// `updateEmail(to:)`.
  283. /// - Parameter completion: Optionally; the block invoked when the reload has finished. Invoked
  284. /// asynchronously on the main thread in the future.
  285. @objc open func reload(completion: ((Error?) -> Void)? = nil) {
  286. kAuthGlobalWorkQueue.async {
  287. self.getAccountInfoRefreshingCache { user, error in
  288. User.callInMainThreadWithError(callback: completion, error: error)
  289. }
  290. }
  291. }
  292. /// Reloads the user's profile data from the server.
  293. ///
  294. /// May fail with an `AuthErrorCodeRequiresRecentLogin` error code. In this case
  295. /// you should call `reauthenticate(with:)` before re-invoking
  296. /// `updateEmail(to:)`.
  297. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  298. open func reload() async throws {
  299. return try await withCheckedThrowingContinuation { continuation in
  300. self.reload { error in
  301. if let error {
  302. continuation.resume(throwing: error)
  303. } else {
  304. continuation.resume()
  305. }
  306. }
  307. }
  308. }
  309. /// Renews the user's authentication tokens by validating a fresh set of credentials supplied
  310. /// by the user and returns additional identity provider data.
  311. ///
  312. /// If the user associated with the supplied credential is different from the current user,
  313. /// or if the validation of the supplied credentials fails; an error is returned and the current
  314. /// user remains signed in.
  315. ///
  316. /// Possible error codes:
  317. /// * `AuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid.
  318. /// This could happen if it has expired or it is malformed.
  319. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts with the
  320. /// identity provider represented by the credential are not enabled. Enable them in the
  321. /// Auth section of the Firebase console.
  322. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email asserted by the credential
  323. /// (e.g. the email in a Facebook access token) is already in use by an existing account,
  324. /// that cannot be authenticated with this method. This error will only be thrown if the
  325. /// "One account per email address" setting is enabled in the Firebase console, under Auth
  326. /// settings. Please note that the error code raised in this specific situation may not be
  327. /// the same on Web and Android.
  328. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  329. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted reauthentication with
  330. /// an incorrect password, if credential is of the type `EmailPasswordAuthCredential`.
  331. /// * `AuthErrorCodeUserMismatch` - Indicates that an attempt was made to
  332. /// reauthenticate with a user which is not the current user.
  333. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  334. /// - Parameter credential: A user-supplied credential, which will be validated by the server.
  335. /// This can be a successful third-party identity provider sign-in, or an email address and
  336. /// password.
  337. /// - Parameter completion: Optionally; the block invoked when the re-authentication operation has
  338. /// finished. Invoked asynchronously on the main thread in the future.
  339. @objc(reauthenticateWithCredential:completion:)
  340. open func reauthenticate(with credential: AuthCredential,
  341. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  342. kAuthGlobalWorkQueue.async {
  343. Task {
  344. do {
  345. let authResult = try await self.auth?.internalSignInAndRetrieveData(
  346. withCredential: credential,
  347. isReauthentication: true
  348. )
  349. guard let user = authResult?.user,
  350. user.uid == self.auth?.getUserID() else {
  351. User.callInMainThreadWithAuthDataResultAndError(
  352. callback: completion,
  353. result: authResult,
  354. error: AuthErrorUtils.userMismatchError()
  355. )
  356. return
  357. }
  358. // Successful reauthenticate
  359. do {
  360. try await self.userProfileUpdate.setTokenService(user: self,
  361. tokenService: user.tokenService)
  362. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  363. result: authResult,
  364. error: nil)
  365. } catch {
  366. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  367. result: authResult,
  368. error: error)
  369. }
  370. } catch {
  371. // If "user not found" error returned by backend,
  372. // translate to user mismatch error which is more
  373. // accurate.
  374. var reportError: Error = error
  375. if (error as NSError).code == AuthErrorCode.userNotFound.rawValue {
  376. reportError = AuthErrorUtils.userMismatchError()
  377. }
  378. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  379. result: nil,
  380. error: reportError)
  381. }
  382. }
  383. }
  384. }
  385. /// Renews the user's authentication tokens by validating a fresh set of credentials supplied
  386. /// by the user and returns additional identity provider data.
  387. ///
  388. /// If the user associated with the supplied credential is different from the current user,
  389. /// or if the validation of the supplied credentials fails; an error is returned and the current
  390. /// user remains signed in.
  391. ///
  392. /// Possible error codes:
  393. /// * `AuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid.
  394. /// This could happen if it has expired or it is malformed.
  395. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts with the
  396. /// identity provider represented by the credential are not enabled. Enable them in the
  397. /// Auth section of the Firebase console.
  398. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email asserted by the credential
  399. /// (e.g. the email in a Facebook access token) is already in use by an existing account,
  400. /// that cannot be authenticated with this method. This error will only be thrown if the
  401. /// "One account per email address" setting is enabled in the Firebase console, under Auth
  402. /// settings. Please note that the error code raised in this specific situation may not be
  403. /// the same on Web and Android.
  404. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  405. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted reauthentication with
  406. /// an incorrect password, if credential is of the type `EmailPasswordAuthCredential`.
  407. /// * `AuthErrorCodeUserMismatch` - Indicates that an attempt was made to
  408. /// reauthenticate with a user which is not the current user.
  409. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  410. /// - Parameter credential: A user-supplied credential, which will be validated by the server.
  411. /// This can be a successful third-party identity provider sign-in, or an email address and
  412. /// password.
  413. /// - Returns: The `AuthDataResult` after the reauthentication.
  414. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  415. @discardableResult
  416. open func reauthenticate(with credential: AuthCredential) async throws -> AuthDataResult {
  417. return try await withCheckedThrowingContinuation { continuation in
  418. self.reauthenticate(with: credential) { result, error in
  419. if let result {
  420. continuation.resume(returning: result)
  421. } else if let error {
  422. continuation.resume(throwing: error)
  423. }
  424. }
  425. }
  426. }
  427. #if os(iOS)
  428. /// Renews the user's authentication using the provided auth provider instance.
  429. ///
  430. /// This method is available on iOS only.
  431. /// - Parameter provider: An instance of an auth provider used to initiate the reauthenticate
  432. /// flow.
  433. /// - Parameter uiDelegate: Optionally an instance of a class conforming to the `AuthUIDelegate`
  434. /// protocol, used for presenting the web context. If nil, a default `AuthUIDelegate`
  435. /// will be used.
  436. /// - Parameter completion: Optionally; a block which is invoked when the reauthenticate flow
  437. /// finishes, or is canceled. Invoked asynchronously on the main thread in the future.
  438. @objc(reauthenticateWithProvider:UIDelegate:completion:)
  439. open func reauthenticate(with provider: FederatedAuthProvider,
  440. uiDelegate: AuthUIDelegate?,
  441. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  442. kAuthGlobalWorkQueue.async {
  443. Task {
  444. do {
  445. let credential = try await provider.credential(with: uiDelegate)
  446. self.reauthenticate(with: credential, completion: completion)
  447. } catch {
  448. if let completion {
  449. completion(nil, error)
  450. }
  451. }
  452. }
  453. }
  454. }
  455. /// Renews the user's authentication using the provided auth provider instance.
  456. ///
  457. /// This method is available on iOS only.
  458. /// - Parameter provider: An instance of an auth provider used to initiate the reauthenticate
  459. /// flow.
  460. /// - Parameter uiDelegate: Optionally an instance of a class conforming to the `AuthUIDelegate`
  461. /// protocol, used for presenting the web context. If nil, a default `AuthUIDelegate`
  462. /// will be used.
  463. /// - Returns: The `AuthDataResult` after the reauthentication.
  464. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  465. @discardableResult
  466. open func reauthenticate(with provider: FederatedAuthProvider,
  467. uiDelegate: AuthUIDelegate?) async throws -> AuthDataResult {
  468. return try await withCheckedThrowingContinuation { continuation in
  469. self.reauthenticate(with: provider, uiDelegate: uiDelegate) { result, error in
  470. if let result {
  471. continuation.resume(returning: result)
  472. } else if let error {
  473. continuation.resume(throwing: error)
  474. }
  475. }
  476. }
  477. }
  478. #endif
  479. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  480. /// - Parameter completion: Optionally; the block invoked when the token is available. Invoked
  481. /// asynchronously on the main thread in the future.
  482. @objc(getIDTokenWithCompletion:)
  483. open func getIDToken(completion: ((String?, Error?) -> Void)?) {
  484. // |getIDTokenForcingRefresh:completion:| is also a public API so there is no need to dispatch to
  485. // global work queue here.
  486. getIDTokenForcingRefresh(false, completion: completion)
  487. }
  488. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  489. ///
  490. /// The authentication token will be refreshed (by making a network request) if it has
  491. /// expired, or if `forceRefresh` is `true`.
  492. /// - Parameter forceRefresh: Forces a token refresh. Useful if the token becomes invalid for some
  493. /// reason other than an expiration.
  494. /// - Parameter completion: Optionally; the block invoked when the token is available. Invoked
  495. /// asynchronously on the main thread in the future.
  496. @objc(getIDTokenForcingRefresh:completion:)
  497. open func getIDTokenForcingRefresh(_ forceRefresh: Bool,
  498. completion: ((String?, Error?) -> Void)?) {
  499. getIDTokenResult(forcingRefresh: forceRefresh) { tokenResult, error in
  500. if let completion {
  501. DispatchQueue.main.async {
  502. completion(tokenResult?.token, error)
  503. }
  504. }
  505. }
  506. }
  507. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  508. ///
  509. /// The authentication token will be refreshed (by making a network request) if it has
  510. /// expired, or if `forceRefresh` is `true`.
  511. /// - Parameter forceRefresh: Forces a token refresh. Useful if the token becomes invalid for some
  512. /// reason other than an expiration.
  513. /// - Returns: The Firebase authentication token.
  514. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  515. open func getIDToken(forcingRefresh forceRefresh: Bool = false) async throws -> String {
  516. return try await withCheckedThrowingContinuation { continuation in
  517. self.getIDTokenForcingRefresh(forceRefresh) { tokenResult, error in
  518. if let tokenResult {
  519. continuation.resume(returning: tokenResult)
  520. } else if let error {
  521. continuation.resume(throwing: error)
  522. }
  523. }
  524. }
  525. }
  526. /// API included for compatibility with a mis-named Firebase 10 API.
  527. /// Use `getIDToken(forcingRefresh forceRefresh: Bool = false)` instead.
  528. open func idTokenForcingRefresh(_ forceRefresh: Bool) async throws -> String {
  529. return try await getIDToken(forcingRefresh: forceRefresh)
  530. }
  531. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  532. /// - Parameter completion: Optionally; the block invoked when the token is available. Invoked
  533. /// asynchronously on the main thread in the future.
  534. @objc(getIDTokenResultWithCompletion:)
  535. open func getIDTokenResult(completion: ((AuthTokenResult?, Error?) -> Void)?) {
  536. getIDTokenResult(forcingRefresh: false) { tokenResult, error in
  537. if let completion {
  538. DispatchQueue.main.async {
  539. completion(tokenResult, error)
  540. }
  541. }
  542. }
  543. }
  544. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  545. ///
  546. /// The authentication token will be refreshed (by making a network request) if it has
  547. /// expired, or if `forcingRefresh` is `true`.
  548. /// - Parameter forcingRefresh: Forces a token refresh. Useful if the token becomes invalid for
  549. /// some
  550. /// reason other than an expiration.
  551. /// - Parameter completion: Optionally; the block invoked when the token is available. Invoked
  552. /// asynchronously on the main thread in the future.
  553. @objc(getIDTokenResultForcingRefresh:completion:)
  554. open func getIDTokenResult(forcingRefresh: Bool,
  555. completion: ((AuthTokenResult?, Error?) -> Void)?) {
  556. kAuthGlobalWorkQueue.async {
  557. self.internalGetToken(forceRefresh: forcingRefresh, backend: self.backend) { token, error in
  558. var tokenResult: AuthTokenResult?
  559. if let token {
  560. do {
  561. tokenResult = try AuthTokenResult.tokenResult(token: token)
  562. AuthLog.logDebug(code: "I-AUT000017", message: "Actual token expiration date: " +
  563. "\(String(describing: tokenResult?.expirationDate))," +
  564. "current date: \(Date())")
  565. if let completion {
  566. DispatchQueue.main.async {
  567. completion(tokenResult, error)
  568. }
  569. }
  570. return
  571. } catch {
  572. if let completion {
  573. DispatchQueue.main.async {
  574. completion(tokenResult, error)
  575. }
  576. }
  577. return
  578. }
  579. }
  580. if let completion {
  581. DispatchQueue.main.async {
  582. completion(nil, error)
  583. }
  584. }
  585. }
  586. }
  587. }
  588. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  589. ///
  590. /// The authentication token will be refreshed (by making a network request) if it has
  591. /// expired, or if `forceRefresh` is `true`.
  592. /// - Parameter forceRefresh: Forces a token refresh. Useful if the token becomes invalid for some
  593. /// reason other than an expiration.
  594. /// - Returns: The Firebase authentication token.
  595. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  596. open func getIDTokenResult(forcingRefresh forceRefresh: Bool = false) async throws
  597. -> AuthTokenResult {
  598. return try await withCheckedThrowingContinuation { continuation in
  599. self.getIDTokenResult(forcingRefresh: forceRefresh) { tokenResult, error in
  600. if let tokenResult {
  601. continuation.resume(returning: tokenResult)
  602. } else if let error {
  603. continuation.resume(throwing: error)
  604. }
  605. }
  606. }
  607. }
  608. /// Associates a user account from a third-party identity provider with this user and
  609. /// returns additional identity provider data.
  610. ///
  611. /// Invoked asynchronously on the main thread in the future.
  612. ///
  613. /// Possible error codes:
  614. /// * `AuthErrorCodeProviderAlreadyLinked` - Indicates an attempt to link a provider of a
  615. /// type already linked to this account.
  616. /// * `AuthErrorCodeCredentialAlreadyInUse` - Indicates an attempt to link with a
  617. /// credential that has already been linked with a different Firebase account.
  618. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts with the identity
  619. /// provider represented by the credential are not enabled. Enable them in the Auth section
  620. /// of the Firebase console.
  621. ///
  622. /// This method may also return error codes associated with `updateEmail(to:)` and
  623. /// `updatePassword(to:)` on `User`.
  624. /// - Parameter credential: The credential for the identity provider.
  625. /// - Parameter completion: Optionally; the block invoked when the unlinking is complete, or
  626. /// fails.
  627. @objc(linkWithCredential:completion:)
  628. open func link(with credential: AuthCredential,
  629. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  630. kAuthGlobalWorkQueue.async {
  631. if self.providerDataRaw[credential.provider] != nil {
  632. User.callInMainThreadWithAuthDataResultAndError(
  633. callback: completion,
  634. result: nil,
  635. error: AuthErrorUtils.providerAlreadyLinkedError()
  636. )
  637. return
  638. }
  639. if let emailCredential = credential as? EmailAuthCredential {
  640. self.link(withEmailCredential: emailCredential, completion: completion)
  641. return
  642. }
  643. #if !os(watchOS)
  644. if let gameCenterCredential = credential as? GameCenterAuthCredential {
  645. self.link(withGameCenterCredential: gameCenterCredential, completion: completion)
  646. return
  647. }
  648. #endif
  649. #if os(iOS)
  650. if let phoneCredential = credential as? PhoneAuthCredential {
  651. self.link(withPhoneCredential: phoneCredential, completion: completion)
  652. return
  653. }
  654. #endif
  655. Task {
  656. do {
  657. let authDataResult = try await self.userProfileUpdate.link(user: self, with: credential)
  658. await MainActor.run {
  659. completion?(authDataResult, nil)
  660. }
  661. } catch {
  662. await MainActor.run {
  663. completion?(nil, error)
  664. }
  665. }
  666. }
  667. }
  668. }
  669. /// Associates a user account from a third-party identity provider with this user and
  670. /// returns additional identity provider data.
  671. ///
  672. /// Invoked asynchronously on the main thread in the future.
  673. ///
  674. /// Possible error codes:
  675. /// * `AuthErrorCodeProviderAlreadyLinked` - Indicates an attempt to link a provider of a
  676. /// type already linked to this account.
  677. /// * `AuthErrorCodeCredentialAlreadyInUse` - Indicates an attempt to link with a
  678. /// credential that has already been linked with a different Firebase account.
  679. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts with the identity
  680. /// provider represented by the credential are not enabled. Enable them in the Auth section
  681. /// of the Firebase console.
  682. ///
  683. /// This method may also return error codes associated with `updateEmail(to:)` and
  684. /// `updatePassword(to:)` on `User`.
  685. /// - Parameter credential: The credential for the identity provider.
  686. /// - Returns: An `AuthDataResult`.
  687. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  688. @discardableResult
  689. open func link(with credential: AuthCredential) async throws -> AuthDataResult {
  690. return try await withCheckedThrowingContinuation { continuation in
  691. self.link(with: credential) { result, error in
  692. if let result {
  693. continuation.resume(returning: result)
  694. } else if let error {
  695. continuation.resume(throwing: error)
  696. }
  697. }
  698. }
  699. }
  700. #if os(iOS)
  701. /// Link the user with the provided auth provider instance.
  702. ///
  703. /// This method is available on iOSonly.
  704. /// - Parameter provider: An instance of an auth provider used to initiate the link flow.
  705. /// - Parameter uiDelegate: Optionally an instance of a class conforming to the `AuthUIDelegate`
  706. /// protocol used for presenting the web context. If nil, a default `AuthUIDelegate` will be
  707. /// used.
  708. /// - Parameter completion: Optionally; a block which is invoked when the link flow finishes, or
  709. /// is canceled. Invoked asynchronously on the main thread in the future.
  710. @objc(linkWithProvider:UIDelegate:completion:)
  711. open func link(with provider: FederatedAuthProvider,
  712. uiDelegate: AuthUIDelegate?,
  713. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  714. kAuthGlobalWorkQueue.async {
  715. Task {
  716. do {
  717. let credential = try await provider.credential(with: uiDelegate)
  718. self.link(with: credential, completion: completion)
  719. } catch {
  720. if let completion {
  721. completion(nil, error)
  722. }
  723. }
  724. }
  725. }
  726. }
  727. /// Link the user with the provided auth provider instance.
  728. ///
  729. /// This method is available on iOSonly.
  730. /// - Parameter provider: An instance of an auth provider used to initiate the link flow.
  731. /// - Parameter uiDelegate: Optionally an instance of a class conforming to the `AuthUIDelegate`
  732. /// protocol used for presenting the web context. If nil, a default `AuthUIDelegate`
  733. /// will be used.
  734. /// - Returns: An AuthDataResult.
  735. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  736. @discardableResult
  737. open func link(with provider: FederatedAuthProvider,
  738. uiDelegate: AuthUIDelegate?) async throws -> AuthDataResult {
  739. return try await withCheckedThrowingContinuation { continuation in
  740. self.link(with: provider, uiDelegate: uiDelegate) { result, error in
  741. if let result {
  742. continuation.resume(returning: result)
  743. } else if let error {
  744. continuation.resume(throwing: error)
  745. }
  746. }
  747. }
  748. }
  749. #endif
  750. /// Disassociates a user account from a third-party identity provider with this user.
  751. ///
  752. /// Invoked asynchronously on the main thread in the future.
  753. ///
  754. /// Possible error codes:
  755. /// * `AuthErrorCodeNoSuchProvider` - Indicates an attempt to unlink a provider
  756. /// that is not linked to the account.
  757. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  758. /// operation that requires a recent login from the user. This error indicates the user
  759. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  760. /// `reauthenticate(with:)`.
  761. /// - Parameter provider: The provider ID of the provider to unlink.
  762. /// - Parameter completion: Optionally; the block invoked when the unlinking is complete, or
  763. /// fails.
  764. @objc open func unlink(fromProvider provider: String,
  765. completion: ((User?, Error?) -> Void)? = nil) {
  766. Task {
  767. do {
  768. let user = try await unlink(fromProvider: provider)
  769. await MainActor.run {
  770. completion?(user, nil)
  771. }
  772. } catch {
  773. await MainActor.run {
  774. completion?(nil, error)
  775. }
  776. }
  777. }
  778. }
  779. /// Disassociates a user account from a third-party identity provider with this user.
  780. ///
  781. /// Invoked asynchronously on the main thread in the future.
  782. ///
  783. /// Possible error codes:
  784. /// * `AuthErrorCodeNoSuchProvider` - Indicates an attempt to unlink a provider
  785. /// that is not linked to the account.
  786. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  787. /// operation that requires a recent login from the user. This error indicates the user
  788. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  789. /// `reauthenticate(with:)`.
  790. /// - Parameter provider: The provider ID of the provider to unlink.
  791. /// - Returns: The user.
  792. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  793. open func unlink(fromProvider provider: String) async throws -> User {
  794. return try await userProfileUpdate.unlink(user: self, fromProvider: provider)
  795. }
  796. /// Initiates email verification for the user.
  797. ///
  798. /// Possible error codes:
  799. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  800. /// sent in the request.
  801. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  802. /// the console for this action.
  803. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  804. /// sending update email.
  805. /// * `AuthErrorCodeUserNotFound` - Indicates the user account was not found.
  806. /// - Parameter completion: Optionally; the block invoked when the request to send an email
  807. /// verification is complete, or fails. Invoked asynchronously on the main thread in the future.
  808. @objc(sendEmailVerificationWithCompletion:)
  809. open func __sendEmailVerification(withCompletion completion: ((Error?) -> Void)?) {
  810. sendEmailVerification(completion: completion)
  811. }
  812. /// Initiates email verification for the user.
  813. ///
  814. /// Possible error codes:
  815. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  816. /// sent in the request.
  817. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  818. /// the console for this action.
  819. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  820. /// sending update email.
  821. /// * `AuthErrorCodeUserNotFound` - Indicates the user account was not found.
  822. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  823. /// handling action codes.
  824. /// - Parameter completion: Optionally; the block invoked when the request to send an email
  825. /// verification is complete, or fails. Invoked asynchronously on the main thread in the future.
  826. @objc(sendEmailVerificationWithActionCodeSettings:completion:)
  827. open func sendEmailVerification(with actionCodeSettings: ActionCodeSettings? = nil,
  828. completion: ((Error?) -> Void)? = nil) {
  829. kAuthGlobalWorkQueue.async {
  830. self.internalGetToken(backend: self.backend) { accessToken, error in
  831. if let error {
  832. User.callInMainThreadWithError(callback: completion, error: error)
  833. return
  834. }
  835. guard let accessToken else {
  836. fatalError("Internal Error: Both error and accessToken are nil.")
  837. }
  838. guard let requestConfiguration = self.auth?.requestConfiguration else {
  839. fatalError("Internal Error: Unexpected nil requestConfiguration.")
  840. }
  841. let request = GetOOBConfirmationCodeRequest.verifyEmailRequest(
  842. accessToken: accessToken,
  843. actionCodeSettings: actionCodeSettings,
  844. requestConfiguration: requestConfiguration
  845. )
  846. Task {
  847. do {
  848. let _ = try await self.backend.call(with: request)
  849. User.callInMainThreadWithError(callback: completion, error: nil)
  850. } catch {
  851. self.signOutIfTokenIsInvalid(withError: error)
  852. User.callInMainThreadWithError(callback: completion, error: error)
  853. }
  854. }
  855. }
  856. }
  857. }
  858. /// Initiates email verification for the user.
  859. ///
  860. /// Possible error codes:
  861. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  862. /// sent in the request.
  863. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  864. /// the console for this action.
  865. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  866. /// sending update email.
  867. /// * `AuthErrorCodeUserNotFound` - Indicates the user account was not found.
  868. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  869. /// handling action codes. The default value is `nil`.
  870. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  871. open func sendEmailVerification(with actionCodeSettings: ActionCodeSettings? = nil) async throws {
  872. return try await withCheckedThrowingContinuation { continuation in
  873. self.sendEmailVerification(with: actionCodeSettings) { error in
  874. if let error {
  875. continuation.resume(throwing: error)
  876. } else {
  877. continuation.resume()
  878. }
  879. }
  880. }
  881. }
  882. /// Deletes the user account (also signs out the user, if this was the current user).
  883. ///
  884. /// Possible error codes:
  885. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  886. /// operation that requires a recent login from the user. This error indicates the user
  887. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  888. /// `reauthenticate(with:)`.
  889. /// - Parameter completion: Optionally; the block invoked when the request to delete the account
  890. /// is complete, or fails. Invoked asynchronously on the main thread in the future.
  891. @objc open func delete(completion: ((Error?) -> Void)? = nil) {
  892. kAuthGlobalWorkQueue.async {
  893. self.internalGetToken(backend: self.backend) { accessToken, error in
  894. if let error {
  895. User.callInMainThreadWithError(callback: completion, error: error)
  896. return
  897. }
  898. guard let accessToken else {
  899. fatalError("Auth Internal Error: Both error and accessToken are nil.")
  900. }
  901. guard let requestConfiguration = self.auth?.requestConfiguration else {
  902. fatalError("Auth Internal Error: Unexpected nil requestConfiguration.")
  903. }
  904. let request = DeleteAccountRequest(localID: self.uid, accessToken: accessToken,
  905. requestConfiguration: requestConfiguration)
  906. Task {
  907. do {
  908. let _ = try await self.backend.call(with: request)
  909. try self.auth?.signOutByForce(withUserID: self.uid)
  910. User.callInMainThreadWithError(callback: completion, error: nil)
  911. } catch {
  912. User.callInMainThreadWithError(callback: completion, error: error)
  913. }
  914. }
  915. }
  916. }
  917. }
  918. /// Deletes the user account (also signs out the user, if this was the current user).
  919. ///
  920. /// Possible error codes:
  921. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  922. /// operation that requires a recent login from the user. This error indicates the user
  923. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  924. /// `reauthenticate(with:)`.
  925. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  926. open func delete() async throws {
  927. return try await withCheckedThrowingContinuation { continuation in
  928. self.delete { error in
  929. if let error {
  930. continuation.resume(throwing: error)
  931. } else {
  932. continuation.resume()
  933. }
  934. }
  935. }
  936. }
  937. /// Send an email to verify the ownership of the account then update to the new email.
  938. /// - Parameter email: The email to be updated to.
  939. /// - Parameter completion: Optionally; the block invoked when the request to send the
  940. /// verification email is complete, or fails.
  941. @objc(sendEmailVerificationBeforeUpdatingEmail:completion:)
  942. open func __sendEmailVerificationBeforeUpdating(email: String, completion: ((Error?) -> Void)?) {
  943. sendEmailVerification(beforeUpdatingEmail: email, completion: completion)
  944. }
  945. /// Send an email to verify the ownership of the account then update to the new email.
  946. /// - Parameter email: The email to be updated to.
  947. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  948. /// handling action codes.
  949. /// - Parameter completion: Optionally; the block invoked when the request to send the
  950. /// verification email is complete, or fails.
  951. @objc open func sendEmailVerification(beforeUpdatingEmail email: String,
  952. actionCodeSettings: ActionCodeSettings? = nil,
  953. completion: ((Error?) -> Void)? = nil) {
  954. kAuthGlobalWorkQueue.async {
  955. self.internalGetToken(backend: self.backend) { accessToken, error in
  956. if let error {
  957. User.callInMainThreadWithError(callback: completion, error: error)
  958. return
  959. }
  960. guard let accessToken else {
  961. fatalError("Internal Error: Both error and accessToken are nil.")
  962. }
  963. guard let requestConfiguration = self.auth?.requestConfiguration else {
  964. fatalError("Internal Error: Unexpected nil requestConfiguration.")
  965. }
  966. let request = GetOOBConfirmationCodeRequest.verifyBeforeUpdateEmail(
  967. accessToken: accessToken,
  968. newEmail: email,
  969. actionCodeSettings: actionCodeSettings,
  970. requestConfiguration: requestConfiguration
  971. )
  972. Task {
  973. do {
  974. let _ = try await self.backend.call(with: request)
  975. User.callInMainThreadWithError(callback: completion, error: nil)
  976. } catch {
  977. User.callInMainThreadWithError(callback: completion, error: error)
  978. }
  979. }
  980. }
  981. }
  982. }
  983. /// Send an email to verify the ownership of the account then update to the new email.
  984. /// - Parameter newEmail: The email to be updated to.
  985. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  986. /// handling action codes.
  987. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  988. open func sendEmailVerification(beforeUpdatingEmail newEmail: String,
  989. actionCodeSettings: ActionCodeSettings? = nil) async throws {
  990. return try await withCheckedThrowingContinuation { continuation in
  991. self.sendEmailVerification(beforeUpdatingEmail: newEmail,
  992. actionCodeSettings: actionCodeSettings) { error in
  993. if let error {
  994. continuation.resume(throwing: error)
  995. } else {
  996. continuation.resume()
  997. }
  998. }
  999. }
  1000. }
  1001. // MARK: Internal implementations below
  1002. func rawAccessToken() -> String {
  1003. return tokenService.accessToken
  1004. }
  1005. func accessTokenExpirationDate() -> Date? {
  1006. return tokenService.accessTokenExpirationDate
  1007. }
  1008. init(withTokenService tokenService: SecureTokenService, backend: AuthBackend) {
  1009. self.backend = backend
  1010. providerDataRaw = [:]
  1011. userProfileUpdate = UserProfileUpdate()
  1012. self.tokenService = tokenService
  1013. isAnonymous = false
  1014. isEmailVerified = false
  1015. metadata = UserMetadata(withCreationDate: nil, lastSignInDate: nil)
  1016. tenantID = nil
  1017. #if os(iOS)
  1018. multiFactor = MultiFactor(withMFAEnrollments: [])
  1019. #endif
  1020. uid = ""
  1021. hasEmailPasswordCredential = false
  1022. requestConfiguration = AuthRequestConfiguration(apiKey: "", appID: "")
  1023. }
  1024. class func retrieveUser(withAuth auth: Auth,
  1025. accessToken: String?,
  1026. accessTokenExpirationDate: Date?,
  1027. refreshToken: String?,
  1028. anonymous: Bool) async throws -> User {
  1029. guard let accessToken = accessToken,
  1030. let refreshToken = refreshToken else {
  1031. throw AuthErrorUtils
  1032. .invalidUserTokenError(message: "Invalid user token: accessToken or refreshToken is nil")
  1033. }
  1034. let tokenService = SecureTokenService(withRequestConfiguration: auth.requestConfiguration,
  1035. accessToken: accessToken,
  1036. accessTokenExpirationDate: accessTokenExpirationDate,
  1037. refreshToken: refreshToken)
  1038. let user = User(withTokenService: tokenService, backend: auth.backend)
  1039. user.auth = auth
  1040. user.tenantID = auth.tenantID
  1041. user.requestConfiguration = auth.requestConfiguration
  1042. let accessToken2 = try await user.internalGetTokenAsync(backend: user.backend)
  1043. let getAccountInfoRequest = GetAccountInfoRequest(
  1044. accessToken: accessToken2,
  1045. requestConfiguration: user.requestConfiguration
  1046. )
  1047. let response = try await auth.backend.call(with: getAccountInfoRequest)
  1048. user.isAnonymous = anonymous
  1049. user.update(withGetAccountInfoResponse: response)
  1050. return user
  1051. }
  1052. @objc open var providerID: String {
  1053. return "Firebase"
  1054. }
  1055. /// The provider's user ID for the user.
  1056. @objc open var uid: String
  1057. /// The name of the user.
  1058. @objc open var displayName: String?
  1059. /// The URL of the user's profile photo.
  1060. @objc open var photoURL: URL?
  1061. /// The user's email address.
  1062. @objc open var email: String?
  1063. /// A phone number associated with the user.
  1064. ///
  1065. /// This property is only available for users authenticated via phone number auth.
  1066. @objc open var phoneNumber: String?
  1067. /// Whether or not the user can be authenticated by using Firebase email and password.
  1068. var hasEmailPasswordCredential: Bool
  1069. /// Used to serialize the update profile calls.
  1070. private let userProfileUpdate: UserProfileUpdate
  1071. /// A strong reference to a requestConfiguration instance associated with this user instance.
  1072. var requestConfiguration: AuthRequestConfiguration
  1073. /// A secure token service associated with this user. For performing token exchanges and
  1074. /// refreshing access tokens.
  1075. var tokenService: SecureTokenService
  1076. private weak var _auth: Auth?
  1077. /// A weak reference to an `Auth` instance associated with this instance.
  1078. weak var auth: Auth? {
  1079. set {
  1080. guard let newValue else {
  1081. fatalError("Firebase Auth Internal Error: Set user's auth property with non-nil instance.")
  1082. }
  1083. _auth = newValue
  1084. requestConfiguration = newValue.requestConfiguration
  1085. tokenService.requestConfiguration = requestConfiguration
  1086. backend = newValue.backend
  1087. }
  1088. get { return _auth }
  1089. }
  1090. // MARK: Private functions
  1091. private func updateEmail(email: String?,
  1092. password: String?,
  1093. callback: @escaping (Error?) -> Void) {
  1094. let hadEmailPasswordCredential = hasEmailPasswordCredential
  1095. executeUserUpdateWithChanges(changeBlock: { user, request in
  1096. if let email {
  1097. request.email = email
  1098. }
  1099. if let password {
  1100. request.password = password
  1101. }
  1102. }) { error in
  1103. if let error {
  1104. callback(error)
  1105. return
  1106. }
  1107. if let email {
  1108. self.email = email
  1109. }
  1110. if self.email != nil {
  1111. if !hadEmailPasswordCredential {
  1112. // The list of providers need to be updated for the newly added email-password provider.
  1113. Task {
  1114. do {
  1115. let accessToken = try await self.internalGetTokenAsync(backend: self.backend)
  1116. if let requestConfiguration = self.auth?.requestConfiguration {
  1117. let getAccountInfoRequest = GetAccountInfoRequest(accessToken: accessToken,
  1118. requestConfiguration: requestConfiguration)
  1119. do {
  1120. let accountInfoResponse = try await self.backend.call(with: getAccountInfoRequest)
  1121. if let users = accountInfoResponse.users {
  1122. for userAccountInfo in users {
  1123. // Set the account to non-anonymous if there are any providers, even if
  1124. // they're not email/password ones.
  1125. if let providerUsers = userAccountInfo.providerUserInfo {
  1126. if providerUsers.count > 0 {
  1127. self.isAnonymous = false
  1128. for providerUserInfo in providerUsers {
  1129. if providerUserInfo.providerID == EmailAuthProvider.id {
  1130. self.hasEmailPasswordCredential = true
  1131. break
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. }
  1138. self.update(withGetAccountInfoResponse: accountInfoResponse)
  1139. if let error = self.updateKeychain() {
  1140. callback(error)
  1141. return
  1142. }
  1143. callback(nil)
  1144. } catch {
  1145. self.signOutIfTokenIsInvalid(withError: error)
  1146. callback(error)
  1147. }
  1148. }
  1149. } catch {
  1150. callback(error)
  1151. }
  1152. }
  1153. return
  1154. }
  1155. }
  1156. if let error = self.updateKeychain() {
  1157. callback(error)
  1158. return
  1159. }
  1160. callback(nil)
  1161. }
  1162. }
  1163. /// Performs a setAccountInfo request by mutating the results of a getAccountInfo response,
  1164. /// atomically in regards to other calls to this method.
  1165. /// - Parameter changeBlock: A block responsible for mutating a template `SetAccountInfoRequest`
  1166. /// - Parameter callback: A block to invoke when the change is complete. Invoked asynchronously on
  1167. /// the auth global work queue in the future.
  1168. func executeUserUpdateWithChanges(changeBlock: @escaping (GetAccountInfoResponse.User,
  1169. SetAccountInfoRequest) -> Void,
  1170. callback: @escaping (Error?) -> Void) {
  1171. Task {
  1172. do {
  1173. try await userProfileUpdate.executeUserUpdateWithChanges(user: self,
  1174. changeBlock: changeBlock)
  1175. await MainActor.run {
  1176. callback(nil)
  1177. }
  1178. } catch {
  1179. await MainActor.run {
  1180. callback(error)
  1181. }
  1182. }
  1183. }
  1184. }
  1185. /// Gets the users' account data from the server, updating our local values.
  1186. /// - Parameter callback: Invoked when the request to getAccountInfo has completed, or when an
  1187. /// error has been detected. Invoked asynchronously on the auth global work queue in the future.
  1188. func getAccountInfoRefreshingCache(callback: @escaping (GetAccountInfoResponse.User?,
  1189. Error?) -> Void) {
  1190. Task {
  1191. do {
  1192. let responseUser = try await userProfileUpdate.getAccountInfoRefreshingCache(self)
  1193. await MainActor.run {
  1194. callback(responseUser, nil)
  1195. }
  1196. } catch {
  1197. await MainActor.run {
  1198. callback(nil, error)
  1199. }
  1200. }
  1201. }
  1202. }
  1203. func update(withGetAccountInfoResponse response: GetAccountInfoResponse) {
  1204. guard let user = response.users?.first else {
  1205. // Silent fallthrough in ObjC code.
  1206. AuthLog.logWarning(code: "I-AUT000016", message: "Missing user in GetAccountInfoResponse")
  1207. return
  1208. }
  1209. uid = user.localID ?? ""
  1210. email = user.email
  1211. isEmailVerified = user.emailVerified
  1212. displayName = user.displayName
  1213. photoURL = user.photoURL
  1214. phoneNumber = user.phoneNumber
  1215. hasEmailPasswordCredential = user.passwordHash != nil && user.passwordHash!.count > 0
  1216. metadata = UserMetadata(withCreationDate: user.creationDate,
  1217. lastSignInDate: user.lastLoginDate)
  1218. var providerData: [String: UserInfoImpl] = [:]
  1219. if let providerUserInfos = user.providerUserInfo {
  1220. for providerUserInfo in providerUserInfos {
  1221. let userInfo = UserInfoImpl.userInfo(
  1222. withGetAccountInfoResponseProviderUserInfo: providerUserInfo
  1223. )
  1224. if let providerID = providerUserInfo.providerID {
  1225. providerData[providerID] = userInfo
  1226. }
  1227. }
  1228. }
  1229. providerDataRaw = providerData
  1230. #if os(iOS)
  1231. if let enrollments = user.mfaEnrollments {
  1232. multiFactor = MultiFactor(withMFAEnrollments: enrollments)
  1233. }
  1234. multiFactor.user = self
  1235. #endif
  1236. }
  1237. #if os(iOS)
  1238. /// Updates the phone number for the user. On success, the cached user profile data is updated.
  1239. ///
  1240. /// Invoked asynchronously on the global work queue in the future.
  1241. /// - Parameter credential: The new phone number credential corresponding to the phone
  1242. /// number to be added to the Firebase account. If a phone number is already linked to the
  1243. /// account, this new phone number will replace it.
  1244. /// - Parameter isLinkOperation: Boolean value indicating whether or not this is a link
  1245. /// operation.
  1246. /// - Parameter completion: Optionally; the block invoked when the user profile change has
  1247. /// finished.
  1248. private func internalUpdateOrLinkPhoneNumber(credential: PhoneAuthCredential,
  1249. isLinkOperation: Bool,
  1250. completion: @escaping (Error?) -> Void) {
  1251. internalGetToken(backend: backend) { accessToken, error in
  1252. if let error {
  1253. completion(error)
  1254. return
  1255. }
  1256. guard let accessToken = accessToken else {
  1257. fatalError("Auth Internal Error: Both accessToken and error are nil")
  1258. }
  1259. guard let configuration = self.auth?.requestConfiguration else {
  1260. fatalError("Auth Internal Error: nil value for VerifyPhoneNumberRequest initializer")
  1261. }
  1262. switch credential.credentialKind {
  1263. case .phoneNumber: fatalError("Internal Error: Missing verificationCode")
  1264. case let .verification(verificationID, code):
  1265. let operation = isLinkOperation ? AuthOperationType.link : AuthOperationType.update
  1266. let request = VerifyPhoneNumberRequest(verificationID: verificationID,
  1267. verificationCode: code,
  1268. operation: operation,
  1269. requestConfiguration: configuration)
  1270. request.accessToken = accessToken
  1271. Task {
  1272. do {
  1273. let verifyResponse = try await self.backend.call(with: request)
  1274. guard let idToken = verifyResponse.idToken,
  1275. let refreshToken = verifyResponse.refreshToken else {
  1276. fatalError("Internal Auth Error: missing token in internalUpdateOrLinkPhoneNumber")
  1277. }
  1278. // Update the new token and refresh user info again.
  1279. self.tokenService = SecureTokenService(
  1280. withRequestConfiguration: configuration,
  1281. accessToken: idToken,
  1282. accessTokenExpirationDate: verifyResponse.approximateExpirationDate,
  1283. refreshToken: refreshToken
  1284. )
  1285. // Get account info to update cached user info.
  1286. self.getAccountInfoRefreshingCache { user, error in
  1287. if let error {
  1288. self.signOutIfTokenIsInvalid(withError: error)
  1289. completion(error)
  1290. return
  1291. }
  1292. self.isAnonymous = false
  1293. if let error = self.updateKeychain() {
  1294. completion(error)
  1295. return
  1296. }
  1297. completion(nil)
  1298. }
  1299. } catch {
  1300. self.signOutIfTokenIsInvalid(withError: error)
  1301. completion(error)
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. #endif
  1308. private func link(withEmail email: String,
  1309. password: String,
  1310. authResult: AuthDataResult,
  1311. _ completion: ((AuthDataResult?, Error?) -> Void)?) {
  1312. internalGetToken(backend: backend) { accessToken, error in
  1313. guard let requestConfiguration = self.auth?.requestConfiguration else {
  1314. fatalError("Internal auth error: missing auth on User")
  1315. }
  1316. let request = SignUpNewUserRequest(email: email,
  1317. password: password,
  1318. displayName: nil,
  1319. idToken: accessToken,
  1320. requestConfiguration: requestConfiguration)
  1321. Task {
  1322. do {
  1323. #if os(iOS)
  1324. guard let auth = self.auth else {
  1325. fatalError("Internal Auth error: missing auth instance on user")
  1326. }
  1327. let response = try await auth.injectRecaptcha(request: request,
  1328. action: AuthRecaptchaAction
  1329. .signUpPassword)
  1330. #else
  1331. let response = try await self.backend.call(with: request)
  1332. #endif
  1333. guard let refreshToken = response.refreshToken,
  1334. let idToken = response.idToken else {
  1335. fatalError("Internal auth error: Invalid SignUpNewUserResponse")
  1336. }
  1337. // Update the new token and refresh user info again.
  1338. try await self.updateTokenAndRefreshUser(
  1339. idToken: idToken,
  1340. refreshToken: refreshToken,
  1341. expirationDate: response.approximateExpirationDate,
  1342. requestConfiguration: requestConfiguration
  1343. )
  1344. User.callInMainThreadWithAuthDataResultAndError(
  1345. callback: completion,
  1346. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1347. error: nil
  1348. )
  1349. } catch {
  1350. self.signOutIfTokenIsInvalid(withError: error)
  1351. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1352. result: nil, error: error)
  1353. }
  1354. }
  1355. }
  1356. }
  1357. private func link(withEmailCredential emailCredential: EmailAuthCredential,
  1358. completion: ((AuthDataResult?, Error?) -> Void)?) {
  1359. if hasEmailPasswordCredential {
  1360. User.callInMainThreadWithAuthDataResultAndError(
  1361. callback: completion,
  1362. result: nil,
  1363. error: AuthErrorUtils
  1364. .providerAlreadyLinkedError()
  1365. )
  1366. return
  1367. }
  1368. switch emailCredential.emailType {
  1369. case let .password(password):
  1370. let result = AuthDataResult(withUser: self, additionalUserInfo: nil)
  1371. link(withEmail: emailCredential.email, password: password, authResult: result, completion)
  1372. case let .link(link):
  1373. internalGetToken(backend: backend) { accessToken, error in
  1374. var queryItems = AuthWebUtils.parseURL(link)
  1375. if link.count == 0 {
  1376. if let urlComponents = URLComponents(string: link),
  1377. let query = urlComponents.query {
  1378. queryItems = AuthWebUtils.parseURL(query)
  1379. }
  1380. }
  1381. guard let actionCode = queryItems["oobCode"],
  1382. let requestConfiguration = self.auth?.requestConfiguration else {
  1383. fatalError("Internal Auth Error: Missing oobCode or requestConfiguration")
  1384. }
  1385. let request = EmailLinkSignInRequest(email: emailCredential.email,
  1386. oobCode: actionCode,
  1387. requestConfiguration: requestConfiguration)
  1388. request.idToken = accessToken
  1389. Task {
  1390. do {
  1391. let response = try await self.backend.call(with: request)
  1392. guard let idToken = response.idToken,
  1393. let refreshToken = response.refreshToken else {
  1394. fatalError("Internal Auth Error: missing token in EmailLinkSignInResponse")
  1395. }
  1396. try await self.updateTokenAndRefreshUser(
  1397. idToken: idToken,
  1398. refreshToken: refreshToken,
  1399. expirationDate: response.approximateExpirationDate,
  1400. requestConfiguration: requestConfiguration
  1401. )
  1402. User.callInMainThreadWithAuthDataResultAndError(
  1403. callback: completion,
  1404. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1405. error: nil
  1406. )
  1407. } catch {
  1408. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1409. result: nil,
  1410. error: error)
  1411. }
  1412. }
  1413. }
  1414. }
  1415. }
  1416. #if !os(watchOS)
  1417. private func link(withGameCenterCredential gameCenterCredential: GameCenterAuthCredential,
  1418. completion: ((AuthDataResult?, Error?) -> Void)?) {
  1419. internalGetToken(backend: backend) { accessToken, error in
  1420. guard let requestConfiguration = self.auth?.requestConfiguration,
  1421. let publicKeyURL = gameCenterCredential.publicKeyURL,
  1422. let signature = gameCenterCredential.signature,
  1423. let salt = gameCenterCredential.salt else {
  1424. fatalError("Internal Auth Error: Nil value field for SignInWithGameCenterRequest")
  1425. }
  1426. let request = SignInWithGameCenterRequest(playerID: gameCenterCredential.playerID,
  1427. teamPlayerID: gameCenterCredential.teamPlayerID,
  1428. gamePlayerID: gameCenterCredential.gamePlayerID,
  1429. publicKeyURL: publicKeyURL,
  1430. signature: signature,
  1431. salt: salt,
  1432. timestamp: gameCenterCredential.timestamp,
  1433. displayName: gameCenterCredential.displayName,
  1434. requestConfiguration: requestConfiguration)
  1435. request.accessToken = accessToken
  1436. Task {
  1437. do {
  1438. let response = try await self.backend.call(with: request)
  1439. guard let idToken = response.idToken,
  1440. let refreshToken = response.refreshToken else {
  1441. fatalError("Internal Auth Error: missing token in link(withGameCredential")
  1442. }
  1443. try await self.updateTokenAndRefreshUser(
  1444. idToken: idToken,
  1445. refreshToken: refreshToken,
  1446. expirationDate: response.approximateExpirationDate,
  1447. requestConfiguration: requestConfiguration
  1448. )
  1449. User.callInMainThreadWithAuthDataResultAndError(
  1450. callback: completion,
  1451. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1452. error: nil
  1453. )
  1454. } catch {
  1455. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1456. result: nil,
  1457. error: error)
  1458. }
  1459. }
  1460. }
  1461. }
  1462. #endif
  1463. #if os(iOS)
  1464. private func link(withPhoneCredential phoneCredential: PhoneAuthCredential,
  1465. completion: ((AuthDataResult?, Error?) -> Void)?) {
  1466. internalUpdateOrLinkPhoneNumber(credential: phoneCredential,
  1467. isLinkOperation: true) { error in
  1468. if let error {
  1469. User.callInMainThreadWithAuthDataResultAndError(
  1470. callback: completion,
  1471. result: nil,
  1472. error: error
  1473. )
  1474. } else {
  1475. let result = AuthDataResult(withUser: self, additionalUserInfo: nil)
  1476. User.callInMainThreadWithAuthDataResultAndError(
  1477. callback: completion,
  1478. result: result,
  1479. error: nil
  1480. )
  1481. }
  1482. }
  1483. }
  1484. #endif
  1485. // Update the new token and refresh user info again.
  1486. private func updateTokenAndRefreshUser(idToken: String,
  1487. refreshToken: String,
  1488. expirationDate: Date?,
  1489. requestConfiguration: AuthRequestConfiguration) async throws {
  1490. return try await userProfileUpdate
  1491. .updateTokenAndRefreshUser(
  1492. user: self,
  1493. idToken: idToken,
  1494. refreshToken: refreshToken,
  1495. expirationDate: expirationDate
  1496. )
  1497. }
  1498. /// Signs out this user if the user or the token is invalid.
  1499. /// - Parameter error: The error from the server.
  1500. func signOutIfTokenIsInvalid(withError error: Error) {
  1501. let code = (error as NSError).code
  1502. if code == AuthErrorCode.userNotFound.rawValue ||
  1503. code == AuthErrorCode.userDisabled.rawValue ||
  1504. code == AuthErrorCode.invalidUserToken.rawValue ||
  1505. code == AuthErrorCode.userTokenExpired.rawValue {
  1506. AuthLog.logNotice(code: "I-AUT000016",
  1507. message: "Invalid user token detected, user is automatically signed out.")
  1508. try? auth?.signOutByForce(withUserID: uid)
  1509. }
  1510. }
  1511. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1512. /// - Parameter callback: The block to invoke when the token is available. Invoked asynchronously
  1513. /// on the global work thread in the future.
  1514. func internalGetToken(forceRefresh: Bool = false,
  1515. backend: AuthBackend,
  1516. callback: @escaping (String?, Error?) -> Void,
  1517. callCallbackOnMain: Bool = false) {
  1518. Task {
  1519. do {
  1520. let token = try await internalGetTokenAsync(forceRefresh: forceRefresh, backend: backend)
  1521. if callCallbackOnMain {
  1522. Auth.wrapMainAsync(callback: callback, with: .success(token))
  1523. } else {
  1524. callback(token, nil)
  1525. }
  1526. } catch {
  1527. if callCallbackOnMain {
  1528. Auth.wrapMainAsync(callback: callback, with: .failure(error))
  1529. } else {
  1530. callback(nil, error)
  1531. }
  1532. }
  1533. }
  1534. }
  1535. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1536. /// - Parameter forceRefresh
  1537. func internalGetTokenAsync(forceRefresh: Bool = false,
  1538. backend: AuthBackend) async throws -> String {
  1539. var keychainError = false
  1540. do {
  1541. let (token, tokenUpdated) = try await tokenService.fetchAccessToken(
  1542. forcingRefresh: forceRefresh, backend: backend
  1543. )
  1544. if tokenUpdated {
  1545. if let error = updateKeychain() {
  1546. keychainError = true
  1547. throw error
  1548. }
  1549. }
  1550. return token!
  1551. } catch {
  1552. if !keychainError {
  1553. signOutIfTokenIsInvalid(withError: error)
  1554. }
  1555. throw error
  1556. }
  1557. }
  1558. /// Updates the keychain for user token or info changes.
  1559. /// - Returns: An `Error` on failure.
  1560. func updateKeychain() -> Error? {
  1561. return auth?.updateKeychain(withUser: self)
  1562. }
  1563. /// Calls a callback in main thread with error.
  1564. /// - Parameter callback: The callback to be called in main thread.
  1565. /// - Parameter error: The error to pass to callback.
  1566. class func callInMainThreadWithError(callback: ((Error?) -> Void)?, error: Error?) {
  1567. if let callback {
  1568. DispatchQueue.main.async {
  1569. callback(error)
  1570. }
  1571. }
  1572. }
  1573. /// Calls a callback in main thread with user and error.
  1574. /// - Parameter callback: The callback to be called in main thread.
  1575. /// - Parameter user: The user to pass to callback if there is no error.
  1576. /// - Parameter error: The error to pass to callback.
  1577. private class func callInMainThreadWithUserAndError(callback: ((User?, Error?) -> Void)?,
  1578. user: User,
  1579. error: Error?) {
  1580. if let callback {
  1581. DispatchQueue.main.async {
  1582. callback((error != nil) ? nil : user, error)
  1583. }
  1584. }
  1585. }
  1586. /// Calls a callback in main thread with user and error.
  1587. /// - Parameter callback: The callback to be called in main thread.
  1588. private class func callInMainThreadWithAuthDataResultAndError(callback: (
  1589. (AuthDataResult?, Error?) -> Void
  1590. )?,
  1591. result: AuthDataResult? = nil,
  1592. error: Error? = nil) {
  1593. if let callback {
  1594. DispatchQueue.main.async {
  1595. callback(result, error)
  1596. }
  1597. }
  1598. }
  1599. // MARK: NSSecureCoding
  1600. private let kUserIDCodingKey = "userID"
  1601. private let kHasEmailPasswordCredentialCodingKey = "hasEmailPassword"
  1602. private let kAnonymousCodingKey = "anonymous"
  1603. private let kEmailCodingKey = "email"
  1604. private let kPhoneNumberCodingKey = "phoneNumber"
  1605. private let kEmailVerifiedCodingKey = "emailVerified"
  1606. private let kDisplayNameCodingKey = "displayName"
  1607. private let kPhotoURLCodingKey = "photoURL"
  1608. private let kProviderDataKey = "providerData"
  1609. private let kAPIKeyCodingKey = "APIKey"
  1610. private let kFirebaseAppIDCodingKey = "firebaseAppID"
  1611. private let kTokenServiceCodingKey = "tokenService"
  1612. private let kMetadataCodingKey = "metadata"
  1613. private let kMultiFactorCodingKey = "multiFactor"
  1614. private let kTenantIDCodingKey = "tenantID"
  1615. public static let supportsSecureCoding = true
  1616. public func encode(with coder: NSCoder) {
  1617. coder.encode(uid, forKey: kUserIDCodingKey)
  1618. coder.encode(isAnonymous, forKey: kAnonymousCodingKey)
  1619. coder.encode(hasEmailPasswordCredential, forKey: kHasEmailPasswordCredentialCodingKey)
  1620. coder.encode(providerDataRaw, forKey: kProviderDataKey)
  1621. coder.encode(email, forKey: kEmailCodingKey)
  1622. coder.encode(phoneNumber, forKey: kPhoneNumberCodingKey)
  1623. coder.encode(isEmailVerified, forKey: kEmailVerifiedCodingKey)
  1624. coder.encode(photoURL, forKey: kPhotoURLCodingKey)
  1625. coder.encode(displayName, forKey: kDisplayNameCodingKey)
  1626. coder.encode(metadata, forKey: kMetadataCodingKey)
  1627. coder.encode(tenantID, forKey: kTenantIDCodingKey)
  1628. if let auth {
  1629. coder.encode(auth.requestConfiguration.apiKey, forKey: kAPIKeyCodingKey)
  1630. coder.encode(auth.requestConfiguration.appID, forKey: kFirebaseAppIDCodingKey)
  1631. }
  1632. coder.encode(tokenService, forKey: kTokenServiceCodingKey)
  1633. #if os(iOS)
  1634. coder.encode(multiFactor, forKey: kMultiFactorCodingKey)
  1635. #endif
  1636. }
  1637. public required init?(coder: NSCoder) {
  1638. guard let userID = coder.decodeObject(of: NSString.self, forKey: kUserIDCodingKey) as? String,
  1639. let tokenService = coder.decodeObject(of: SecureTokenService.self,
  1640. forKey: kTokenServiceCodingKey) else {
  1641. return nil
  1642. }
  1643. let anonymous = coder.decodeBool(forKey: kAnonymousCodingKey)
  1644. let hasEmailPasswordCredential = coder.decodeBool(forKey: kHasEmailPasswordCredentialCodingKey)
  1645. let displayName = coder.decodeObject(
  1646. of: NSString.self,
  1647. forKey: kDisplayNameCodingKey
  1648. ) as? String
  1649. let photoURL = coder.decodeObject(of: NSURL.self, forKey: kPhotoURLCodingKey) as? URL
  1650. let email = coder.decodeObject(of: NSString.self, forKey: kEmailCodingKey) as? String
  1651. let phoneNumber = coder.decodeObject(
  1652. of: NSString.self,
  1653. forKey: kPhoneNumberCodingKey
  1654. ) as? String
  1655. let emailVerified = coder.decodeBool(forKey: kEmailVerifiedCodingKey)
  1656. let classes = [NSDictionary.self, NSString.self, UserInfoImpl.self]
  1657. let providerData = coder.decodeObject(of: classes, forKey: kProviderDataKey)
  1658. as? [String: UserInfoImpl]
  1659. let metadata = coder.decodeObject(of: UserMetadata.self, forKey: kMetadataCodingKey)
  1660. let tenantID = coder.decodeObject(of: NSString.self, forKey: kTenantIDCodingKey) as? String
  1661. #if os(iOS)
  1662. let multiFactor = coder.decodeObject(of: MultiFactor.self, forKey: kMultiFactorCodingKey)
  1663. #endif
  1664. self.tokenService = tokenService
  1665. uid = userID
  1666. isAnonymous = anonymous
  1667. self.hasEmailPasswordCredential = hasEmailPasswordCredential
  1668. self.email = email
  1669. isEmailVerified = emailVerified
  1670. self.displayName = displayName
  1671. self.photoURL = photoURL
  1672. providerDataRaw = providerData ?? [:]
  1673. self.phoneNumber = phoneNumber
  1674. self.metadata = metadata ?? UserMetadata(withCreationDate: nil, lastSignInDate: nil)
  1675. self.tenantID = tenantID
  1676. // Note, in practice, the caller will set the `auth` property of this user
  1677. // instance which will as a side-effect overwrite the request configuration.
  1678. // The assignment here is a best-effort placeholder.
  1679. let apiKey = coder.decodeObject(of: NSString.self, forKey: kAPIKeyCodingKey) as? String
  1680. let appID = coder.decodeObject(
  1681. of: NSString.self,
  1682. forKey: kFirebaseAppIDCodingKey
  1683. ) as? String
  1684. requestConfiguration = AuthRequestConfiguration(apiKey: apiKey ?? "", appID: appID ?? "")
  1685. // This property will be overwritten later via the `user.auth` property update. For now, a
  1686. // placeholder is set as the property update should happen right after this initializer.
  1687. backend = AuthBackend(rpcIssuer: AuthBackendRPCIssuer())
  1688. userProfileUpdate = UserProfileUpdate()
  1689. #if os(iOS)
  1690. self.multiFactor = multiFactor ?? MultiFactor()
  1691. super.init()
  1692. multiFactor?.user = self
  1693. #endif
  1694. }
  1695. }