User.swift 86 KB

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