User.swift 86 KB

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