User.swift 76 KB

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