User.swift 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  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 credential: 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. /// - Returns: An AuthDataResult.
  733. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  734. @discardableResult
  735. open func link(with provider: FederatedAuthProvider,
  736. uiDelegate: AuthUIDelegate?) async throws -> AuthDataResult {
  737. return try await withCheckedThrowingContinuation { continuation in
  738. self.link(with: provider, uiDelegate: uiDelegate) { result, error in
  739. if let result {
  740. continuation.resume(returning: result)
  741. } else if let error {
  742. continuation.resume(throwing: error)
  743. }
  744. }
  745. }
  746. }
  747. #endif
  748. /// Disassociates a user account from a third-party identity provider with this user.
  749. ///
  750. /// Invoked asynchronously on the main thread in the future.
  751. ///
  752. /// Possible error codes:
  753. /// * `AuthErrorCodeNoSuchProvider` - Indicates an attempt to unlink a provider
  754. /// that is not linked to the account.
  755. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  756. /// operation that requires a recent login from the user. This error indicates the user
  757. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  758. /// `reauthenticate(with:)`.
  759. /// - Parameter provider: The provider ID of the provider to unlink.
  760. /// - Parameter completion: Optionally; the block invoked when the unlinking is complete, or
  761. /// fails.
  762. @objc open func unlink(fromProvider provider: String,
  763. completion: ((User?, Error?) -> Void)? = nil) {
  764. Task {
  765. do {
  766. let user = try await unlink(fromProvider: provider)
  767. await MainActor.run {
  768. completion?(user, nil)
  769. }
  770. } catch {
  771. await MainActor.run {
  772. completion?(nil, error)
  773. }
  774. }
  775. }
  776. }
  777. /// Disassociates a user account from a third-party identity provider with this user.
  778. ///
  779. /// Invoked asynchronously on the main thread in the future.
  780. ///
  781. /// Possible error codes:
  782. /// * `AuthErrorCodeNoSuchProvider` - Indicates an attempt to unlink a provider
  783. /// that is not linked to the account.
  784. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  785. /// operation that requires a recent login from the user. This error indicates the user
  786. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  787. /// `reauthenticate(with:)`.
  788. /// - Parameter provider: The provider ID of the provider to unlink.
  789. /// - Returns: The user.
  790. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  791. open func unlink(fromProvider provider: String) async throws -> User {
  792. return try await userProfileUpdate.unlink(user: self, fromProvider: provider)
  793. }
  794. /// Initiates email verification for the user.
  795. ///
  796. /// Possible error codes:
  797. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  798. /// sent in the request.
  799. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  800. /// the console for this action.
  801. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  802. /// sending update email.
  803. /// * `AuthErrorCodeUserNotFound` - Indicates the user account was not found.
  804. /// - Parameter completion: Optionally; the block invoked when the request to send an email
  805. /// verification is complete, or fails. Invoked asynchronously on the main thread in the future.
  806. @objc(sendEmailVerificationWithCompletion:)
  807. open func __sendEmailVerification(withCompletion completion: ((Error?) -> Void)?) {
  808. sendEmailVerification(completion: completion)
  809. }
  810. /// Initiates email verification for the user.
  811. ///
  812. /// Possible error codes:
  813. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  814. /// sent in the request.
  815. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  816. /// the console for this action.
  817. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  818. /// sending update email.
  819. /// * `AuthErrorCodeUserNotFound` - Indicates the user account was not found.
  820. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  821. /// handling action codes.
  822. /// - Parameter completion: Optionally; the block invoked when the request to send an email
  823. /// verification is complete, or fails. Invoked asynchronously on the main thread in the future.
  824. @objc(sendEmailVerificationWithActionCodeSettings:completion:)
  825. open func sendEmailVerification(with actionCodeSettings: ActionCodeSettings? = nil,
  826. completion: ((Error?) -> Void)? = nil) {
  827. kAuthGlobalWorkQueue.async {
  828. self.internalGetToken { accessToken, error in
  829. if let error {
  830. User.callInMainThreadWithError(callback: completion, error: error)
  831. return
  832. }
  833. guard let accessToken else {
  834. fatalError("Internal Error: Both error and accessToken are nil.")
  835. }
  836. guard let requestConfiguration = self.auth?.requestConfiguration else {
  837. fatalError("Internal Error: Unexpected nil requestConfiguration.")
  838. }
  839. let request = GetOOBConfirmationCodeRequest.verifyEmailRequest(
  840. accessToken: accessToken,
  841. actionCodeSettings: actionCodeSettings,
  842. requestConfiguration: requestConfiguration
  843. )
  844. Task {
  845. do {
  846. let _ = try await AuthBackend.call(with: request)
  847. User.callInMainThreadWithError(callback: completion, error: nil)
  848. } catch {
  849. self.signOutIfTokenIsInvalid(withError: error)
  850. User.callInMainThreadWithError(callback: completion, error: error)
  851. }
  852. }
  853. }
  854. }
  855. }
  856. /// Initiates email verification for the user.
  857. ///
  858. /// Possible error codes:
  859. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  860. /// sent in the request.
  861. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  862. /// the console for this action.
  863. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  864. /// sending update email.
  865. /// * `AuthErrorCodeUserNotFound` - Indicates the user account was not found.
  866. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  867. /// handling action codes. The default value is `nil`.
  868. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  869. open func sendEmailVerification(with actionCodeSettings: ActionCodeSettings? = nil) async throws {
  870. return try await withCheckedThrowingContinuation { continuation in
  871. self.sendEmailVerification(with: actionCodeSettings) { error in
  872. if let error {
  873. continuation.resume(throwing: error)
  874. } else {
  875. continuation.resume()
  876. }
  877. }
  878. }
  879. }
  880. /// Deletes the user account (also signs out the user, if this was the current user).
  881. ///
  882. /// Possible error codes:
  883. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  884. /// operation that requires a recent login from the user. This error indicates the user
  885. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  886. /// `reauthenticate(with:)`.
  887. /// - Parameter completion: Optionally; the block invoked when the request to delete the account
  888. /// is complete, or fails. Invoked asynchronously on the main thread in the future.
  889. @objc open func delete(completion: ((Error?) -> Void)? = nil) {
  890. kAuthGlobalWorkQueue.async {
  891. self.internalGetToken { accessToken, error in
  892. if let error {
  893. User.callInMainThreadWithError(callback: completion, error: error)
  894. return
  895. }
  896. guard let accessToken else {
  897. fatalError("Auth Internal Error: Both error and accessToken are nil.")
  898. }
  899. guard let requestConfiguration = self.auth?.requestConfiguration else {
  900. fatalError("Auth Internal Error: Unexpected nil requestConfiguration.")
  901. }
  902. let request = DeleteAccountRequest(localID: self.uid, accessToken: accessToken,
  903. requestConfiguration: requestConfiguration)
  904. Task {
  905. do {
  906. let _ = try await AuthBackend.call(with: request)
  907. try self.auth?.signOutByForce(withUserID: self.uid)
  908. User.callInMainThreadWithError(callback: completion, error: nil)
  909. } catch {
  910. User.callInMainThreadWithError(callback: completion, error: error)
  911. }
  912. }
  913. }
  914. }
  915. }
  916. /// Deletes the user account (also signs out the user, if this was the current user).
  917. ///
  918. /// Possible error codes:
  919. /// * `AuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive
  920. /// operation that requires a recent login from the user. This error indicates the user
  921. /// has not signed in recently enough. To resolve, reauthenticate the user by calling
  922. /// `reauthenticate(with:)`.
  923. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  924. open func delete() async throws {
  925. return try await withCheckedThrowingContinuation { continuation in
  926. self.delete { error in
  927. if let error {
  928. continuation.resume(throwing: error)
  929. } else {
  930. continuation.resume()
  931. }
  932. }
  933. }
  934. }
  935. /// Send an email to verify the ownership of the account then update to the new email.
  936. /// - Parameter email: The email to be updated to.
  937. /// - Parameter completion: Optionally; the block invoked when the request to send the
  938. /// verification email is complete, or fails.
  939. @objc(sendEmailVerificationBeforeUpdatingEmail:completion:)
  940. open func __sendEmailVerificationBeforeUpdating(email: String, completion: ((Error?) -> Void)?) {
  941. sendEmailVerification(beforeUpdatingEmail: email, completion: completion)
  942. }
  943. /// Send an email to verify the ownership of the account then update to the new email.
  944. /// - Parameter email: The email to be updated to.
  945. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  946. /// handling action codes.
  947. /// - Parameter completion: Optionally; the block invoked when the request to send the
  948. /// verification email is complete, or fails.
  949. @objc open func sendEmailVerification(beforeUpdatingEmail email: String,
  950. actionCodeSettings: ActionCodeSettings? = nil,
  951. completion: ((Error?) -> Void)? = nil) {
  952. kAuthGlobalWorkQueue.async {
  953. self.internalGetToken { accessToken, error in
  954. if let error {
  955. User.callInMainThreadWithError(callback: completion, error: error)
  956. return
  957. }
  958. guard let accessToken else {
  959. fatalError("Internal Error: Both error and accessToken are nil.")
  960. }
  961. guard let requestConfiguration = self.auth?.requestConfiguration else {
  962. fatalError("Internal Error: Unexpected nil requestConfiguration.")
  963. }
  964. let request = GetOOBConfirmationCodeRequest.verifyBeforeUpdateEmail(
  965. accessToken: accessToken,
  966. newEmail: email,
  967. actionCodeSettings: actionCodeSettings,
  968. requestConfiguration: requestConfiguration
  969. )
  970. Task {
  971. do {
  972. let _ = try await AuthBackend.call(with: request)
  973. User.callInMainThreadWithError(callback: completion, error: nil)
  974. } catch {
  975. User.callInMainThreadWithError(callback: completion, error: error)
  976. }
  977. }
  978. }
  979. }
  980. }
  981. /// Send an email to verify the ownership of the account then update to the new email.
  982. /// - Parameter newEmail: The email to be updated to.
  983. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  984. /// handling action codes.
  985. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  986. open func sendEmailVerification(beforeUpdatingEmail newEmail: String,
  987. actionCodeSettings: ActionCodeSettings? = nil) async throws {
  988. return try await withCheckedThrowingContinuation { continuation in
  989. self.sendEmailVerification(beforeUpdatingEmail: newEmail,
  990. actionCodeSettings: actionCodeSettings) { error in
  991. if let error {
  992. continuation.resume(throwing: error)
  993. } else {
  994. continuation.resume()
  995. }
  996. }
  997. }
  998. }
  999. // MARK: Internal implementations below
  1000. func rawAccessToken() -> String {
  1001. return tokenService.accessToken
  1002. }
  1003. func accessTokenExpirationDate() -> Date? {
  1004. return tokenService.accessTokenExpirationDate
  1005. }
  1006. init(withTokenService tokenService: SecureTokenService) {
  1007. providerDataRaw = [:]
  1008. userProfileUpdate = UserProfileUpdate()
  1009. self.tokenService = tokenService
  1010. isAnonymous = false
  1011. isEmailVerified = false
  1012. metadata = UserMetadata(withCreationDate: nil, lastSignInDate: nil)
  1013. tenantID = nil
  1014. #if os(iOS)
  1015. multiFactor = MultiFactor(withMFAEnrollments: [])
  1016. #endif
  1017. uid = ""
  1018. hasEmailPasswordCredential = false
  1019. requestConfiguration = AuthRequestConfiguration(apiKey: "", appID: "")
  1020. }
  1021. class func retrieveUser(withAuth auth: Auth,
  1022. accessToken: String?,
  1023. accessTokenExpirationDate: Date?,
  1024. refreshToken: String?,
  1025. anonymous: Bool) async throws -> User {
  1026. guard let accessToken = accessToken,
  1027. let refreshToken = refreshToken else {
  1028. fatalError("Internal FirebaseAuth Error: nil token")
  1029. }
  1030. let tokenService = SecureTokenService(withRequestConfiguration: auth.requestConfiguration,
  1031. accessToken: accessToken,
  1032. accessTokenExpirationDate: accessTokenExpirationDate,
  1033. refreshToken: refreshToken)
  1034. let user = User(withTokenService: tokenService)
  1035. user.auth = auth
  1036. user.tenantID = auth.tenantID
  1037. user.requestConfiguration = auth.requestConfiguration
  1038. let accessToken2 = try await user.internalGetTokenAsync()
  1039. let getAccountInfoRequest = GetAccountInfoRequest(
  1040. accessToken: accessToken2,
  1041. requestConfiguration: user.requestConfiguration
  1042. )
  1043. let response = try await AuthBackend.call(with: getAccountInfoRequest)
  1044. user.isAnonymous = anonymous
  1045. user.update(withGetAccountInfoResponse: response)
  1046. return user
  1047. }
  1048. @objc open var providerID: String {
  1049. return "Firebase"
  1050. }
  1051. /// The provider's user ID for the user.
  1052. @objc open var uid: String
  1053. /// The name of the user.
  1054. @objc open var displayName: String?
  1055. /// The URL of the user's profile photo.
  1056. @objc open var photoURL: URL?
  1057. /// The user's email address.
  1058. @objc open var email: String?
  1059. /// A phone number associated with the user.
  1060. ///
  1061. /// This property is only available for users authenticated via phone number auth.
  1062. @objc open var phoneNumber: String?
  1063. /// Whether or not the user can be authenticated by using Firebase email and password.
  1064. var hasEmailPasswordCredential: Bool
  1065. /// Used to serialize the update profile calls.
  1066. private let userProfileUpdate: UserProfileUpdate
  1067. /// A strong reference to a requestConfiguration instance associated with this user instance.
  1068. var requestConfiguration: AuthRequestConfiguration
  1069. /// A secure token service associated with this user. For performing token exchanges and
  1070. /// refreshing access tokens.
  1071. var tokenService: SecureTokenService
  1072. private weak var _auth: Auth?
  1073. /// A weak reference to an `Auth` instance associated with this instance.
  1074. weak var auth: Auth? {
  1075. set {
  1076. _auth = newValue
  1077. guard let requestConfiguration = auth?.requestConfiguration else {
  1078. fatalError("Firebase Auth Internal Error: nil requestConfiguration when initializing User")
  1079. }
  1080. tokenService.requestConfiguration = requestConfiguration
  1081. self.requestConfiguration = requestConfiguration
  1082. }
  1083. get { return _auth }
  1084. }
  1085. // MARK: Private functions
  1086. private func updateEmail(email: String?,
  1087. password: String?,
  1088. callback: @escaping (Error?) -> Void) {
  1089. let hadEmailPasswordCredential = hasEmailPasswordCredential
  1090. executeUserUpdateWithChanges(changeBlock: { user, request in
  1091. if let email {
  1092. request.email = email
  1093. }
  1094. if let password {
  1095. request.password = password
  1096. }
  1097. }) { error in
  1098. if let error {
  1099. callback(error)
  1100. return
  1101. }
  1102. if let email {
  1103. self.email = email
  1104. }
  1105. if self.email != nil {
  1106. if !hadEmailPasswordCredential {
  1107. // The list of providers need to be updated for the newly added email-password provider.
  1108. Task {
  1109. do {
  1110. let accessToken = try await self.internalGetTokenAsync()
  1111. if let requestConfiguration = self.auth?.requestConfiguration {
  1112. let getAccountInfoRequest = GetAccountInfoRequest(accessToken: accessToken,
  1113. requestConfiguration: requestConfiguration)
  1114. do {
  1115. let accountInfoResponse = try await AuthBackend.call(with: getAccountInfoRequest)
  1116. if let users = accountInfoResponse.users {
  1117. for userAccountInfo in users {
  1118. // Set the account to non-anonymous if there are any providers, even if
  1119. // they're not email/password ones.
  1120. if let providerUsers = userAccountInfo.providerUserInfo {
  1121. if providerUsers.count > 0 {
  1122. self.isAnonymous = false
  1123. for providerUserInfo in providerUsers {
  1124. if providerUserInfo.providerID == EmailAuthProvider.id {
  1125. self.hasEmailPasswordCredential = true
  1126. break
  1127. }
  1128. }
  1129. }
  1130. }
  1131. }
  1132. }
  1133. self.update(withGetAccountInfoResponse: accountInfoResponse)
  1134. if let error = self.updateKeychain() {
  1135. callback(error)
  1136. return
  1137. }
  1138. callback(nil)
  1139. } catch {
  1140. self.signOutIfTokenIsInvalid(withError: error)
  1141. callback(error)
  1142. }
  1143. }
  1144. } catch {
  1145. callback(error)
  1146. }
  1147. }
  1148. return
  1149. }
  1150. }
  1151. if let error = self.updateKeychain() {
  1152. callback(error)
  1153. return
  1154. }
  1155. callback(nil)
  1156. }
  1157. }
  1158. /// Performs a setAccountInfo request by mutating the results of a getAccountInfo response,
  1159. /// atomically in regards to other calls to this method.
  1160. /// - Parameter changeBlock: A block responsible for mutating a template `SetAccountInfoRequest`
  1161. /// - Parameter callback: A block to invoke when the change is complete. Invoked asynchronously on
  1162. /// the auth global work queue in the future.
  1163. func executeUserUpdateWithChanges(changeBlock: @escaping (GetAccountInfoResponse.User,
  1164. SetAccountInfoRequest) -> Void,
  1165. callback: @escaping (Error?) -> Void) {
  1166. Task {
  1167. do {
  1168. try await userProfileUpdate.executeUserUpdateWithChanges(user: self,
  1169. changeBlock: changeBlock)
  1170. await MainActor.run {
  1171. callback(nil)
  1172. }
  1173. } catch {
  1174. await MainActor.run {
  1175. callback(error)
  1176. }
  1177. }
  1178. }
  1179. }
  1180. /// Gets the users' account data from the server, updating our local values.
  1181. /// - Parameter callback: Invoked when the request to getAccountInfo has completed, or when an
  1182. /// error has been detected. Invoked asynchronously on the auth global work queue in the future.
  1183. func getAccountInfoRefreshingCache(callback: @escaping (GetAccountInfoResponse.User?,
  1184. Error?) -> Void) {
  1185. Task {
  1186. do {
  1187. let responseUser = try await userProfileUpdate.getAccountInfoRefreshingCache(self)
  1188. await MainActor.run {
  1189. callback(responseUser, nil)
  1190. }
  1191. } catch {
  1192. await MainActor.run {
  1193. callback(nil, error)
  1194. }
  1195. }
  1196. }
  1197. }
  1198. func update(withGetAccountInfoResponse response: GetAccountInfoResponse) {
  1199. guard let user = response.users?.first else {
  1200. // Silent fallthrough in ObjC code.
  1201. AuthLog.logWarning(code: "I-AUT000016", message: "Missing user in GetAccountInfoResponse")
  1202. return
  1203. }
  1204. uid = user.localID ?? ""
  1205. email = user.email
  1206. isEmailVerified = user.emailVerified
  1207. displayName = user.displayName
  1208. photoURL = user.photoURL
  1209. phoneNumber = user.phoneNumber
  1210. hasEmailPasswordCredential = user.passwordHash != nil && user.passwordHash!.count > 0
  1211. metadata = UserMetadata(withCreationDate: user.creationDate,
  1212. lastSignInDate: user.lastLoginDate)
  1213. var providerData: [String: UserInfoImpl] = [:]
  1214. if let providerUserInfos = user.providerUserInfo {
  1215. for providerUserInfo in providerUserInfos {
  1216. let userInfo = UserInfoImpl.userInfo(
  1217. withGetAccountInfoResponseProviderUserInfo: providerUserInfo
  1218. )
  1219. if let providerID = providerUserInfo.providerID {
  1220. providerData[providerID] = userInfo
  1221. }
  1222. }
  1223. }
  1224. providerDataRaw = providerData
  1225. #if os(iOS)
  1226. if let enrollments = user.mfaEnrollments {
  1227. multiFactor = MultiFactor(withMFAEnrollments: enrollments)
  1228. }
  1229. multiFactor.user = self
  1230. #endif
  1231. }
  1232. #if os(iOS)
  1233. /// Updates the phone number for the user. On success, the cached user profile data is updated.
  1234. ///
  1235. /// Invoked asynchronously on the global work queue in the future.
  1236. /// - Parameter credential: The new phone number credential corresponding to the phone
  1237. /// number to be added to the Firebase account. If a phone number is already linked to the
  1238. /// account, this new phone number will replace it.
  1239. /// - Parameter isLinkOperation: Boolean value indicating whether or not this is a link
  1240. /// operation.
  1241. /// - Parameter completion: Optionally; the block invoked when the user profile change has
  1242. /// finished.
  1243. private func internalUpdateOrLinkPhoneNumber(credential: PhoneAuthCredential,
  1244. isLinkOperation: Bool,
  1245. completion: @escaping (Error?) -> Void) {
  1246. internalGetToken { accessToken, error in
  1247. if let error {
  1248. completion(error)
  1249. return
  1250. }
  1251. guard let accessToken = accessToken else {
  1252. fatalError("Auth Internal Error: Both accessToken and error are nil")
  1253. }
  1254. guard let configuration = self.auth?.requestConfiguration else {
  1255. fatalError("Auth Internal Error: nil value for VerifyPhoneNumberRequest initializer")
  1256. }
  1257. switch credential.credentialKind {
  1258. case .phoneNumber: fatalError("Internal Error: Missing verificationCode")
  1259. case let .verification(verificationID, code):
  1260. let operation = isLinkOperation ? AuthOperationType.link : AuthOperationType.update
  1261. let request = VerifyPhoneNumberRequest(verificationID: verificationID,
  1262. verificationCode: code,
  1263. operation: operation,
  1264. requestConfiguration: configuration)
  1265. request.accessToken = accessToken
  1266. Task {
  1267. do {
  1268. let verifyResponse = try await AuthBackend.call(with: request)
  1269. guard let idToken = verifyResponse.idToken,
  1270. let refreshToken = verifyResponse.refreshToken else {
  1271. fatalError("Internal Auth Error: missing token in internalUpdateOrLinkPhoneNumber")
  1272. }
  1273. // Update the new token and refresh user info again.
  1274. self.tokenService = SecureTokenService(
  1275. withRequestConfiguration: configuration,
  1276. accessToken: idToken,
  1277. accessTokenExpirationDate: verifyResponse.approximateExpirationDate,
  1278. refreshToken: refreshToken
  1279. )
  1280. // Get account info to update cached user info.
  1281. self.getAccountInfoRefreshingCache { user, error in
  1282. if let error {
  1283. self.signOutIfTokenIsInvalid(withError: error)
  1284. completion(error)
  1285. return
  1286. }
  1287. self.isAnonymous = false
  1288. if let error = self.updateKeychain() {
  1289. completion(error)
  1290. return
  1291. }
  1292. completion(nil)
  1293. }
  1294. } catch {
  1295. self.signOutIfTokenIsInvalid(withError: error)
  1296. completion(error)
  1297. }
  1298. }
  1299. }
  1300. }
  1301. }
  1302. #endif
  1303. private func link(withEmail email: String,
  1304. password: String,
  1305. authResult: AuthDataResult,
  1306. _ completion: ((AuthDataResult?, Error?) -> Void)?) {
  1307. internalGetToken { accessToken, error in
  1308. guard let requestConfiguration = self.auth?.requestConfiguration else {
  1309. fatalError("Internal auth error: missing auth on User")
  1310. }
  1311. let request = SignUpNewUserRequest(email: email,
  1312. password: password,
  1313. displayName: nil,
  1314. idToken: accessToken,
  1315. requestConfiguration: requestConfiguration)
  1316. Task {
  1317. do {
  1318. #if os(iOS)
  1319. guard let auth = self.auth else {
  1320. fatalError("Internal Auth error: missing auth instance on user")
  1321. }
  1322. let response = try await auth.injectRecaptcha(request: request,
  1323. action: AuthRecaptchaAction
  1324. .signUpPassword)
  1325. #else
  1326. let response = try await AuthBackend.call(with: request)
  1327. #endif
  1328. guard let refreshToken = response.refreshToken,
  1329. let idToken = response.idToken else {
  1330. fatalError("Internal auth error: Invalid SignUpNewUserResponse")
  1331. }
  1332. // Update the new token and refresh user info again.
  1333. try await self.updateTokenAndRefreshUser(
  1334. idToken: idToken,
  1335. refreshToken: refreshToken,
  1336. expirationDate: response.approximateExpirationDate,
  1337. requestConfiguration: requestConfiguration
  1338. )
  1339. User.callInMainThreadWithAuthDataResultAndError(
  1340. callback: completion,
  1341. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1342. error: nil
  1343. )
  1344. } catch {
  1345. self.signOutIfTokenIsInvalid(withError: error)
  1346. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1347. result: nil, error: error)
  1348. }
  1349. }
  1350. }
  1351. }
  1352. private func link(withEmailCredential emailCredential: EmailAuthCredential,
  1353. completion: ((AuthDataResult?, Error?) -> Void)?) {
  1354. if hasEmailPasswordCredential {
  1355. User.callInMainThreadWithAuthDataResultAndError(
  1356. callback: completion,
  1357. result: nil,
  1358. error: AuthErrorUtils
  1359. .providerAlreadyLinkedError()
  1360. )
  1361. return
  1362. }
  1363. switch emailCredential.emailType {
  1364. case let .password(password):
  1365. let result = AuthDataResult(withUser: self, additionalUserInfo: nil)
  1366. link(withEmail: emailCredential.email, password: password, authResult: result, completion)
  1367. case let .link(link):
  1368. internalGetToken { accessToken, error in
  1369. var queryItems = AuthWebUtils.parseURL(link)
  1370. if link.count == 0 {
  1371. if let urlComponents = URLComponents(string: link),
  1372. let query = urlComponents.query {
  1373. queryItems = AuthWebUtils.parseURL(query)
  1374. }
  1375. }
  1376. guard let actionCode = queryItems["oobCode"],
  1377. let requestConfiguration = self.auth?.requestConfiguration else {
  1378. fatalError("Internal Auth Error: Missing oobCode or requestConfiguration")
  1379. }
  1380. let request = EmailLinkSignInRequest(email: emailCredential.email,
  1381. oobCode: actionCode,
  1382. requestConfiguration: requestConfiguration)
  1383. request.idToken = accessToken
  1384. Task {
  1385. do {
  1386. let response = try await AuthBackend.call(with: request)
  1387. guard let idToken = response.idToken,
  1388. let refreshToken = response.refreshToken else {
  1389. fatalError("Internal Auth Error: missing token in EmailLinkSignInResponse")
  1390. }
  1391. try await self.updateTokenAndRefreshUser(
  1392. idToken: idToken,
  1393. refreshToken: refreshToken,
  1394. expirationDate: response.approximateExpirationDate,
  1395. requestConfiguration: requestConfiguration
  1396. )
  1397. User.callInMainThreadWithAuthDataResultAndError(
  1398. callback: completion,
  1399. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1400. error: nil
  1401. )
  1402. } catch {
  1403. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1404. result: nil,
  1405. error: error)
  1406. }
  1407. }
  1408. }
  1409. }
  1410. }
  1411. #if !os(watchOS)
  1412. private func link(withGameCenterCredential gameCenterCredential: GameCenterAuthCredential,
  1413. completion: ((AuthDataResult?, Error?) -> Void)?) {
  1414. internalGetToken { accessToken, error in
  1415. guard let requestConfiguration = self.auth?.requestConfiguration,
  1416. let publicKeyURL = gameCenterCredential.publicKeyURL,
  1417. let signature = gameCenterCredential.signature,
  1418. let salt = gameCenterCredential.salt else {
  1419. fatalError("Internal Auth Error: Nil value field for SignInWithGameCenterRequest")
  1420. }
  1421. let request = SignInWithGameCenterRequest(playerID: gameCenterCredential.playerID,
  1422. teamPlayerID: gameCenterCredential.teamPlayerID,
  1423. gamePlayerID: gameCenterCredential.gamePlayerID,
  1424. publicKeyURL: publicKeyURL,
  1425. signature: signature,
  1426. salt: salt,
  1427. timestamp: gameCenterCredential.timestamp,
  1428. displayName: gameCenterCredential.displayName,
  1429. requestConfiguration: requestConfiguration)
  1430. request.accessToken = accessToken
  1431. Task {
  1432. do {
  1433. let response = try await AuthBackend.call(with: request)
  1434. guard let idToken = response.idToken,
  1435. let refreshToken = response.refreshToken else {
  1436. fatalError("Internal Auth Error: missing token in link(withGameCredential")
  1437. }
  1438. try await self.updateTokenAndRefreshUser(
  1439. idToken: idToken,
  1440. refreshToken: refreshToken,
  1441. expirationDate: response.approximateExpirationDate,
  1442. requestConfiguration: requestConfiguration
  1443. )
  1444. User.callInMainThreadWithAuthDataResultAndError(
  1445. callback: completion,
  1446. result: AuthDataResult(withUser: self, additionalUserInfo: nil),
  1447. error: nil
  1448. )
  1449. } catch {
  1450. User.callInMainThreadWithAuthDataResultAndError(callback: completion,
  1451. result: nil,
  1452. error: error)
  1453. }
  1454. }
  1455. }
  1456. }
  1457. #endif
  1458. #if os(iOS)
  1459. private func link(withPhoneCredential phoneCredential: PhoneAuthCredential,
  1460. completion: ((AuthDataResult?, Error?) -> Void)?) {
  1461. internalUpdateOrLinkPhoneNumber(credential: phoneCredential,
  1462. isLinkOperation: true) { error in
  1463. if let error {
  1464. User.callInMainThreadWithAuthDataResultAndError(
  1465. callback: completion,
  1466. result: nil,
  1467. error: error
  1468. )
  1469. } else {
  1470. let result = AuthDataResult(withUser: self, additionalUserInfo: nil)
  1471. User.callInMainThreadWithAuthDataResultAndError(
  1472. callback: completion,
  1473. result: result,
  1474. error: nil
  1475. )
  1476. }
  1477. }
  1478. }
  1479. #endif
  1480. // Update the new token and refresh user info again.
  1481. private func updateTokenAndRefreshUser(idToken: String,
  1482. refreshToken: String,
  1483. expirationDate: Date?,
  1484. requestConfiguration: AuthRequestConfiguration) async throws {
  1485. return try await userProfileUpdate
  1486. .updateTokenAndRefreshUser(
  1487. user: self,
  1488. idToken: idToken,
  1489. refreshToken: refreshToken,
  1490. expirationDate: expirationDate
  1491. )
  1492. }
  1493. /// Signs out this user if the user or the token is invalid.
  1494. /// - Parameter error: The error from the server.
  1495. func signOutIfTokenIsInvalid(withError error: Error) {
  1496. let code = (error as NSError).code
  1497. if code == AuthErrorCode.userNotFound.rawValue ||
  1498. code == AuthErrorCode.userDisabled.rawValue ||
  1499. code == AuthErrorCode.invalidUserToken.rawValue ||
  1500. code == AuthErrorCode.userTokenExpired.rawValue {
  1501. AuthLog.logNotice(code: "I-AUT000016",
  1502. message: "Invalid user token detected, user is automatically signed out.")
  1503. try? auth?.signOutByForce(withUserID: uid)
  1504. }
  1505. }
  1506. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1507. /// - Parameter callback: The block to invoke when the token is available. Invoked asynchronously
  1508. /// on the global work thread in the future.
  1509. func internalGetToken(forceRefresh: Bool = false,
  1510. callback: @escaping (String?, Error?) -> Void) {
  1511. Task {
  1512. do {
  1513. let token = try await internalGetTokenAsync(forceRefresh: forceRefresh)
  1514. callback(token, nil)
  1515. } catch {
  1516. callback(nil, error)
  1517. }
  1518. }
  1519. }
  1520. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  1521. /// - Parameter forceRefresh
  1522. func internalGetTokenAsync(forceRefresh: Bool = false) async throws -> String {
  1523. var keychainError = false
  1524. do {
  1525. let (token, tokenUpdated) = try await tokenService.fetchAccessToken(
  1526. forcingRefresh: forceRefresh
  1527. )
  1528. if tokenUpdated {
  1529. if let error = updateKeychain() {
  1530. keychainError = true
  1531. throw error
  1532. }
  1533. }
  1534. return token!
  1535. } catch {
  1536. if !keychainError {
  1537. signOutIfTokenIsInvalid(withError: error)
  1538. }
  1539. throw error
  1540. }
  1541. }
  1542. /// Updates the keychain for user token or info changes.
  1543. /// - Returns: An `Error` on failure.
  1544. func updateKeychain() -> Error? {
  1545. return auth?.updateKeychain(withUser: self)
  1546. }
  1547. /// Calls a callback in main thread with error.
  1548. /// - Parameter callback: The callback to be called in main thread.
  1549. /// - Parameter error: The error to pass to callback.
  1550. class func callInMainThreadWithError(callback: ((Error?) -> Void)?, error: Error?) {
  1551. if let callback {
  1552. DispatchQueue.main.async {
  1553. callback(error)
  1554. }
  1555. }
  1556. }
  1557. /// Calls a callback in main thread with user and error.
  1558. /// - Parameter callback: The callback to be called in main thread.
  1559. /// - Parameter user: The user to pass to callback if there is no error.
  1560. /// - Parameter error: The error to pass to callback.
  1561. private class func callInMainThreadWithUserAndError(callback: ((User?, Error?) -> Void)?,
  1562. user: User,
  1563. error: Error?) {
  1564. if let callback {
  1565. DispatchQueue.main.async {
  1566. callback((error != nil) ? nil : user, error)
  1567. }
  1568. }
  1569. }
  1570. /// Calls a callback in main thread with user and error.
  1571. /// - Parameter callback: The callback to be called in main thread.
  1572. private class func callInMainThreadWithAuthDataResultAndError(callback: (
  1573. (AuthDataResult?, Error?) -> Void
  1574. )?,
  1575. result: AuthDataResult? = nil,
  1576. error: Error? = nil) {
  1577. if let callback {
  1578. DispatchQueue.main.async {
  1579. callback(result, error)
  1580. }
  1581. }
  1582. }
  1583. // MARK: NSSecureCoding
  1584. private let kUserIDCodingKey = "userID"
  1585. private let kHasEmailPasswordCredentialCodingKey = "hasEmailPassword"
  1586. private let kAnonymousCodingKey = "anonymous"
  1587. private let kEmailCodingKey = "email"
  1588. private let kPhoneNumberCodingKey = "phoneNumber"
  1589. private let kEmailVerifiedCodingKey = "emailVerified"
  1590. private let kDisplayNameCodingKey = "displayName"
  1591. private let kPhotoURLCodingKey = "photoURL"
  1592. private let kProviderDataKey = "providerData"
  1593. private let kAPIKeyCodingKey = "APIKey"
  1594. private let kFirebaseAppIDCodingKey = "firebaseAppID"
  1595. private let kTokenServiceCodingKey = "tokenService"
  1596. private let kMetadataCodingKey = "metadata"
  1597. private let kMultiFactorCodingKey = "multiFactor"
  1598. private let kTenantIDCodingKey = "tenantID"
  1599. public static let supportsSecureCoding = true
  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 tokenService = coder.decodeObject(of: SecureTokenService.self,
  1624. forKey: kTokenServiceCodingKey) else {
  1625. return nil
  1626. }
  1627. let anonymous = coder.decodeBool(forKey: kAnonymousCodingKey)
  1628. let hasEmailPasswordCredential = coder.decodeBool(forKey: kHasEmailPasswordCredentialCodingKey)
  1629. let displayName = coder.decodeObject(
  1630. of: NSString.self,
  1631. forKey: kDisplayNameCodingKey
  1632. ) as? String
  1633. let photoURL = coder.decodeObject(of: NSURL.self, forKey: kPhotoURLCodingKey) as? URL
  1634. let email = coder.decodeObject(of: NSString.self, forKey: kEmailCodingKey) as? String
  1635. let phoneNumber = coder.decodeObject(
  1636. of: NSString.self,
  1637. forKey: kPhoneNumberCodingKey
  1638. ) as? String
  1639. let emailVerified = coder.decodeBool(forKey: kEmailVerifiedCodingKey)
  1640. let classes = [NSDictionary.self, NSString.self, UserInfoImpl.self]
  1641. let providerData = coder.decodeObject(of: classes, forKey: kProviderDataKey)
  1642. as? [String: UserInfoImpl]
  1643. let metadata = coder.decodeObject(of: UserMetadata.self, forKey: kMetadataCodingKey)
  1644. let tenantID = coder.decodeObject(of: NSString.self, forKey: kTenantIDCodingKey) as? String
  1645. #if os(iOS)
  1646. let multiFactor = coder.decodeObject(of: MultiFactor.self, forKey: kMultiFactorCodingKey)
  1647. #endif
  1648. self.tokenService = tokenService
  1649. uid = userID
  1650. isAnonymous = anonymous
  1651. self.hasEmailPasswordCredential = hasEmailPasswordCredential
  1652. self.email = email
  1653. isEmailVerified = emailVerified
  1654. self.displayName = displayName
  1655. self.photoURL = photoURL
  1656. providerDataRaw = providerData ?? [:]
  1657. self.phoneNumber = phoneNumber
  1658. self.metadata = metadata ?? UserMetadata(withCreationDate: nil, lastSignInDate: nil)
  1659. self.tenantID = tenantID
  1660. // Note, in practice, the caller will set the `auth` property of this user
  1661. // instance which will as a side-effect overwrite the request configuration.
  1662. // The assignment here is a best-effort placeholder.
  1663. let apiKey = coder.decodeObject(of: NSString.self, forKey: kAPIKeyCodingKey) as? String
  1664. let appID = coder.decodeObject(
  1665. of: NSString.self,
  1666. forKey: kFirebaseAppIDCodingKey
  1667. ) as? String
  1668. requestConfiguration = AuthRequestConfiguration(apiKey: apiKey ?? "", appID: appID ?? "")
  1669. userProfileUpdate = UserProfileUpdate()
  1670. #if os(iOS)
  1671. self.multiFactor = multiFactor ?? MultiFactor()
  1672. super.init()
  1673. multiFactor?.user = self
  1674. #endif
  1675. }
  1676. }