User.swift 87 KB

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