User.swift 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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, @unchecked Sendable /* TODO: unchecked */ {
  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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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: (@Sendable (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,
  943. completion: (@Sendable (Error?) -> Void)?) {
  944. sendEmailVerification(beforeUpdatingEmail: email, completion: completion)
  945. }
  946. /// Send an email to verify the ownership of the account then update to the new email.
  947. /// - Parameter email: The email to be updated to.
  948. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  949. /// handling action codes.
  950. /// - Parameter completion: Optionally; the block invoked when the request to send the
  951. /// verification email is complete, or fails.
  952. @objc open func sendEmailVerification(beforeUpdatingEmail email: String,
  953. actionCodeSettings: ActionCodeSettings? = nil,
  954. completion: (@Sendable (Error?) -> Void)? = nil) {
  955. kAuthGlobalWorkQueue.async {
  956. self.internalGetToken(backend: self.backend) { accessToken, error in
  957. if let error {
  958. User.callInMainThreadWithError(callback: completion, error: error)
  959. return
  960. }
  961. guard let accessToken else {
  962. fatalError("Internal Error: Both error and accessToken are nil.")
  963. }
  964. guard let requestConfiguration = self.auth?.requestConfiguration else {
  965. fatalError("Internal Error: Unexpected nil requestConfiguration.")
  966. }
  967. let request = GetOOBConfirmationCodeRequest.verifyBeforeUpdateEmail(
  968. accessToken: accessToken,
  969. newEmail: email,
  970. actionCodeSettings: actionCodeSettings,
  971. requestConfiguration: requestConfiguration
  972. )
  973. Task {
  974. do {
  975. let _ = try await self.backend.call(with: request)
  976. User.callInMainThreadWithError(callback: completion, error: nil)
  977. } catch {
  978. User.callInMainThreadWithError(callback: completion, error: error)
  979. }
  980. }
  981. }
  982. }
  983. }
  984. /// Send an email to verify the ownership of the account then update to the new email.
  985. /// - Parameter newEmail: The email to be updated to.
  986. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  987. /// handling action codes.
  988. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  989. open func sendEmailVerification(beforeUpdatingEmail newEmail: String,
  990. actionCodeSettings: ActionCodeSettings? = nil) async throws {
  991. return try await withCheckedThrowingContinuation { continuation in
  992. self.sendEmailVerification(beforeUpdatingEmail: newEmail,
  993. actionCodeSettings: actionCodeSettings) { error in
  994. if let error {
  995. continuation.resume(throwing: error)
  996. } else {
  997. continuation.resume()
  998. }
  999. }
  1000. }
  1001. }
  1002. // MARK: Internal implementations below
  1003. func rawAccessToken() -> String {
  1004. return tokenService.accessToken
  1005. }
  1006. func accessTokenExpirationDate() -> Date? {
  1007. return tokenService.accessTokenExpirationDate
  1008. }
  1009. init(withTokenService tokenService: SecureTokenService, backend: AuthBackend) {
  1010. self.backend = backend
  1011. providerDataRaw = [:]
  1012. userProfileUpdate = UserProfileUpdate()
  1013. self.tokenService = tokenService
  1014. isAnonymous = false
  1015. isEmailVerified = false
  1016. metadata = UserMetadata(withCreationDate: nil, lastSignInDate: nil)
  1017. tenantID = nil
  1018. #if os(iOS)
  1019. multiFactor = MultiFactor(withMFAEnrollments: [])
  1020. #endif
  1021. uid = ""
  1022. hasEmailPasswordCredential = false
  1023. requestConfiguration = AuthRequestConfiguration(apiKey: "", appID: "")
  1024. }
  1025. class func retrieveUser(withAuth auth: Auth,
  1026. accessToken: String?,
  1027. accessTokenExpirationDate: Date?,
  1028. refreshToken: String?,
  1029. anonymous: Bool) async throws -> User {
  1030. guard let accessToken = accessToken,
  1031. let refreshToken = refreshToken else {
  1032. throw AuthErrorUtils.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 @Sendable (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 @Sendable (GetAccountInfoResponse.User,
  1169. SetAccountInfoRequest)
  1170. -> Void,
  1171. callback: @escaping @Sendable (Error?) -> Void) {
  1172. Task {
  1173. do {
  1174. try await userProfileUpdate.executeUserUpdateWithChanges(user: self,
  1175. changeBlock: changeBlock)
  1176. await MainActor.run {
  1177. callback(nil)
  1178. }
  1179. } catch {
  1180. await MainActor.run {
  1181. callback(error)
  1182. }
  1183. }
  1184. }
  1185. }
  1186. /// Gets the users' account data from the server, updating our local values.
  1187. /// - Parameter callback: Invoked when the request to getAccountInfo has completed, or when an
  1188. /// error has been detected. Invoked asynchronously on the auth global work queue in the future.
  1189. func getAccountInfoRefreshingCache(callback: @escaping @Sendable (GetAccountInfoResponse.User?,
  1190. Error?) -> Void) {
  1191. Task {
  1192. do {
  1193. let responseUser = try await userProfileUpdate.getAccountInfoRefreshingCache(self)
  1194. await MainActor.run {
  1195. callback(responseUser, nil)
  1196. }
  1197. } catch {
  1198. await MainActor.run {
  1199. callback(nil, error)
  1200. }
  1201. }
  1202. }
  1203. }
  1204. func update(withGetAccountInfoResponse response: GetAccountInfoResponse) {
  1205. guard let user = response.users?.first else {
  1206. // Silent fallthrough in ObjC code.
  1207. AuthLog.logWarning(code: "I-AUT000016", message: "Missing user in GetAccountInfoResponse")
  1208. return
  1209. }
  1210. uid = user.localID ?? ""
  1211. email = user.email
  1212. isEmailVerified = user.emailVerified
  1213. displayName = user.displayName
  1214. photoURL = user.photoURL
  1215. phoneNumber = user.phoneNumber
  1216. hasEmailPasswordCredential = user.passwordHash != nil && user.passwordHash!.count > 0
  1217. metadata = UserMetadata(withCreationDate: user.creationDate,
  1218. lastSignInDate: user.lastLoginDate)
  1219. var providerData: [String: UserInfoImpl] = [:]
  1220. if let providerUserInfos = user.providerUserInfo {
  1221. for providerUserInfo in providerUserInfos {
  1222. let userInfo = UserInfoImpl.userInfo(
  1223. withGetAccountInfoResponseProviderUserInfo: providerUserInfo
  1224. )
  1225. if let providerID = providerUserInfo.providerID {
  1226. providerData[providerID] = userInfo
  1227. }
  1228. }
  1229. }
  1230. providerDataRaw = providerData
  1231. #if os(iOS)
  1232. if let enrollments = user.mfaEnrollments {
  1233. multiFactor = MultiFactor(withMFAEnrollments: enrollments)
  1234. }
  1235. multiFactor.user = self
  1236. #endif
  1237. }
  1238. #if os(iOS)
  1239. /// Updates the phone number for the user. On success, the cached user profile data is updated.
  1240. ///
  1241. /// Invoked asynchronously on the global work queue in the future.
  1242. /// - Parameter credential: The new phone number credential corresponding to the phone
  1243. /// number to be added to the Firebase account. If a phone number is already linked to the
  1244. /// account, this new phone number will replace it.
  1245. /// - Parameter isLinkOperation: Boolean value indicating whether or not this is a link
  1246. /// operation.
  1247. /// - Parameter completion: Optionally; the block invoked when the user profile change has
  1248. /// finished.
  1249. private func internalUpdateOrLinkPhoneNumber(credential: PhoneAuthCredential,
  1250. isLinkOperation: Bool,
  1251. completion: @escaping @Sendable (Error?) -> Void) {
  1252. internalGetToken(backend: backend) { accessToken, error in
  1253. if let error {
  1254. completion(error)
  1255. return
  1256. }
  1257. guard let accessToken = accessToken else {
  1258. fatalError("Auth Internal Error: Both accessToken and error are nil")
  1259. }
  1260. guard let configuration = self.auth?.requestConfiguration else {
  1261. fatalError("Auth Internal Error: nil value for VerifyPhoneNumberRequest initializer")
  1262. }
  1263. switch credential.credentialKind {
  1264. case .phoneNumber: fatalError("Internal Error: Missing verificationCode")
  1265. case let .verification(verificationID, code):
  1266. let operation = isLinkOperation ? AuthOperationType.link : AuthOperationType.update
  1267. let request = VerifyPhoneNumberRequest(verificationID: verificationID,
  1268. verificationCode: code,
  1269. operation: operation,
  1270. requestConfiguration: configuration)
  1271. request.accessToken = accessToken
  1272. Task {
  1273. do {
  1274. let verifyResponse = try await self.backend.call(with: request)
  1275. guard let idToken = verifyResponse.idToken,
  1276. let refreshToken = verifyResponse.refreshToken else {
  1277. fatalError("Internal Auth Error: missing token in internalUpdateOrLinkPhoneNumber")
  1278. }
  1279. // Update the new token and refresh user info again.
  1280. self.tokenService = SecureTokenService(
  1281. withRequestConfiguration: configuration,
  1282. accessToken: idToken,
  1283. accessTokenExpirationDate: verifyResponse.approximateExpirationDate,
  1284. refreshToken: refreshToken
  1285. )
  1286. // Get account info to update cached user info.
  1287. self.getAccountInfoRefreshingCache { user, error in
  1288. if let error {
  1289. self.signOutIfTokenIsInvalid(withError: error)
  1290. completion(error)
  1291. return
  1292. }
  1293. self.isAnonymous = false
  1294. if let error = self.updateKeychain() {
  1295. completion(error)
  1296. return
  1297. }
  1298. completion(nil)
  1299. }
  1300. } catch {
  1301. self.signOutIfTokenIsInvalid(withError: error)
  1302. completion(error)
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. #endif
  1309. private func link(withEmail email: String,
  1310. password: String,
  1311. authResult: AuthDataResult,
  1312. _ completion: (@Sendable (AuthDataResult?, Error?) -> Void)?) {
  1313. internalGetToken(backend: backend) { accessToken, error in
  1314. guard let requestConfiguration = self.auth?.requestConfiguration else {
  1315. fatalError("Internal auth error: missing auth on User")
  1316. }
  1317. let request = SignUpNewUserRequest(email: email,
  1318. password: password,
  1319. displayName: nil,
  1320. idToken: accessToken,
  1321. requestConfiguration: requestConfiguration)
  1322. Task {
  1323. do {
  1324. #if os(iOS)
  1325. guard let auth = self.auth else {
  1326. fatalError("Internal Auth error: missing auth instance on user")
  1327. }
  1328. let response = try await auth.injectRecaptcha(request: request,
  1329. action: AuthRecaptchaAction
  1330. .signUpPassword)
  1331. #else
  1332. let response = try await self.backend.call(with: request)
  1333. #endif
  1334. guard let refreshToken = response.refreshToken,
  1335. let idToken = response.idToken else {
  1336. fatalError("Internal auth error: Invalid SignUpNewUserResponse")
  1337. }
  1338. // Update the new token and refresh user info again.
  1339. try await self.updateTokenAndRefreshUser(
  1340. idToken: idToken,
  1341. refreshToken: refreshToken,
  1342. expirationDate: response.approximateExpirationDate,
  1343. requestConfiguration: requestConfiguration
  1344. )
  1345. User.callInMainThreadWithAuthDataResultAndError(
  1346. callback: completion,
  1347. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1348. error: nil
  1349. )
  1350. } catch {
  1351. self.signOutIfTokenIsInvalid(withError: error)
  1352. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1353. result: nil, error: error)
  1354. }
  1355. }
  1356. }
  1357. }
  1358. private func link(withEmailCredential emailCredential: EmailAuthCredential,
  1359. completion: (@Sendable (AuthDataResult?, Error?) -> Void)?) {
  1360. if hasEmailPasswordCredential {
  1361. User.callInMainThreadWithAuthDataResultAndError(
  1362. callback: completion,
  1363. result: nil,
  1364. error: AuthErrorUtils
  1365. .providerAlreadyLinkedError()
  1366. )
  1367. return
  1368. }
  1369. switch emailCredential.emailType {
  1370. case let .password(password):
  1371. let result = AuthDataResult(withUser: self, additionalUserInfo: nil)
  1372. link(withEmail: emailCredential.email, password: password, authResult: result, completion)
  1373. case let .link(link):
  1374. internalGetToken(backend: backend) { accessToken, error in
  1375. var queryItems = AuthWebUtils.parseURL(link)
  1376. if link.count == 0 {
  1377. if let urlComponents = URLComponents(string: link),
  1378. let query = urlComponents.query {
  1379. queryItems = AuthWebUtils.parseURL(query)
  1380. }
  1381. }
  1382. guard let actionCode = queryItems["oobCode"],
  1383. let requestConfiguration = self.auth?.requestConfiguration else {
  1384. fatalError("Internal Auth Error: Missing oobCode or requestConfiguration")
  1385. }
  1386. let request = EmailLinkSignInRequest(email: emailCredential.email,
  1387. oobCode: actionCode,
  1388. requestConfiguration: requestConfiguration)
  1389. request.idToken = accessToken
  1390. Task {
  1391. do {
  1392. let response = try await self.backend.call(with: request)
  1393. guard let idToken = response.idToken,
  1394. let refreshToken = response.refreshToken else {
  1395. fatalError("Internal Auth Error: missing token in EmailLinkSignInResponse")
  1396. }
  1397. try await self.updateTokenAndRefreshUser(
  1398. idToken: idToken,
  1399. refreshToken: refreshToken,
  1400. expirationDate: response.approximateExpirationDate,
  1401. requestConfiguration: requestConfiguration
  1402. )
  1403. User.callInMainThreadWithAuthDataResultAndError(
  1404. callback: completion,
  1405. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1406. error: nil
  1407. )
  1408. } catch {
  1409. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1410. result: nil,
  1411. error: error)
  1412. }
  1413. }
  1414. }
  1415. }
  1416. }
  1417. #if !os(watchOS)
  1418. private func link(withGameCenterCredential gameCenterCredential: GameCenterAuthCredential,
  1419. completion: (@Sendable (AuthDataResult?, Error?) -> Void)?) {
  1420. internalGetToken(backend: backend) { accessToken, error in
  1421. guard let requestConfiguration = self.auth?.requestConfiguration,
  1422. let publicKeyURL = gameCenterCredential.publicKeyURL,
  1423. let signature = gameCenterCredential.signature,
  1424. let salt = gameCenterCredential.salt else {
  1425. fatalError("Internal Auth Error: Nil value field for SignInWithGameCenterRequest")
  1426. }
  1427. let request = SignInWithGameCenterRequest(playerID: gameCenterCredential.playerID,
  1428. teamPlayerID: gameCenterCredential.teamPlayerID,
  1429. gamePlayerID: gameCenterCredential.gamePlayerID,
  1430. publicKeyURL: publicKeyURL,
  1431. signature: signature,
  1432. salt: salt,
  1433. timestamp: gameCenterCredential.timestamp,
  1434. displayName: gameCenterCredential.displayName,
  1435. requestConfiguration: requestConfiguration)
  1436. request.accessToken = accessToken
  1437. Task {
  1438. do {
  1439. let response = try await self.backend.call(with: request)
  1440. guard let idToken = response.idToken,
  1441. let refreshToken = response.refreshToken else {
  1442. fatalError("Internal Auth Error: missing token in link(withGameCredential")
  1443. }
  1444. try await self.updateTokenAndRefreshUser(
  1445. idToken: idToken,
  1446. refreshToken: refreshToken,
  1447. expirationDate: response.approximateExpirationDate,
  1448. requestConfiguration: requestConfiguration
  1449. )
  1450. User.callInMainThreadWithAuthDataResultAndError(
  1451. callback: completion,
  1452. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1453. error: nil
  1454. )
  1455. } catch {
  1456. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1457. result: nil,
  1458. error: error)
  1459. }
  1460. }
  1461. }
  1462. }
  1463. #endif
  1464. #if os(iOS)
  1465. private func link(withPhoneCredential phoneCredential: PhoneAuthCredential,
  1466. completion: (@Sendable (AuthDataResult?, Error?) -> Void)?) {
  1467. internalUpdateOrLinkPhoneNumber(credential: phoneCredential,
  1468. isLinkOperation: true) { error in
  1469. if let error {
  1470. User.callInMainThreadWithAuthDataResultAndError(
  1471. callback: completion,
  1472. result: nil,
  1473. error: error
  1474. )
  1475. } else {
  1476. let result = AuthDataResult(withUser: self, additionalUserInfo: nil)
  1477. User.callInMainThreadWithAuthDataResultAndError(
  1478. callback: completion,
  1479. result: result,
  1480. error: nil
  1481. )
  1482. }
  1483. }
  1484. }
  1485. #endif
  1486. // Update the new token and refresh user info again.
  1487. private func updateTokenAndRefreshUser(idToken: String,
  1488. refreshToken: String,
  1489. expirationDate: Date?,
  1490. requestConfiguration: AuthRequestConfiguration) async throws {
  1491. return try await userProfileUpdate
  1492. .updateTokenAndRefreshUser(
  1493. user: self,
  1494. idToken: idToken,
  1495. refreshToken: refreshToken,
  1496. expirationDate: expirationDate
  1497. )
  1498. }
  1499. /// Signs out this user if the user or the token is invalid.
  1500. /// - Parameter error: The error from the server.
  1501. func signOutIfTokenIsInvalid(withError error: Error) {
  1502. let code = (error as NSError).code
  1503. if code == AuthErrorCode.userNotFound.rawValue ||
  1504. code == AuthErrorCode.userDisabled.rawValue ||
  1505. code == AuthErrorCode.invalidUserToken.rawValue ||
  1506. code == AuthErrorCode.userTokenExpired.rawValue {
  1507. AuthLog.logNotice(code: "I-AUT000016",
  1508. message: "Invalid user token detected, user is automatically signed out.")
  1509. try? auth?.signOutByForce(withUserID: uid)
  1510. }
  1511. }
  1512. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1513. /// - Parameter callback: The block to invoke when the token is available. Invoked asynchronously
  1514. /// on the global work thread in the future.
  1515. func internalGetToken(forceRefresh: Bool = false,
  1516. backend: AuthBackend,
  1517. callback: @escaping @Sendable (String?, Error?) -> Void) {
  1518. Task {
  1519. do {
  1520. let token = try await internalGetTokenAsync(forceRefresh: forceRefresh, backend: backend)
  1521. callback(token, nil)
  1522. } catch {
  1523. callback(nil, error)
  1524. }
  1525. }
  1526. }
  1527. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1528. /// - Parameter forceRefresh
  1529. func internalGetTokenAsync(forceRefresh: Bool = false,
  1530. backend: AuthBackend) async throws -> String {
  1531. var keychainError = false
  1532. do {
  1533. let (token, tokenUpdated) = try await tokenService.fetchAccessToken(
  1534. forcingRefresh: forceRefresh, backend: backend
  1535. )
  1536. if tokenUpdated {
  1537. if let error = updateKeychain() {
  1538. keychainError = true
  1539. throw error
  1540. }
  1541. }
  1542. return token!
  1543. } catch {
  1544. if !keychainError {
  1545. signOutIfTokenIsInvalid(withError: error)
  1546. }
  1547. throw error
  1548. }
  1549. }
  1550. /// Updates the keychain for user token or info changes.
  1551. /// - Returns: An `Error` on failure.
  1552. func updateKeychain() -> Error? {
  1553. return auth?.updateKeychain(withUser: self)
  1554. }
  1555. /// Calls a callback in main thread with error.
  1556. /// - Parameter callback: The callback to be called in main thread.
  1557. /// - Parameter error: The error to pass to callback.
  1558. class func callInMainThreadWithError(callback: (@MainActor (Error?) -> Void)?, error: Error?) {
  1559. if let callback {
  1560. DispatchQueue.main.async {
  1561. callback(error)
  1562. }
  1563. }
  1564. }
  1565. /// Calls a callback in main thread with user and error.
  1566. /// - Parameter callback: The callback to be called in main thread.
  1567. /// - Parameter user: The user to pass to callback if there is no error.
  1568. /// - Parameter error: The error to pass to callback.
  1569. private class func callInMainThreadWithUserAndError(callback: (@MainActor (User?, Error?)
  1570. -> Void)?,
  1571. user: User,
  1572. error: Error?) {
  1573. if let callback {
  1574. DispatchQueue.main.async {
  1575. callback((error != nil) ? nil : user, error)
  1576. }
  1577. }
  1578. }
  1579. /// Calls a callback in main thread with user and error.
  1580. /// - Parameter callback: The callback to be called in main thread.
  1581. private class func callInMainThreadWithAuthDataResultAndError(callback: (
  1582. @MainActor (AuthDataResult?, Error?) -> Void
  1583. )?,
  1584. result: AuthDataResult? = nil,
  1585. error: Error? = nil) {
  1586. if let callback {
  1587. DispatchQueue.main.async {
  1588. callback(result, error)
  1589. }
  1590. }
  1591. }
  1592. // MARK: NSSecureCoding
  1593. private let kUserIDCodingKey = "userID"
  1594. private let kHasEmailPasswordCredentialCodingKey = "hasEmailPassword"
  1595. private let kAnonymousCodingKey = "anonymous"
  1596. private let kEmailCodingKey = "email"
  1597. private let kPhoneNumberCodingKey = "phoneNumber"
  1598. private let kEmailVerifiedCodingKey = "emailVerified"
  1599. private let kDisplayNameCodingKey = "displayName"
  1600. private let kPhotoURLCodingKey = "photoURL"
  1601. private let kProviderDataKey = "providerData"
  1602. private let kAPIKeyCodingKey = "APIKey"
  1603. private let kFirebaseAppIDCodingKey = "firebaseAppID"
  1604. private let kTokenServiceCodingKey = "tokenService"
  1605. private let kMetadataCodingKey = "metadata"
  1606. private let kMultiFactorCodingKey = "multiFactor"
  1607. private let kTenantIDCodingKey = "tenantID"
  1608. public static let supportsSecureCoding = true
  1609. public func encode(with coder: NSCoder) {
  1610. coder.encode(uid, forKey: kUserIDCodingKey)
  1611. coder.encode(isAnonymous, forKey: kAnonymousCodingKey)
  1612. coder.encode(hasEmailPasswordCredential, forKey: kHasEmailPasswordCredentialCodingKey)
  1613. coder.encode(providerDataRaw, forKey: kProviderDataKey)
  1614. coder.encode(email, forKey: kEmailCodingKey)
  1615. coder.encode(phoneNumber, forKey: kPhoneNumberCodingKey)
  1616. coder.encode(isEmailVerified, forKey: kEmailVerifiedCodingKey)
  1617. coder.encode(photoURL, forKey: kPhotoURLCodingKey)
  1618. coder.encode(displayName, forKey: kDisplayNameCodingKey)
  1619. coder.encode(metadata, forKey: kMetadataCodingKey)
  1620. coder.encode(tenantID, forKey: kTenantIDCodingKey)
  1621. if let auth {
  1622. coder.encode(auth.requestConfiguration.apiKey, forKey: kAPIKeyCodingKey)
  1623. coder.encode(auth.requestConfiguration.appID, forKey: kFirebaseAppIDCodingKey)
  1624. }
  1625. coder.encode(tokenService, forKey: kTokenServiceCodingKey)
  1626. #if os(iOS)
  1627. coder.encode(multiFactor, forKey: kMultiFactorCodingKey)
  1628. #endif
  1629. }
  1630. public required init?(coder: NSCoder) {
  1631. guard let userID = coder.decodeObject(of: NSString.self, forKey: kUserIDCodingKey) as? String,
  1632. let tokenService = coder.decodeObject(of: SecureTokenService.self,
  1633. forKey: kTokenServiceCodingKey) else {
  1634. return nil
  1635. }
  1636. let anonymous = coder.decodeBool(forKey: kAnonymousCodingKey)
  1637. let hasEmailPasswordCredential = coder.decodeBool(forKey: kHasEmailPasswordCredentialCodingKey)
  1638. let displayName = coder.decodeObject(
  1639. of: NSString.self,
  1640. forKey: kDisplayNameCodingKey
  1641. ) as? String
  1642. let photoURL = coder.decodeObject(of: NSURL.self, forKey: kPhotoURLCodingKey) as? URL
  1643. let email = coder.decodeObject(of: NSString.self, forKey: kEmailCodingKey) as? String
  1644. let phoneNumber = coder.decodeObject(
  1645. of: NSString.self,
  1646. forKey: kPhoneNumberCodingKey
  1647. ) as? String
  1648. let emailVerified = coder.decodeBool(forKey: kEmailVerifiedCodingKey)
  1649. let classes = [NSDictionary.self, NSString.self, UserInfoImpl.self]
  1650. let providerData = coder.decodeObject(of: classes, forKey: kProviderDataKey)
  1651. as? [String: UserInfoImpl]
  1652. let metadata = coder.decodeObject(of: UserMetadata.self, forKey: kMetadataCodingKey)
  1653. let tenantID = coder.decodeObject(of: NSString.self, forKey: kTenantIDCodingKey) as? String
  1654. #if os(iOS)
  1655. let multiFactor = coder.decodeObject(of: MultiFactor.self, forKey: kMultiFactorCodingKey)
  1656. #endif
  1657. self.tokenService = tokenService
  1658. uid = userID
  1659. isAnonymous = anonymous
  1660. self.hasEmailPasswordCredential = hasEmailPasswordCredential
  1661. self.email = email
  1662. isEmailVerified = emailVerified
  1663. self.displayName = displayName
  1664. self.photoURL = photoURL
  1665. providerDataRaw = providerData ?? [:]
  1666. self.phoneNumber = phoneNumber
  1667. self.metadata = metadata ?? UserMetadata(withCreationDate: nil, lastSignInDate: nil)
  1668. self.tenantID = tenantID
  1669. // Note, in practice, the caller will set the `auth` property of this user
  1670. // instance which will as a side-effect overwrite the request configuration.
  1671. // The assignment here is a best-effort placeholder.
  1672. let apiKey = coder.decodeObject(of: NSString.self, forKey: kAPIKeyCodingKey) as? String
  1673. let appID = coder.decodeObject(
  1674. of: NSString.self,
  1675. forKey: kFirebaseAppIDCodingKey
  1676. ) as? String
  1677. requestConfiguration = AuthRequestConfiguration(apiKey: apiKey ?? "", appID: appID ?? "")
  1678. // This property will be overwritten later via the `user.auth` property update. For now, a
  1679. // placeholder is set as the property update should happen right after this initializer.
  1680. backend = AuthBackend(rpcIssuer: AuthBackendRPCIssuer())
  1681. userProfileUpdate = UserProfileUpdate()
  1682. #if os(iOS)
  1683. self.multiFactor = multiFactor ?? MultiFactor()
  1684. super.init()
  1685. multiFactor?.user = self
  1686. #endif
  1687. }
  1688. }