User.swift 76 KB

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