User.swift 80 KB

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