Auth.swift 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431
  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 FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. import FirebaseCoreExtension
  19. #if COCOAPODS
  20. internal import GoogleUtilities
  21. #else
  22. internal import GoogleUtilities_AppDelegateSwizzler
  23. internal import GoogleUtilities_Environment
  24. #endif
  25. #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
  26. import UIKit
  27. #endif
  28. // Export the deprecated Objective-C defined globals and typedefs.
  29. #if SWIFT_PACKAGE
  30. @_exported import FirebaseAuthInternal
  31. #endif // SWIFT_PACKAGE
  32. #if os(iOS)
  33. @available(iOS 13.0, *)
  34. extension Auth: UISceneDelegate {
  35. open func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
  36. for urlContext in URLContexts {
  37. let _ = canHandle(urlContext.url)
  38. }
  39. }
  40. }
  41. @available(iOS 13.0, *)
  42. extension Auth: UIApplicationDelegate {
  43. open func application(_ application: UIApplication,
  44. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  45. setAPNSToken(deviceToken, type: .unknown)
  46. }
  47. open func application(_ application: UIApplication,
  48. didFailToRegisterForRemoteNotificationsWithError error: Error) {
  49. kAuthGlobalWorkQueue.sync {
  50. self.tokenManager.cancel(withError: error)
  51. }
  52. }
  53. open func application(_ application: UIApplication,
  54. didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  55. fetchCompletionHandler completionHandler:
  56. @escaping (UIBackgroundFetchResult) -> Void) {
  57. _ = canHandleNotification(userInfo)
  58. completionHandler(UIBackgroundFetchResult.noData)
  59. }
  60. open func application(_ application: UIApplication,
  61. open url: URL,
  62. options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
  63. return canHandle(url)
  64. }
  65. }
  66. #endif
  67. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  68. extension Auth: AuthInterop {
  69. /// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  70. ///
  71. /// This method is not for public use. It is for Firebase clients of AuthInterop.
  72. @objc(getTokenForcingRefresh:withCallback:)
  73. public func getToken(forcingRefresh forceRefresh: Bool,
  74. completion callback: @escaping (String?, Error?) -> Void) {
  75. kAuthGlobalWorkQueue.async { [weak self] in
  76. if let strongSelf = self {
  77. // Enable token auto-refresh if not already enabled.
  78. if !strongSelf.autoRefreshTokens {
  79. AuthLog.logInfo(code: "I-AUT000002", message: "Token auto-refresh enabled.")
  80. strongSelf.autoRefreshTokens = true
  81. strongSelf.scheduleAutoTokenRefresh()
  82. #if os(iOS) || os(tvOS) // TODO(ObjC): Is a similar mechanism needed on macOS?
  83. strongSelf.applicationDidBecomeActiveObserver =
  84. NotificationCenter.default.addObserver(
  85. forName: UIApplication.didBecomeActiveNotification,
  86. object: nil, queue: nil
  87. ) { notification in
  88. if let strongSelf = self {
  89. strongSelf.isAppInBackground = false
  90. if !strongSelf.autoRefreshScheduled {
  91. strongSelf.scheduleAutoTokenRefresh()
  92. }
  93. }
  94. }
  95. strongSelf.applicationDidEnterBackgroundObserver =
  96. NotificationCenter.default.addObserver(
  97. forName: UIApplication.didEnterBackgroundNotification,
  98. object: nil, queue: nil
  99. ) { notification in
  100. if let strongSelf = self {
  101. strongSelf.isAppInBackground = true
  102. }
  103. }
  104. #endif
  105. }
  106. }
  107. // Call back with 'nil' if there is no current user.
  108. guard let strongSelf = self, let currentUser = strongSelf._currentUser else {
  109. DispatchQueue.main.async {
  110. callback(nil, nil)
  111. }
  112. return
  113. }
  114. // Call back with current user token.
  115. currentUser
  116. .internalGetToken(
  117. forceRefresh: forceRefresh,
  118. backend: strongSelf.backend,
  119. callback: callback,
  120. callCallbackOnMain: true
  121. )
  122. }
  123. }
  124. /// Get the current Auth user's UID. Returns nil if there is no user signed in.
  125. ///
  126. /// This method is not for public use. It is for Firebase clients of AuthInterop.
  127. open func getUserID() -> String? {
  128. return _currentUser?.uid
  129. }
  130. }
  131. /// Manages authentication for Firebase apps.
  132. ///
  133. /// This class is thread-safe.
  134. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  135. @preconcurrency
  136. @objc(FIRAuth) open class Auth: NSObject {
  137. /// Gets the auth object for the default Firebase app.
  138. ///
  139. /// The default Firebase app must have already been configured or an exception will be raised.
  140. @objc open class func auth() -> Auth {
  141. guard let defaultApp = FirebaseApp.app() else {
  142. fatalError("The default FirebaseApp instance must be configured before the default Auth " +
  143. "instance can be initialized. One way to ensure this is to call " +
  144. "`FirebaseApp.configure()` in the App Delegate's " +
  145. "`application(_:didFinishLaunchingWithOptions:)` (or the `@main` struct's " +
  146. "initializer in SwiftUI).")
  147. }
  148. return auth(app: defaultApp)
  149. }
  150. /// Gets the auth object for a `FirebaseApp`.
  151. /// - Parameter app: The app for which to retrieve the associated `Auth` instance.
  152. /// - Returns: The `Auth` instance associated with the given app.
  153. @objc open class func auth(app: FirebaseApp) -> Auth {
  154. return ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container) as! Auth
  155. }
  156. /// Gets the `FirebaseApp` object that this auth object is connected to.
  157. @objc public internal(set) weak var app: FirebaseApp?
  158. /// Synchronously gets the cached current user, or null if there is none.
  159. @objc public var currentUser: User? {
  160. kAuthGlobalWorkQueue.sync {
  161. _currentUser
  162. }
  163. }
  164. private var _currentUser: User?
  165. /// The current user language code.
  166. ///
  167. /// This property can be set to the app's current language by
  168. /// calling `useAppLanguage()`.
  169. ///
  170. /// The string used to set this property must be a language code that follows BCP 47.
  171. @objc open var languageCode: String? {
  172. get {
  173. kAuthGlobalWorkQueue.sync {
  174. requestConfiguration.languageCode
  175. }
  176. }
  177. set(val) {
  178. kAuthGlobalWorkQueue.sync {
  179. requestConfiguration.languageCode = val
  180. }
  181. }
  182. }
  183. /// Contains settings related to the auth object.
  184. @NSCopying @objc open var settings: AuthSettings?
  185. /// The current user access group that the Auth instance is using.
  186. ///
  187. /// Default is `nil`.
  188. @objc public internal(set) var userAccessGroup: String?
  189. /// Contains shareAuthStateAcrossDevices setting related to the auth object.
  190. ///
  191. /// If userAccessGroup is not set, setting shareAuthStateAcrossDevices will
  192. /// have no effect. You should set shareAuthStateAcrossDevices to its desired
  193. /// state and then set the userAccessGroup after.
  194. @objc open var shareAuthStateAcrossDevices: Bool = false
  195. /// The tenant ID of the auth instance. `nil` if none is available.
  196. @objc open var tenantID: String?
  197. /// The custom authentication domain used to handle all sign-in redirects.
  198. /// End-users will see
  199. /// this domain when signing in. This domain must be allowlisted in the Firebase Console.
  200. @objc open var customAuthDomain: String?
  201. /// Sets the `currentUser` on the receiver to the provided user object.
  202. /// - Parameters:
  203. /// - user: The user object to be set as the current user of the calling Auth instance.
  204. /// - completion: Optionally; a block invoked after the user of the calling Auth instance has
  205. /// been updated or an error was encountered.
  206. @objc open func updateCurrentUser(_ user: User?, completion: ((Error?) -> Void)? = nil) {
  207. kAuthGlobalWorkQueue.async {
  208. guard let user else {
  209. let error = AuthErrorUtils.nullUserError(message: nil)
  210. Auth.wrapMainAsync(completion, error)
  211. return
  212. }
  213. let updateUserBlock: (User) -> Void = { user in
  214. do {
  215. try self.updateCurrentUser(user, byForce: true, savingToDisk: true)
  216. Auth.wrapMainAsync(completion, nil)
  217. } catch {
  218. Auth.wrapMainAsync(completion, error)
  219. }
  220. }
  221. if user.requestConfiguration.apiKey != self.requestConfiguration.apiKey {
  222. // If the API keys are different, then we need to confirm that the user belongs to the same
  223. // project before proceeding.
  224. user.requestConfiguration = self.requestConfiguration
  225. user.reload { error in
  226. if let error {
  227. Auth.wrapMainAsync(completion, error)
  228. return
  229. }
  230. updateUserBlock(user)
  231. }
  232. } else {
  233. updateUserBlock(user)
  234. }
  235. }
  236. }
  237. /// Sets the `currentUser` on the receiver to the provided user object.
  238. /// - Parameter user: The user object to be set as the current user of the calling Auth instance.
  239. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  240. open func updateCurrentUser(_ user: User) async throws {
  241. return try await withCheckedThrowingContinuation { continuation in
  242. self.updateCurrentUser(user) { error in
  243. if let error {
  244. continuation.resume(throwing: error)
  245. } else {
  246. continuation.resume()
  247. }
  248. }
  249. }
  250. }
  251. /// [Deprecated] Fetches the list of all sign-in methods previously used for the provided
  252. /// email address. This method returns an empty list when [Email Enumeration
  253. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  254. /// is enabled, irrespective of the number of authentication methods available for the given
  255. /// email.
  256. ///
  257. /// Possible error codes: `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  258. ///
  259. /// - Parameter email: The email address for which to obtain a list of sign-in methods.
  260. /// - Parameter completion: Optionally; a block which is invoked when the list of sign in methods
  261. /// for the specified email address is ready or an error was encountered. Invoked asynchronously
  262. /// on the main thread in the future.
  263. #if !FIREBASE_CI
  264. @available(
  265. *,
  266. deprecated,
  267. message: "`fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled."
  268. )
  269. #endif // !FIREBASE_CI
  270. @objc open func fetchSignInMethods(forEmail email: String,
  271. completion: (([String]?, Error?) -> Void)? = nil) {
  272. kAuthGlobalWorkQueue.async {
  273. let request = CreateAuthURIRequest(identifier: email,
  274. continueURI: "http://www.google.com/",
  275. requestConfiguration: self.requestConfiguration)
  276. Task {
  277. do {
  278. let response = try await self.backend.call(with: request)
  279. Auth.wrapMainAsync(callback: completion, with: .success(response.signinMethods))
  280. } catch {
  281. Auth.wrapMainAsync(callback: completion, with: .failure(error))
  282. }
  283. }
  284. }
  285. }
  286. /// [Deprecated] Fetches the list of all sign-in methods previously used for the provided
  287. /// email address. This method returns an empty list when [Email Enumeration
  288. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  289. /// is enabled, irrespective of the number of authentication methods available for the given
  290. /// email.
  291. ///
  292. /// Possible error codes: `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  293. ///
  294. /// - Parameter email: The email address for which to obtain a list of sign-in methods.
  295. /// - Returns: List of sign-in methods
  296. @available(
  297. *,
  298. deprecated,
  299. message: "`fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled."
  300. )
  301. open func fetchSignInMethods(forEmail email: String) async throws -> [String] {
  302. return try await withCheckedThrowingContinuation { continuation in
  303. self.fetchSignInMethods(forEmail: email) { methods, error in
  304. if let methods {
  305. continuation.resume(returning: methods)
  306. } else {
  307. continuation.resume(throwing: error!)
  308. }
  309. }
  310. }
  311. }
  312. /// Signs in using an email address and password.
  313. ///
  314. /// When [Email Enumeration
  315. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  316. /// is enabled, this method fails with an error in case of an invalid
  317. /// email/password.
  318. ///
  319. /// Possible error codes:
  320. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  321. /// accounts are not enabled. Enable them in the Auth section of the
  322. /// Firebase console.
  323. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  324. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  325. /// sign in with an incorrect password.
  326. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  327. /// - Parameter email: The user's email address.
  328. /// - Parameter password: The user's password.
  329. /// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
  330. /// or is canceled. Invoked asynchronously on the main thread in the future.
  331. @objc open func signIn(withEmail email: String,
  332. password: String,
  333. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  334. kAuthGlobalWorkQueue.async {
  335. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  336. Task {
  337. do {
  338. let authData = try await self.internalSignInAndRetrieveData(
  339. withEmail: email,
  340. password: password
  341. )
  342. decoratedCallback(.success(authData))
  343. } catch {
  344. decoratedCallback(.failure(error))
  345. }
  346. }
  347. }
  348. }
  349. /// Signs in using an email address and password.
  350. ///
  351. /// When [Email Enumeration
  352. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  353. /// is enabled, this method throws in case of an invalid email/password.
  354. ///
  355. /// Possible error codes:
  356. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  357. /// accounts are not enabled. Enable them in the Auth section of the
  358. /// Firebase console.
  359. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  360. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  361. /// sign in with an incorrect password.
  362. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  363. /// - Parameter email: The user's email address.
  364. /// - Parameter password: The user's password.
  365. /// - Returns: The signed in user.
  366. func internalSignInUser(withEmail email: String,
  367. password: String) async throws -> User {
  368. let request = VerifyPasswordRequest(email: email,
  369. password: password,
  370. requestConfiguration: requestConfiguration)
  371. if request.password.count == 0 {
  372. throw AuthErrorUtils.wrongPasswordError(message: nil)
  373. }
  374. #if os(iOS)
  375. let response = try await injectRecaptcha(request: request,
  376. action: AuthRecaptchaAction.signInWithPassword)
  377. #else
  378. let response = try await backend.call(with: request)
  379. #endif
  380. return try await completeSignIn(
  381. withAccessToken: response.idToken,
  382. accessTokenExpirationDate: response.approximateExpirationDate,
  383. refreshToken: response.refreshToken,
  384. anonymous: false
  385. )
  386. }
  387. /// Signs in using an email address and password.
  388. ///
  389. /// Possible error codes:
  390. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  391. /// accounts are not enabled. Enable them in the Auth section of the
  392. /// Firebase console.
  393. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  394. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  395. /// sign in with an incorrect password.
  396. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  397. /// - Parameter email: The user's email address.
  398. /// - Parameter password: The user's password.
  399. /// - Returns: The `AuthDataResult` after a successful signin.
  400. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  401. @discardableResult
  402. open func signIn(withEmail email: String, password: String) async throws -> AuthDataResult {
  403. return try await withCheckedThrowingContinuation { continuation in
  404. self.signIn(withEmail: email, password: password) { authData, error in
  405. if let authData {
  406. continuation.resume(returning: authData)
  407. } else {
  408. continuation.resume(throwing: error!)
  409. }
  410. }
  411. }
  412. }
  413. /// Signs in using an email address and email sign-in link.
  414. ///
  415. /// Possible error codes:
  416. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  417. /// accounts are not enabled. Enable them in the Auth section of the
  418. /// Firebase console.
  419. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  420. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  421. /// sign in with an incorrect password.
  422. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  423. /// - Parameter email: The user's email address.
  424. /// - Parameter link: The email sign-in link.
  425. /// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
  426. /// or is canceled. Invoked asynchronously on the main thread in the future.
  427. @objc open func signIn(withEmail email: String,
  428. link: String,
  429. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  430. kAuthGlobalWorkQueue.async {
  431. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  432. let credential = EmailAuthCredential(withEmail: email, link: link)
  433. Task {
  434. do {
  435. let authData = try await self.internalSignInAndRetrieveData(withCredential: credential,
  436. isReauthentication: false)
  437. decoratedCallback(.success(authData))
  438. } catch {
  439. decoratedCallback(.failure(error))
  440. }
  441. }
  442. }
  443. }
  444. /// Signs in using an email address and email sign-in link.
  445. /// Possible error codes:
  446. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  447. /// accounts are not enabled. Enable them in the Auth section of the
  448. /// Firebase console.
  449. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  450. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  451. /// sign in with an incorrect password.
  452. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  453. /// - Parameter email: The user's email address.
  454. /// - Parameter link: The email sign-in link.
  455. /// - Returns: The `AuthDataResult` after a successful signin.
  456. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  457. open func signIn(withEmail email: String, link: String) async throws -> AuthDataResult {
  458. return try await withCheckedThrowingContinuation { continuation in
  459. self.signIn(withEmail: email, link: link) { result, error in
  460. if let result {
  461. continuation.resume(returning: result)
  462. } else {
  463. continuation.resume(throwing: error!)
  464. }
  465. }
  466. }
  467. }
  468. #if os(iOS)
  469. /// Signs in using the provided auth provider instance.
  470. ///
  471. /// Possible error codes:
  472. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  473. /// accounts are not enabled. Enable them in the Auth section of the
  474. /// Firebase console.
  475. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  476. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  477. /// sign in with an incorrect password.
  478. /// * `AuthErrorCodeWebNetworkRequestFailed` - Indicates that a network request within a
  479. /// SFSafariViewController or WKWebView failed.
  480. /// * `AuthErrorCodeWebInternalError` - Indicates that an internal error occurred within a
  481. /// SFSafariViewController or WKWebView.
  482. /// * `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during
  483. /// a web sign-in flow.
  484. /// * `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to
  485. /// present a new web context while one was already being presented.
  486. /// * `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was
  487. /// cancelled prematurely by the user.
  488. /// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
  489. /// by the credential (e.g. the email in a Facebook access token) is already in use by an
  490. /// existing account, that cannot be authenticated with this sign-in method. Call
  491. /// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
  492. /// the sign-in providers returned. This error will only be thrown if the "One account per
  493. /// email address" setting is enabled in the Firebase console, under Auth settings.
  494. /// - Parameter provider: An instance of an auth provider used to initiate the sign-in flow.
  495. /// - Parameter uiDelegate: Optionally an instance of a class conforming to the AuthUIDelegate
  496. /// protocol, this is used for presenting the web context. If nil, a default AuthUIDelegate
  497. /// will be used.
  498. /// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
  499. /// or is canceled. Invoked asynchronously on the main thread in the future.
  500. @available(tvOS, unavailable)
  501. @available(macOS, unavailable)
  502. @available(watchOS, unavailable)
  503. @objc(signInWithProvider:UIDelegate:completion:)
  504. open func signIn(with provider: FederatedAuthProvider,
  505. uiDelegate: AuthUIDelegate?,
  506. completion: ((AuthDataResult?, Error?) -> Void)?) {
  507. kAuthGlobalWorkQueue.async {
  508. Task {
  509. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  510. do {
  511. let credential = try await provider.credential(with: uiDelegate)
  512. let authData = try await self.internalSignInAndRetrieveData(
  513. withCredential: credential,
  514. isReauthentication: false
  515. )
  516. decoratedCallback(.success(authData))
  517. } catch {
  518. decoratedCallback(.failure(error))
  519. }
  520. }
  521. }
  522. }
  523. /// Signs in using the provided auth provider instance.
  524. ///
  525. /// Possible error codes:
  526. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
  527. /// accounts are not enabled. Enable them in the Auth section of the
  528. /// Firebase console.
  529. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  530. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
  531. /// sign in with an incorrect password.
  532. /// * `AuthErrorCodeWebNetworkRequestFailed` - Indicates that a network request within a
  533. /// SFSafariViewController or WKWebView failed.
  534. /// * `AuthErrorCodeWebInternalError` - Indicates that an internal error occurred within a
  535. /// SFSafariViewController or WKWebView.
  536. /// * `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during
  537. /// a web sign-in flow.
  538. /// * `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to
  539. /// present a new web context while one was already being presented.
  540. /// * `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was
  541. /// cancelled prematurely by the user.
  542. /// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
  543. /// by the credential (e.g. the email in a Facebook access token) is already in use by an
  544. /// existing account, that cannot be authenticated with this sign-in method. Call
  545. /// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
  546. /// the sign-in providers returned. This error will only be thrown if the "One account per
  547. /// email address" setting is enabled in the Firebase console, under Auth settings.
  548. /// - Parameter provider: An instance of an auth provider used to initiate the sign-in flow.
  549. /// - Parameter uiDelegate: Optionally an instance of a class conforming to the AuthUIDelegate
  550. /// protocol, this is used for presenting the web context. If nil, a default AuthUIDelegate
  551. /// will be used.
  552. /// - Returns: The `AuthDataResult` after the successful signin.
  553. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  554. @available(tvOS, unavailable)
  555. @available(macOS, unavailable)
  556. @available(watchOS, unavailable)
  557. @discardableResult
  558. open func signIn(with provider: FederatedAuthProvider,
  559. uiDelegate: AuthUIDelegate?) async throws -> AuthDataResult {
  560. return try await withCheckedThrowingContinuation { continuation in
  561. self.signIn(with: provider, uiDelegate: uiDelegate) { result, error in
  562. if let result {
  563. continuation.resume(returning: result)
  564. } else {
  565. continuation.resume(throwing: error!)
  566. }
  567. }
  568. }
  569. }
  570. #endif // iOS
  571. /// Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook
  572. /// login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional
  573. /// identity provider data.
  574. ///
  575. /// Possible error codes:
  576. /// * `AuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid.
  577. /// This could happen if it has expired or it is malformed.
  578. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts
  579. /// with the identity provider represented by the credential are not enabled.
  580. /// Enable them in the Auth section of the Firebase console.
  581. /// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
  582. /// by the credential (e.g. the email in a Facebook access token) is already in use by an
  583. /// existing account, that cannot be authenticated with this sign-in method. Call
  584. /// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
  585. /// the sign-in providers returned. This error will only be thrown if the "One account per
  586. /// email address" setting is enabled in the Firebase console, under Auth settings.
  587. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  588. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an
  589. /// incorrect password, if credential is of the type EmailPasswordAuthCredential.
  590. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  591. /// * `AuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was
  592. /// created with an empty verification ID.
  593. /// * `AuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential
  594. /// was created with an empty verification code.
  595. /// * `AuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential
  596. /// was created with an invalid verification Code.
  597. /// * `AuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was
  598. /// created with an invalid verification ID.
  599. /// * `AuthErrorCodeSessionExpired` - Indicates that the SMS code has expired.
  600. /// - Parameter credential: The credential supplied by the IdP.
  601. /// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
  602. /// or is canceled. Invoked asynchronously on the main thread in the future.
  603. @objc(signInWithCredential:completion:)
  604. open func signIn(with credential: AuthCredential,
  605. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  606. kAuthGlobalWorkQueue.async {
  607. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  608. Task {
  609. do {
  610. let authData = try await self.internalSignInAndRetrieveData(withCredential: credential,
  611. isReauthentication: false)
  612. decoratedCallback(.success(authData))
  613. } catch {
  614. decoratedCallback(.failure(error))
  615. }
  616. }
  617. }
  618. }
  619. /// Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook
  620. /// login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional
  621. /// identity provider data.
  622. ///
  623. /// Possible error codes:
  624. /// * `AuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid.
  625. /// This could happen if it has expired or it is malformed.
  626. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts
  627. /// with the identity provider represented by the credential are not enabled.
  628. /// Enable them in the Auth section of the Firebase console.
  629. /// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
  630. /// by the credential (e.g. the email in a Facebook access token) is already in use by an
  631. /// existing account, that cannot be authenticated with this sign-in method. Call
  632. /// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
  633. /// the sign-in providers returned. This error will only be thrown if the "One account per
  634. /// email address" setting is enabled in the Firebase console, under Auth settings.
  635. /// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
  636. /// * `AuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an
  637. /// incorrect password, if credential is of the type EmailPasswordAuthCredential.
  638. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  639. /// * `AuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was
  640. /// created with an empty verification ID.
  641. /// * `AuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential
  642. /// was created with an empty verification code.
  643. /// * `AuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential
  644. /// was created with an invalid verification Code.
  645. /// * `AuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was
  646. /// created with an invalid verification ID.
  647. /// * `AuthErrorCodeSessionExpired` - Indicates that the SMS code has expired.
  648. /// - Parameter credential: The credential supplied by the IdP.
  649. /// - Returns: The `AuthDataResult` after the successful signin.
  650. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  651. @discardableResult
  652. open func signIn(with credential: AuthCredential) async throws -> AuthDataResult {
  653. return try await withCheckedThrowingContinuation { continuation in
  654. self.signIn(with: credential) { result, error in
  655. if let result {
  656. continuation.resume(returning: result)
  657. } else {
  658. continuation.resume(throwing: error!)
  659. }
  660. }
  661. }
  662. }
  663. /// Asynchronously creates and becomes an anonymous user.
  664. ///
  665. /// If there is already an anonymous user signed in, that user will be returned instead.
  666. /// If there is any other existing user signed in, that user will be signed out.
  667. ///
  668. /// Possible error codes:
  669. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are
  670. /// not enabled. Enable them in the Auth section of the Firebase console.
  671. /// - Parameter completion: Optionally; a block which is invoked when the sign in finishes, or is
  672. /// canceled. Invoked asynchronously on the main thread in the future.
  673. @objc open func signInAnonymously(completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  674. kAuthGlobalWorkQueue.async {
  675. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  676. if let currentUser = self._currentUser, currentUser.isAnonymous {
  677. let result = AuthDataResult(withUser: currentUser, additionalUserInfo: nil)
  678. decoratedCallback(.success(result))
  679. return
  680. }
  681. let request = SignUpNewUserRequest(requestConfiguration: self.requestConfiguration)
  682. Task {
  683. do {
  684. let response = try await self.backend.call(with: request)
  685. let user = try await self.completeSignIn(
  686. withAccessToken: response.idToken,
  687. accessTokenExpirationDate: response.approximateExpirationDate,
  688. refreshToken: response.refreshToken,
  689. anonymous: true
  690. )
  691. // TODO: The ObjC implementation passed a nil providerID to the nonnull providerID
  692. let additionalUserInfo = AdditionalUserInfo(providerID: "",
  693. profile: nil,
  694. username: nil,
  695. isNewUser: true)
  696. decoratedCallback(
  697. .success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
  698. )
  699. } catch {
  700. decoratedCallback(.failure(error))
  701. }
  702. }
  703. }
  704. }
  705. /// Asynchronously creates and becomes an anonymous user.
  706. ///
  707. /// If there is already an anonymous user signed in, that user will be returned instead.
  708. /// If there is any other existing user signed in, that user will be signed out.
  709. ///
  710. /// Possible error codes:
  711. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are
  712. /// not enabled. Enable them in the Auth section of the Firebase console.
  713. /// - Returns: The `AuthDataResult` after the successful signin.
  714. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  715. @discardableResult
  716. @objc open func signInAnonymously() async throws -> AuthDataResult {
  717. return try await withCheckedThrowingContinuation { continuation in
  718. self.signInAnonymously { result, error in
  719. if let result {
  720. continuation.resume(returning: result)
  721. } else {
  722. continuation.resume(throwing: error!)
  723. }
  724. }
  725. }
  726. }
  727. /// Asynchronously signs in to Firebase with the given Auth token.
  728. ///
  729. /// Possible error codes:
  730. /// * `AuthErrorCodeInvalidCustomToken` - Indicates a validation error with
  731. /// the custom token.
  732. /// * `AuthErrorCodeCustomTokenMismatch` - Indicates the service account and the API key
  733. /// belong to different projects.
  734. /// - Parameter token: A self-signed custom auth token.
  735. /// - Parameter completion: Optionally; a block which is invoked when the sign in finishes, or is
  736. /// canceled. Invoked asynchronously on the main thread in the future.
  737. @objc open func signIn(withCustomToken token: String,
  738. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  739. kAuthGlobalWorkQueue.async {
  740. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  741. let request = VerifyCustomTokenRequest(token: token,
  742. requestConfiguration: self.requestConfiguration)
  743. Task {
  744. do {
  745. let response = try await self.backend.call(with: request)
  746. let user = try await self.completeSignIn(
  747. withAccessToken: response.idToken,
  748. accessTokenExpirationDate: response.approximateExpirationDate,
  749. refreshToken: response.refreshToken,
  750. anonymous: false
  751. )
  752. // TODO: The ObjC implementation passed a nil providerID to the nonnull providerID
  753. let additionalUserInfo = AdditionalUserInfo(providerID: "",
  754. profile: nil,
  755. username: nil,
  756. isNewUser: response.isNewUser)
  757. decoratedCallback(
  758. .success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
  759. )
  760. } catch {
  761. decoratedCallback(.failure(error))
  762. }
  763. }
  764. }
  765. }
  766. /// Asynchronously signs in to Firebase with the given Auth token.
  767. ///
  768. /// Possible error codes:
  769. /// * `AuthErrorCodeInvalidCustomToken` - Indicates a validation error with
  770. /// the custom token.
  771. /// * `AuthErrorCodeCustomTokenMismatch` - Indicates the service account and the API key
  772. /// belong to different projects.
  773. /// - Parameter token: A self-signed custom auth token.
  774. /// - Returns: The `AuthDataResult` after the successful signin.
  775. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  776. @discardableResult
  777. open func signIn(withCustomToken token: String) async throws -> AuthDataResult {
  778. return try await withCheckedThrowingContinuation { continuation in
  779. self.signIn(withCustomToken: token) { result, error in
  780. if let result {
  781. continuation.resume(returning: result)
  782. } else {
  783. continuation.resume(throwing: error!)
  784. }
  785. }
  786. }
  787. }
  788. /// Creates and, on success, signs in a user with the given email address and password.
  789. ///
  790. /// Possible error codes:
  791. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  792. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up
  793. /// already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user
  794. /// used, and prompt the user to sign in with one of those.
  795. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts
  796. /// are not enabled. Enable them in the Auth section of the Firebase console.
  797. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  798. /// considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo
  799. /// dictionary object will contain more detailed explanation that can be shown to the user.
  800. /// - Parameter email: The user's email address.
  801. /// - Parameter password: The user's desired password.
  802. /// - Parameter completion: Optionally; a block which is invoked when the sign up flow finishes,
  803. /// or is canceled. Invoked asynchronously on the main thread in the future.
  804. @objc open func createUser(withEmail email: String,
  805. password: String,
  806. completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
  807. guard password.count > 0 else {
  808. if let completion {
  809. completion(nil, AuthErrorUtils.weakPasswordError(serverResponseReason: "Missing password"))
  810. }
  811. return
  812. }
  813. guard email.count > 0 else {
  814. if let completion {
  815. completion(nil, AuthErrorUtils.missingEmailError(message: nil))
  816. }
  817. return
  818. }
  819. kAuthGlobalWorkQueue.async {
  820. let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
  821. let request = SignUpNewUserRequest(email: email,
  822. password: password,
  823. displayName: nil,
  824. idToken: nil,
  825. requestConfiguration: self.requestConfiguration)
  826. #if os(iOS)
  827. Task {
  828. do {
  829. let response = try await self.injectRecaptcha(
  830. request: request,
  831. action: AuthRecaptchaAction.signUpPassword
  832. )
  833. self.internalCreateUserWithEmail(
  834. request: request,
  835. inResponse: response,
  836. decoratedCallback: decoratedCallback
  837. )
  838. } catch {
  839. DispatchQueue.main.async {
  840. decoratedCallback(.failure(error))
  841. }
  842. return
  843. }
  844. }
  845. #else
  846. self.internalCreateUserWithEmail(
  847. request: request,
  848. decoratedCallback: decoratedCallback
  849. )
  850. #endif
  851. }
  852. }
  853. private func internalCreateUserWithEmail(request: SignUpNewUserRequest,
  854. inResponse: SignUpNewUserResponse? = nil,
  855. decoratedCallback: @escaping (Result<
  856. AuthDataResult,
  857. Error
  858. >)
  859. -> Void) {
  860. Task {
  861. do {
  862. var response: SignUpNewUserResponse
  863. if let inResponse {
  864. response = inResponse
  865. } else {
  866. response = try await self.backend.call(with: request)
  867. }
  868. let user = try await self.completeSignIn(
  869. withAccessToken: response.idToken,
  870. accessTokenExpirationDate: response.approximateExpirationDate,
  871. refreshToken: response.refreshToken,
  872. anonymous: false
  873. )
  874. let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
  875. profile: nil,
  876. username: nil,
  877. isNewUser: true)
  878. decoratedCallback(
  879. .success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
  880. )
  881. } catch {
  882. decoratedCallback(.failure(error))
  883. }
  884. }
  885. }
  886. /// Creates and, on success, signs in a user with the given email address and password.
  887. ///
  888. /// Possible error codes:
  889. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  890. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up
  891. /// already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user
  892. /// used, and prompt the user to sign in with one of those.
  893. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts
  894. /// are not enabled. Enable them in the Auth section of the Firebase console.
  895. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  896. /// considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo
  897. /// dictionary object will contain more detailed explanation that can be shown to the user.
  898. /// - Parameter email: The user's email address.
  899. /// - Parameter password: The user's desired password.
  900. /// - Returns: The `AuthDataResult` after the successful signin.
  901. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  902. @discardableResult
  903. open func createUser(withEmail email: String, password: String) async throws -> AuthDataResult {
  904. return try await withCheckedThrowingContinuation { continuation in
  905. self.createUser(withEmail: email, password: password) { result, error in
  906. if let result {
  907. continuation.resume(returning: result)
  908. } else {
  909. continuation.resume(throwing: error!)
  910. }
  911. }
  912. }
  913. }
  914. /// Resets the password given a code sent to the user outside of the app and a new password
  915. /// for the user.
  916. ///
  917. /// Possible error codes:
  918. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  919. /// considered too weak.
  920. /// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign
  921. /// in with the specified identity provider.
  922. /// * `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired.
  923. /// * `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid.
  924. /// - Parameter code: The reset code.
  925. /// - Parameter newPassword: The new password.
  926. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  927. /// Invoked asynchronously on the main thread in the future.
  928. @objc open func confirmPasswordReset(withCode code: String, newPassword: String,
  929. completion: @escaping (Error?) -> Void) {
  930. kAuthGlobalWorkQueue.async {
  931. let request = ResetPasswordRequest(oobCode: code,
  932. newPassword: newPassword,
  933. requestConfiguration: self.requestConfiguration)
  934. self.wrapAsyncRPCTask(request, completion)
  935. }
  936. }
  937. /// Resets the password given a code sent to the user outside of the app and a new password
  938. /// for the user.
  939. ///
  940. /// Possible error codes:
  941. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  942. /// considered too weak.
  943. /// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign
  944. /// in with the specified identity provider.
  945. /// * `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired.
  946. /// * `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid.
  947. /// - Parameter code: The reset code.
  948. /// - Parameter newPassword: The new password.
  949. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  950. open func confirmPasswordReset(withCode code: String, newPassword: String) async throws {
  951. return try await withCheckedThrowingContinuation { continuation in
  952. self.confirmPasswordReset(withCode: code, newPassword: newPassword) { error in
  953. if let error {
  954. continuation.resume(throwing: error)
  955. } else {
  956. continuation.resume()
  957. }
  958. }
  959. }
  960. }
  961. /// Checks the validity of an out of band code.
  962. /// - Parameter code: The out of band code to check validity.
  963. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  964. /// Invoked
  965. /// asynchronously on the main thread in the future.
  966. @objc open func checkActionCode(_ code: String,
  967. completion: @escaping (ActionCodeInfo?, Error?) -> Void) {
  968. kAuthGlobalWorkQueue.async {
  969. let request = ResetPasswordRequest(oobCode: code,
  970. newPassword: nil,
  971. requestConfiguration: self.requestConfiguration)
  972. Task {
  973. do {
  974. let response = try await self.backend.call(with: request)
  975. let operation = ActionCodeInfo.actionCodeOperation(forRequestType: response.requestType)
  976. guard let email = response.email else {
  977. fatalError("Internal Auth Error: Failed to get a ResetPasswordResponse")
  978. }
  979. let actionCodeInfo = ActionCodeInfo(withOperation: operation,
  980. email: email,
  981. newEmail: response.verifiedEmail)
  982. Auth.wrapMainAsync(callback: completion, with: .success(actionCodeInfo))
  983. } catch {
  984. Auth.wrapMainAsync(callback: completion, with: .failure(error))
  985. }
  986. }
  987. }
  988. }
  989. /// Checks the validity of an out of band code.
  990. /// - Parameter code: The out of band code to check validity.
  991. /// - Returns: An `ActionCodeInfo`.
  992. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  993. open func checkActionCode(_ code: String) async throws -> ActionCodeInfo {
  994. return try await withCheckedThrowingContinuation { continuation in
  995. self.checkActionCode(code) { info, error in
  996. if let info {
  997. continuation.resume(returning: info)
  998. } else {
  999. continuation.resume(throwing: error!)
  1000. }
  1001. }
  1002. }
  1003. }
  1004. /// Checks the validity of a verify password reset code.
  1005. /// - Parameter code: The password reset code to be verified.
  1006. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1007. /// Invoked asynchronously on the main thread in the future.
  1008. @objc open func verifyPasswordResetCode(_ code: String,
  1009. completion: @escaping (String?, Error?) -> Void) {
  1010. checkActionCode(code) { info, error in
  1011. if let error {
  1012. completion(nil, error)
  1013. return
  1014. }
  1015. completion(info?.email, nil)
  1016. }
  1017. }
  1018. /// Checks the validity of a verify password reset code.
  1019. /// - Parameter code: The password reset code to be verified.
  1020. /// - Returns: An email.
  1021. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1022. open func verifyPasswordResetCode(_ code: String) async throws -> String {
  1023. return try await withCheckedThrowingContinuation { continuation in
  1024. self.verifyPasswordResetCode(code) { code, error in
  1025. if let code {
  1026. continuation.resume(returning: code)
  1027. } else {
  1028. continuation.resume(throwing: error!)
  1029. }
  1030. }
  1031. }
  1032. }
  1033. /// Applies out of band code.
  1034. ///
  1035. /// This method will not work for out of band codes which require an additional parameter,
  1036. /// such as password reset code.
  1037. /// - Parameter code: The out of band code to be applied.
  1038. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1039. /// Invoked asynchronously on the main thread in the future.
  1040. @objc open func applyActionCode(_ code: String, completion: @escaping (Error?) -> Void) {
  1041. kAuthGlobalWorkQueue.async {
  1042. let request = SetAccountInfoRequest(requestConfiguration: self.requestConfiguration)
  1043. request.oobCode = code
  1044. self.wrapAsyncRPCTask(request, completion)
  1045. }
  1046. }
  1047. /// Applies out of band code.
  1048. ///
  1049. /// This method will not work for out of band codes which require an additional parameter,
  1050. /// such as password reset code.
  1051. /// - Parameter code: The out of band code to be applied.
  1052. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1053. open func applyActionCode(_ code: String) async throws {
  1054. return try await withCheckedThrowingContinuation { continuation in
  1055. self.applyActionCode(code) { error in
  1056. if let error {
  1057. continuation.resume(throwing: error)
  1058. } else {
  1059. continuation.resume()
  1060. }
  1061. }
  1062. }
  1063. }
  1064. /// Initiates a password reset for the given email address.
  1065. ///
  1066. /// This method does not throw an
  1067. /// error when there's no user account with the given email address and [Email Enumeration
  1068. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  1069. /// is enabled.
  1070. ///
  1071. /// Possible error codes:
  1072. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  1073. /// sent in the request.
  1074. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  1075. /// the console for this action.
  1076. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  1077. /// sending update email.
  1078. /// - Parameter email: The email address of the user.
  1079. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1080. /// Invoked
  1081. /// asynchronously on the main thread in the future.
  1082. @objc open func sendPasswordReset(withEmail email: String,
  1083. completion: ((Error?) -> Void)? = nil) {
  1084. sendPasswordReset(withEmail: email, actionCodeSettings: nil, completion: completion)
  1085. }
  1086. /// Initiates a password reset for the given email address and `ActionCodeSettings` object.
  1087. ///
  1088. /// This method does not throw an
  1089. /// error when there's no user account with the given email address and [Email Enumeration
  1090. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  1091. /// is enabled.
  1092. ///
  1093. /// Possible error codes:
  1094. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  1095. /// sent in the request.
  1096. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  1097. /// the console for this action.
  1098. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  1099. /// sending update email.
  1100. /// * `AuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing when
  1101. /// `handleCodeInApp` is set to true.
  1102. /// * `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name
  1103. /// is missing when the `androidInstallApp` flag is set to true.
  1104. /// * `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the
  1105. /// continue URL is not allowlisted in the Firebase console.
  1106. /// * `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the
  1107. /// continue URL is not valid.
  1108. /// - Parameter email: The email address of the user.
  1109. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1110. /// handling action codes.
  1111. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1112. /// Invoked asynchronously on the main thread in the future.
  1113. @objc open func sendPasswordReset(withEmail email: String,
  1114. actionCodeSettings: ActionCodeSettings?,
  1115. completion: ((Error?) -> Void)? = nil) {
  1116. kAuthGlobalWorkQueue.async {
  1117. let request = GetOOBConfirmationCodeRequest.passwordResetRequest(
  1118. email: email,
  1119. actionCodeSettings: actionCodeSettings,
  1120. requestConfiguration: self.requestConfiguration
  1121. )
  1122. #if os(iOS)
  1123. Task {
  1124. do {
  1125. _ = try await self.injectRecaptcha(
  1126. request: request,
  1127. action: AuthRecaptchaAction.getOobCode
  1128. )
  1129. Auth.wrapMainAsync(completion, nil)
  1130. } catch {
  1131. Auth.wrapMainAsync(completion, error)
  1132. }
  1133. }
  1134. #else
  1135. self.wrapAsyncRPCTask(request, completion)
  1136. #endif
  1137. }
  1138. }
  1139. /// Initiates a password reset for the given email address and `ActionCodeSettings` object.
  1140. ///
  1141. /// This method does not throw an
  1142. /// error when there's no user account with the given email address and [Email Enumeration
  1143. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  1144. /// is enabled.
  1145. ///
  1146. /// Possible error codes:
  1147. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  1148. /// sent in the request.
  1149. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  1150. /// the console for this action.
  1151. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  1152. /// sending update email.
  1153. /// * `AuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing when
  1154. /// `handleCodeInApp` is set to true.
  1155. /// * `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name
  1156. /// is missing when the `androidInstallApp` flag is set to true.
  1157. /// * `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the
  1158. /// continue URL is not allowlisted in the Firebase console.
  1159. /// * `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the
  1160. /// continue URL is not valid.
  1161. /// - Parameter email: The email address of the user.
  1162. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1163. /// handling action codes.
  1164. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1165. open func sendPasswordReset(withEmail email: String,
  1166. actionCodeSettings: ActionCodeSettings? = nil) async throws {
  1167. return try await withCheckedThrowingContinuation { continuation in
  1168. self.sendPasswordReset(withEmail: email, actionCodeSettings: actionCodeSettings) { error in
  1169. if let error {
  1170. continuation.resume(throwing: error)
  1171. } else {
  1172. continuation.resume()
  1173. }
  1174. }
  1175. }
  1176. }
  1177. /// Sends a sign in with email link to provided email address.
  1178. /// - Parameter email: The email address of the user.
  1179. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1180. /// handling action codes.
  1181. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1182. /// Invoked asynchronously on the main thread in the future.
  1183. @objc open func sendSignInLink(toEmail email: String,
  1184. actionCodeSettings: ActionCodeSettings,
  1185. completion: ((Error?) -> Void)? = nil) {
  1186. if !actionCodeSettings.handleCodeInApp {
  1187. fatalError("The handleCodeInApp flag in ActionCodeSettings must be true for Email-link " +
  1188. "Authentication.")
  1189. }
  1190. kAuthGlobalWorkQueue.async {
  1191. let request = GetOOBConfirmationCodeRequest.signInWithEmailLinkRequest(
  1192. email,
  1193. actionCodeSettings: actionCodeSettings,
  1194. requestConfiguration: self.requestConfiguration
  1195. )
  1196. #if os(iOS)
  1197. Task {
  1198. do {
  1199. _ = try await self.injectRecaptcha(
  1200. request: request,
  1201. action: AuthRecaptchaAction.getOobCode
  1202. )
  1203. Auth.wrapMainAsync(completion, nil)
  1204. } catch {
  1205. Auth.wrapMainAsync(completion, error)
  1206. }
  1207. }
  1208. #else
  1209. self.wrapAsyncRPCTask(request, completion)
  1210. #endif
  1211. }
  1212. }
  1213. /// Sends a sign in with email link to provided email address.
  1214. /// - Parameter email: The email address of the user.
  1215. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1216. /// handling action codes.
  1217. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1218. open func sendSignInLink(toEmail email: String,
  1219. actionCodeSettings: ActionCodeSettings) async throws {
  1220. return try await withCheckedThrowingContinuation { continuation in
  1221. self.sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in
  1222. if let error {
  1223. continuation.resume(throwing: error)
  1224. } else {
  1225. continuation.resume()
  1226. }
  1227. }
  1228. }
  1229. }
  1230. /// Signs out the current user.
  1231. ///
  1232. /// Possible error codes:
  1233. /// * `AuthErrorCodeKeychainError` - Indicates an error occurred when accessing the
  1234. /// keychain. The `NSLocalizedFailureReasonErrorKey` field in the `userInfo`
  1235. /// dictionary will contain more information about the error encountered.
  1236. @objc(signOut:) open func signOut() throws {
  1237. try kAuthGlobalWorkQueue.sync {
  1238. guard self._currentUser != nil else {
  1239. return
  1240. }
  1241. return try self.updateCurrentUser(nil, byForce: false, savingToDisk: true)
  1242. }
  1243. }
  1244. /// Checks if link is an email sign-in link.
  1245. /// - Parameter link: The email sign-in link.
  1246. /// - Returns: `true` when the link passed matches the expected format of an email sign-in link.
  1247. @objc open func isSignIn(withEmailLink link: String) -> Bool {
  1248. guard link.count > 0 else {
  1249. return false
  1250. }
  1251. let queryItems = getQueryItems(link)
  1252. if let _ = queryItems["oobCode"],
  1253. let mode = queryItems["mode"],
  1254. mode == "signIn" {
  1255. return true
  1256. }
  1257. return false
  1258. }
  1259. #if os(iOS) && !targetEnvironment(macCatalyst)
  1260. /// Initializes reCAPTCHA using the settings configured for the project or tenant.
  1261. ///
  1262. /// If you change the tenant ID of the `Auth` instance, the configuration will be
  1263. /// reloaded.
  1264. @objc(initializeRecaptchaConfigWithCompletion:)
  1265. open func initializeRecaptchaConfig(completion: ((Error?) -> Void)?) {
  1266. Task {
  1267. do {
  1268. try await initializeRecaptchaConfig()
  1269. if let completion {
  1270. completion(nil)
  1271. }
  1272. } catch {
  1273. if let completion {
  1274. completion(error)
  1275. }
  1276. }
  1277. }
  1278. }
  1279. /// Initializes reCAPTCHA using the settings configured for the project or tenant.
  1280. ///
  1281. /// If you change the tenant ID of the `Auth` instance, the configuration will be
  1282. /// reloaded.
  1283. open func initializeRecaptchaConfig() async throws {
  1284. // Trigger recaptcha verification flow to initialize the recaptcha client and
  1285. // config. Recaptcha token will be returned.
  1286. let verifier = AuthRecaptchaVerifier.shared(auth: self)
  1287. _ = try await verifier.verify(forceRefresh: true, action: AuthRecaptchaAction.defaultAction)
  1288. }
  1289. #endif
  1290. /// Registers a block as an "auth state did change" listener.
  1291. ///
  1292. /// To be invoked when:
  1293. /// * The block is registered as a listener,
  1294. /// * A user with a different UID from the current user has signed in, or
  1295. /// * The current user has signed out.
  1296. ///
  1297. /// The block is invoked immediately after adding it according to its standard invocation
  1298. /// semantics, asynchronously on the main thread. Users should pay special attention to
  1299. /// making sure the block does not inadvertently retain objects which should not be retained by
  1300. /// the long-lived block. The block itself will be retained by `Auth` until it is
  1301. /// unregistered or until the `Auth` instance is otherwise deallocated.
  1302. /// - Parameter listener: The block to be invoked. The block is always invoked asynchronously on
  1303. /// the main thread, even for it's initial invocation after having been added as a listener.
  1304. /// - Returns: A handle useful for manually unregistering the block as a listener.
  1305. @objc(addAuthStateDidChangeListener:)
  1306. open func addStateDidChangeListener(_ listener: @escaping (Auth, User?) -> Void)
  1307. -> NSObjectProtocol {
  1308. var firstInvocation = true
  1309. var previousUserID: String?
  1310. return addIDTokenDidChangeListener { auth, user in
  1311. let shouldCallListener = firstInvocation || previousUserID != user?.uid
  1312. firstInvocation = false
  1313. previousUserID = user?.uid
  1314. if shouldCallListener {
  1315. listener(auth, user)
  1316. }
  1317. }
  1318. }
  1319. /// Unregisters a block as an "auth state did change" listener.
  1320. /// - Parameter listenerHandle: The handle for the listener.
  1321. @objc(removeAuthStateDidChangeListener:)
  1322. open func removeStateDidChangeListener(_ listenerHandle: NSObjectProtocol) {
  1323. NotificationCenter.default.removeObserver(listenerHandle)
  1324. objc_sync_enter(Auth.self)
  1325. defer { objc_sync_exit(Auth.self) }
  1326. listenerHandles.remove(listenerHandle)
  1327. }
  1328. /// Registers a block as an "ID token did change" listener.
  1329. ///
  1330. /// To be invoked when:
  1331. /// * The block is registered as a listener,
  1332. /// * A user with a different UID from the current user has signed in,
  1333. /// * The ID token of the current user has been refreshed, or
  1334. /// * The current user has signed out.
  1335. ///
  1336. /// The block is invoked immediately after adding it according to its standard invocation
  1337. /// semantics, asynchronously on the main thread. Users should pay special attention to
  1338. /// making sure the block does not inadvertently retain objects which should not be retained by
  1339. /// the long-lived block. The block itself will be retained by `Auth` until it is
  1340. /// unregistered or until the `Auth` instance is otherwise deallocated.
  1341. /// - Parameter listener: The block to be invoked. The block is always invoked asynchronously on
  1342. /// the main thread, even for it's initial invocation after having been added as a listener.
  1343. /// - Returns: A handle useful for manually unregistering the block as a listener.
  1344. @objc open func addIDTokenDidChangeListener(_ listener: @escaping (Auth, User?) -> Void)
  1345. -> NSObjectProtocol {
  1346. let handle = NotificationCenter.default.addObserver(
  1347. forName: Auth.authStateDidChangeNotification,
  1348. object: self,
  1349. queue: OperationQueue.main
  1350. ) { notification in
  1351. if let auth = notification.object as? Auth {
  1352. listener(auth, auth._currentUser)
  1353. }
  1354. }
  1355. objc_sync_enter(Auth.self)
  1356. listenerHandles.add(listener)
  1357. objc_sync_exit(Auth.self)
  1358. DispatchQueue.main.async {
  1359. listener(self, self._currentUser)
  1360. }
  1361. return handle
  1362. }
  1363. /// Unregisters a block as an "ID token did change" listener.
  1364. /// - Parameter listenerHandle: The handle for the listener.
  1365. @objc open func removeIDTokenDidChangeListener(_ listenerHandle: NSObjectProtocol) {
  1366. NotificationCenter.default.removeObserver(listenerHandle)
  1367. objc_sync_enter(Auth.self)
  1368. listenerHandles.remove(listenerHandle)
  1369. objc_sync_exit(Auth.self)
  1370. }
  1371. /// Sets `languageCode` to the app's current language.
  1372. @objc open func useAppLanguage() {
  1373. kAuthGlobalWorkQueue.sync {
  1374. self.requestConfiguration.languageCode = Locale.preferredLanguages.first
  1375. }
  1376. }
  1377. /// Configures Firebase Auth to connect to an emulated host instead of the remote backend.
  1378. @objc open func useEmulator(withHost host: String, port: Int) {
  1379. guard host.count > 0 else {
  1380. fatalError("Cannot connect to empty host")
  1381. }
  1382. // If host is an IPv6 address, it should be formatted with surrounding brackets.
  1383. let formattedHost = host.contains(":") ? "[\(host)]" : host
  1384. kAuthGlobalWorkQueue.sync {
  1385. self.requestConfiguration.emulatorHostAndPort = "\(formattedHost):\(port)"
  1386. #if os(iOS)
  1387. self.settings?.appVerificationDisabledForTesting = true
  1388. #endif
  1389. }
  1390. }
  1391. /// Revoke the users token with authorization code.
  1392. /// - Parameter authorizationCode: The authorization code used to perform the revocation.
  1393. /// - Parameter completion: (Optional) the block invoked when the request to revoke the token is
  1394. /// complete, or fails. Invoked asynchronously on the main thread in the future.
  1395. @objc open func revokeToken(withAuthorizationCode authorizationCode: String,
  1396. completion: ((Error?) -> Void)? = nil) {
  1397. _currentUser?.internalGetToken(backend: backend) { idToken, error in
  1398. if let error {
  1399. Auth.wrapMainAsync(completion, error)
  1400. return
  1401. }
  1402. guard let idToken else {
  1403. fatalError("Internal Auth Error: Both idToken and error are nil")
  1404. }
  1405. let request = RevokeTokenRequest(withToken: authorizationCode,
  1406. idToken: idToken,
  1407. requestConfiguration: self.requestConfiguration)
  1408. self.wrapAsyncRPCTask(request, completion)
  1409. }
  1410. }
  1411. /// Revoke the users token with authorization code.
  1412. /// - Parameter authorizationCode: The authorization code used to perform the revocation.
  1413. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1414. open func revokeToken(withAuthorizationCode authorizationCode: String) async throws {
  1415. return try await withCheckedThrowingContinuation { continuation in
  1416. self.revokeToken(withAuthorizationCode: authorizationCode) { error in
  1417. if let error {
  1418. continuation.resume(throwing: error)
  1419. } else {
  1420. continuation.resume()
  1421. }
  1422. }
  1423. }
  1424. }
  1425. /// Switch userAccessGroup and current user to the given accessGroup and the user stored in it.
  1426. @objc open func useUserAccessGroup(_ accessGroup: String?) throws {
  1427. // self.storedUserManager is initialized asynchronously. Make sure it is done.
  1428. kAuthGlobalWorkQueue.sync {}
  1429. return try internalUseUserAccessGroup(accessGroup)
  1430. }
  1431. private func internalUseUserAccessGroup(_ accessGroup: String?) throws {
  1432. storedUserManager.setStoredUserAccessGroup(accessGroup: accessGroup)
  1433. let user = try getStoredUser(forAccessGroup: accessGroup)
  1434. try updateCurrentUser(user, byForce: false, savingToDisk: false)
  1435. if userAccessGroup == nil, accessGroup != nil {
  1436. let userKey = "\(firebaseAppName)\(kUserKey)"
  1437. try keychainServices.removeData(forKey: userKey)
  1438. }
  1439. userAccessGroup = accessGroup
  1440. lastNotifiedUserToken = user?.rawAccessToken()
  1441. }
  1442. /// Get the stored user in the given accessGroup.
  1443. ///
  1444. /// This API is not supported on tvOS when `shareAuthStateAcrossDevices` is set to `true`.
  1445. /// and will return `nil`.
  1446. /// Please refer to https://github.com/firebase/firebase-ios-sdk/issues/8878 for details.
  1447. @available(swift 1000.0) // Objective-C only API
  1448. @objc(getStoredUserForAccessGroup:error:)
  1449. open func __getStoredUser(forAccessGroup accessGroup: String?,
  1450. error outError: NSErrorPointer) -> User? {
  1451. do {
  1452. return try getStoredUser(forAccessGroup: accessGroup)
  1453. } catch {
  1454. outError?.pointee = error as NSError
  1455. return nil
  1456. }
  1457. }
  1458. /// Get the stored user in the given accessGroup.
  1459. ///
  1460. /// This API is not supported on tvOS when `shareAuthStateAcrossDevices` is set to `true`.
  1461. /// and will return `nil`.
  1462. ///
  1463. /// Please refer to https://github.com/firebase/firebase-ios-sdk/issues/8878 for details.
  1464. open func getStoredUser(forAccessGroup accessGroup: String?) throws -> User? {
  1465. var user: User?
  1466. if let accessGroup {
  1467. #if os(tvOS)
  1468. if shareAuthStateAcrossDevices {
  1469. AuthLog.logError(code: "I-AUT000001",
  1470. message: "Getting a stored user for a given access group is not supported " +
  1471. "on tvOS when `shareAuthStateAcrossDevices` is set to `true` (#8878)." +
  1472. "This case will return `nil`.")
  1473. return nil
  1474. }
  1475. #endif
  1476. guard let apiKey = app?.options.apiKey else {
  1477. fatalError("Internal Auth Error: missing apiKey")
  1478. }
  1479. user = try storedUserManager.getStoredUser(
  1480. accessGroup: accessGroup,
  1481. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1482. projectIdentifier: apiKey
  1483. )
  1484. } else {
  1485. let userKey = "\(firebaseAppName)\(kUserKey)"
  1486. if let encodedUserData = try keychainServices.data(forKey: userKey) {
  1487. let unarchiver = try NSKeyedUnarchiver(forReadingFrom: encodedUserData)
  1488. user = unarchiver.decodeObject(of: User.self, forKey: userKey)
  1489. }
  1490. }
  1491. user?.auth = self
  1492. return user
  1493. }
  1494. #if os(iOS)
  1495. /// The APNs token used for phone number authentication.
  1496. ///
  1497. /// The type of the token (production or sandbox) will be automatically
  1498. /// detected based on your provisioning profile.
  1499. ///
  1500. /// This property is available on iOS only.
  1501. ///
  1502. /// If swizzling is disabled, the APNs Token must be set for phone number auth to work,
  1503. /// by either setting this property or by calling `setAPNSToken(_:type:)`.
  1504. @objc(APNSToken) open var apnsToken: Data? {
  1505. kAuthGlobalWorkQueue.sync {
  1506. self.tokenManager.token?.data
  1507. }
  1508. }
  1509. /// Sets the APNs token along with its type.
  1510. ///
  1511. /// This method is available on iOS only.
  1512. ///
  1513. /// If swizzling is disabled, the APNs Token must be set for phone number auth to work,
  1514. /// by either setting calling this method or by setting the `APNSToken` property.
  1515. @objc open func setAPNSToken(_ token: Data, type: AuthAPNSTokenType) {
  1516. kAuthGlobalWorkQueue.sync {
  1517. self.tokenManager.token = AuthAPNSToken(withData: token, type: type)
  1518. }
  1519. }
  1520. /// Whether the specific remote notification is handled by `Auth` .
  1521. ///
  1522. /// This method is available on iOS only.
  1523. ///
  1524. /// If swizzling is disabled, related remote notifications must be forwarded to this method
  1525. /// for phone number auth to work.
  1526. /// - Parameter userInfo: A dictionary that contains information related to the
  1527. /// notification in question.
  1528. /// - Returns: Whether or the notification is handled. A return value of `true` means the
  1529. /// notification is for Firebase Auth so the caller should ignore the notification from further
  1530. /// processing, and `false` means the notification is for the app (or another library) so
  1531. /// the caller should continue handling this notification as usual.
  1532. @objc open func canHandleNotification(_ userInfo: [AnyHashable: Any]) -> Bool {
  1533. kAuthGlobalWorkQueue.sync {
  1534. self.notificationManager.canHandle(notification: userInfo)
  1535. }
  1536. }
  1537. /// Whether the specific URL is handled by `Auth` .
  1538. ///
  1539. /// This method is available on iOS only.
  1540. ///
  1541. /// If swizzling is disabled, URLs received by the application delegate must be forwarded
  1542. /// to this method for phone number auth to work.
  1543. /// - Parameter url: The URL received by the application delegate from any of the openURL
  1544. /// method.
  1545. /// - Returns: Whether or the URL is handled. `true` means the URL is for Firebase Auth
  1546. /// so the caller should ignore the URL from further processing, and `false` means the
  1547. /// the URL is for the app (or another library) so the caller should continue handling
  1548. /// this URL as usual.
  1549. @objc(canHandleURL:) open func canHandle(_ url: URL) -> Bool {
  1550. kAuthGlobalWorkQueue.sync {
  1551. guard let authURLPresenter = self.authURLPresenter as? AuthURLPresenter else {
  1552. return false
  1553. }
  1554. return authURLPresenter.canHandle(url: url)
  1555. }
  1556. }
  1557. #endif
  1558. /// The name of the `NSNotificationCenter` notification which is posted when the auth state
  1559. /// changes (for example, a new token has been produced, a user signs in or signs out).
  1560. ///
  1561. /// The object parameter of the notification is the sender `Auth` instance.
  1562. public static let authStateDidChangeNotification =
  1563. NSNotification.Name(rawValue: "FIRAuthStateDidChangeNotification")
  1564. // MARK: Internal methods
  1565. init(app: FirebaseApp,
  1566. keychainStorageProvider: AuthKeychainStorage = AuthKeychainStorageReal.shared,
  1567. backend: AuthBackend = .init(rpcIssuer: AuthBackendRPCIssuer()),
  1568. authDispatcher: AuthDispatcher = .init()) {
  1569. self.app = app
  1570. mainBundleUrlTypes = Bundle.main
  1571. .object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]]
  1572. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  1573. in: app.container)
  1574. guard let apiKey = app.options.apiKey else {
  1575. fatalError("Missing apiKey for Auth initialization")
  1576. }
  1577. firebaseAppName = app.name
  1578. #if os(iOS)
  1579. authURLPresenter = AuthURLPresenter()
  1580. settings = AuthSettings()
  1581. GULAppDelegateSwizzler.proxyOriginalDelegateIncludingAPNSMethods()
  1582. GULSceneDelegateSwizzler.proxyOriginalSceneDelegate()
  1583. #endif
  1584. requestConfiguration = AuthRequestConfiguration(apiKey: apiKey,
  1585. appID: app.options.googleAppID,
  1586. auth: nil,
  1587. heartbeatLogger: app.heartbeatLogger,
  1588. appCheck: appCheck)
  1589. self.backend = backend
  1590. self.authDispatcher = authDispatcher
  1591. let keychainServiceName = Auth.keychainServiceName(for: app)
  1592. keychainServices = AuthKeychainServices(service: keychainServiceName,
  1593. storage: keychainStorageProvider)
  1594. storedUserManager = AuthStoredUserManager(
  1595. serviceName: keychainServiceName,
  1596. keychainServices: keychainServices
  1597. )
  1598. super.init()
  1599. requestConfiguration.auth = self
  1600. protectedDataInitialization()
  1601. }
  1602. private func protectedDataInitialization() {
  1603. // Continue with the rest of initialization in the work thread.
  1604. kAuthGlobalWorkQueue.async { [weak self] in
  1605. // Load current user from Keychain.
  1606. guard let self else {
  1607. return
  1608. }
  1609. do {
  1610. if let storedUserAccessGroup = self.storedUserManager.getStoredUserAccessGroup() {
  1611. try self.internalUseUserAccessGroup(storedUserAccessGroup)
  1612. } else {
  1613. let user = try self.getUser()
  1614. if let user {
  1615. self.tenantID = user.tenantID
  1616. }
  1617. try self.updateCurrentUser(user, byForce: false, savingToDisk: false)
  1618. if let user {
  1619. self.lastNotifiedUserToken = user.rawAccessToken()
  1620. }
  1621. }
  1622. } catch {
  1623. #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
  1624. if (error as NSError).code == AuthErrorCode.keychainError.rawValue {
  1625. // If there's a keychain error, assume it is due to the keychain being accessed
  1626. // before the device is unlocked as a result of prewarming, and listen for the
  1627. // UIApplicationProtectedDataDidBecomeAvailable notification.
  1628. self.addProtectedDataDidBecomeAvailableObserver()
  1629. }
  1630. #endif
  1631. AuthLog.logError(code: "I-AUT000001",
  1632. message: "Error loading saved user when starting up: \(error)")
  1633. }
  1634. #if os(iOS)
  1635. if GULAppEnvironmentUtil.isAppExtension() {
  1636. // iOS App extensions should not call [UIApplication sharedApplication], even if
  1637. // UIApplication responds to it.
  1638. return
  1639. }
  1640. // Using reflection here to avoid build errors in extensions.
  1641. let sel = NSSelectorFromString("sharedApplication")
  1642. guard UIApplication.responds(to: sel),
  1643. let rawApplication = UIApplication.perform(sel),
  1644. let application = rawApplication.takeUnretainedValue() as? UIApplication else {
  1645. return
  1646. }
  1647. // Initialize for phone number auth.
  1648. self.tokenManager = AuthAPNSTokenManager(withApplication: application)
  1649. self.appCredentialManager = AuthAppCredentialManager(withKeychain: self.keychainServices)
  1650. self.notificationManager = AuthNotificationManager(
  1651. withApplication: application,
  1652. appCredentialManager: self.appCredentialManager
  1653. )
  1654. GULAppDelegateSwizzler.registerAppDelegateInterceptor(self)
  1655. GULSceneDelegateSwizzler.registerSceneDelegateInterceptor(self)
  1656. #endif
  1657. }
  1658. }
  1659. #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
  1660. private func addProtectedDataDidBecomeAvailableObserver() {
  1661. protectedDataDidBecomeAvailableObserver =
  1662. NotificationCenter.default.addObserver(
  1663. forName: UIApplication.protectedDataDidBecomeAvailableNotification,
  1664. object: nil,
  1665. queue: nil
  1666. ) { [weak self] notification in
  1667. guard let self else { return }
  1668. if let observer = self.protectedDataDidBecomeAvailableObserver {
  1669. NotificationCenter.default.removeObserver(
  1670. observer,
  1671. name: UIApplication.protectedDataDidBecomeAvailableNotification,
  1672. object: nil
  1673. )
  1674. }
  1675. self.protectedDataInitialization()
  1676. }
  1677. }
  1678. #endif
  1679. deinit {
  1680. let defaultCenter = NotificationCenter.default
  1681. while listenerHandles.count > 0 {
  1682. let handleToRemove = listenerHandles.lastObject
  1683. defaultCenter.removeObserver(handleToRemove as Any)
  1684. listenerHandles.removeLastObject()
  1685. }
  1686. #if os(iOS)
  1687. defaultCenter.removeObserver(applicationDidBecomeActiveObserver as Any,
  1688. name: UIApplication.didBecomeActiveNotification,
  1689. object: nil)
  1690. defaultCenter.removeObserver(applicationDidEnterBackgroundObserver as Any,
  1691. name: UIApplication.didEnterBackgroundNotification,
  1692. object: nil)
  1693. #endif
  1694. }
  1695. private func getUser() throws -> User? {
  1696. var user: User?
  1697. if let userAccessGroup {
  1698. guard let apiKey = app?.options.apiKey else {
  1699. fatalError("Internal Auth Error: missing apiKey")
  1700. }
  1701. user = try storedUserManager.getStoredUser(
  1702. accessGroup: userAccessGroup,
  1703. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1704. projectIdentifier: apiKey
  1705. )
  1706. } else {
  1707. let userKey = "\(firebaseAppName)\(kUserKey)"
  1708. guard let encodedUserData = try keychainServices.data(forKey: userKey) else {
  1709. return nil
  1710. }
  1711. let unarchiver = try NSKeyedUnarchiver(forReadingFrom: encodedUserData)
  1712. user = unarchiver.decodeObject(of: User.self, forKey: userKey)
  1713. }
  1714. user?.auth = self
  1715. return user
  1716. }
  1717. /// Gets the keychain service name global data for the particular app by name.
  1718. /// - Parameter appName: The name of the Firebase app to get keychain service name for.
  1719. class func keychainServiceForAppID(_ appID: String) -> String {
  1720. return "firebase_auth_\(appID)"
  1721. }
  1722. func updateKeychain(withUser user: User?) -> Error? {
  1723. if user != _currentUser {
  1724. // No-op if the user is no longer signed in. This is not considered an error as we don't check
  1725. // whether the user is still current on other callbacks of user operations either.
  1726. return nil
  1727. }
  1728. do {
  1729. try saveUser(user)
  1730. possiblyPostAuthStateChangeNotification()
  1731. } catch {
  1732. return error
  1733. }
  1734. return nil
  1735. }
  1736. /// A map from Firebase app name to keychain service names.
  1737. ///
  1738. /// This map is needed for looking up the keychain service name after the FirebaseApp instance
  1739. /// is deleted, to remove the associated keychain item. Accessing should occur within a
  1740. /// @synchronized([FIRAuth class]) context.
  1741. fileprivate static var gKeychainServiceNameForAppName: [String: String] = [:]
  1742. /// Gets the keychain service name global data for the particular app by
  1743. /// name, creating an entry for one if it does not exist.
  1744. /// - Parameter app: The Firebase app to get the keychain service name for.
  1745. /// - Returns: The keychain service name for the given app.
  1746. static func keychainServiceName(for app: FirebaseApp) -> String {
  1747. objc_sync_enter(Auth.self)
  1748. defer { objc_sync_exit(Auth.self) }
  1749. let appName = app.name
  1750. if let serviceName = gKeychainServiceNameForAppName[appName] {
  1751. return serviceName
  1752. } else {
  1753. let serviceName = "firebase_auth_\(app.options.googleAppID)"
  1754. gKeychainServiceNameForAppName[appName] = serviceName
  1755. return serviceName
  1756. }
  1757. }
  1758. /// Deletes the keychain service name global data for the particular app by name.
  1759. /// - Parameter appName: The name of the Firebase app to delete keychain service name for.
  1760. /// - Returns: The deleted keychain service name, if any.
  1761. static func deleteKeychainServiceNameForAppName(_ appName: String) -> String? {
  1762. objc_sync_enter(Auth.self)
  1763. defer { objc_sync_exit(Auth.self) }
  1764. guard let serviceName = gKeychainServiceNameForAppName[appName] else {
  1765. return nil
  1766. }
  1767. gKeychainServiceNameForAppName.removeValue(forKey: appName)
  1768. return serviceName
  1769. }
  1770. func signOutByForce(withUserID userID: String) throws {
  1771. guard _currentUser?.uid == userID else {
  1772. return
  1773. }
  1774. try updateCurrentUser(nil, byForce: true, savingToDisk: true)
  1775. }
  1776. // MARK: Private methods
  1777. /// Posts the auth state change notification if current user's token has been changed.
  1778. private func possiblyPostAuthStateChangeNotification() {
  1779. let token = _currentUser?.rawAccessToken()
  1780. if lastNotifiedUserToken == token ||
  1781. (token != nil && lastNotifiedUserToken == token) {
  1782. return
  1783. }
  1784. lastNotifiedUserToken = token
  1785. if autoRefreshTokens {
  1786. // Schedule new refresh task after successful attempt.
  1787. scheduleAutoTokenRefresh()
  1788. }
  1789. var internalNotificationParameters: [String: Any] = [:]
  1790. if let app = app {
  1791. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationAppKey] = app
  1792. }
  1793. if let token, token.count > 0 {
  1794. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationTokenKey] = token
  1795. }
  1796. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationUIDKey] = _currentUser?
  1797. .uid
  1798. let notifications = NotificationCenter.default
  1799. DispatchQueue.main.async {
  1800. notifications.post(name: NSNotification.Name.FIRAuthStateDidChangeInternal,
  1801. object: self,
  1802. userInfo: internalNotificationParameters)
  1803. notifications.post(name: Auth.authStateDidChangeNotification, object: self)
  1804. }
  1805. }
  1806. /// Schedules a task to automatically refresh tokens on the current user. The0 token refresh
  1807. /// is scheduled 5 minutes before the scheduled expiration time.
  1808. ///
  1809. /// If the token expires in less than 5 minutes, schedule the token refresh immediately.
  1810. private func scheduleAutoTokenRefresh() {
  1811. let tokenExpirationInterval =
  1812. (_currentUser?.accessTokenExpirationDate()?.timeIntervalSinceNow ?? 0) - 5 * 60
  1813. scheduleAutoTokenRefresh(withDelay: max(tokenExpirationInterval, 0), retry: false)
  1814. }
  1815. /// Schedules a task to automatically refresh tokens on the current user.
  1816. /// - Parameter delay: The delay in seconds after which the token refresh task should be scheduled
  1817. /// to be executed.
  1818. /// - Parameter retry: Flag to determine whether the invocation is a retry attempt or not.
  1819. private func scheduleAutoTokenRefresh(withDelay delay: TimeInterval, retry: Bool) {
  1820. guard let accessToken = _currentUser?.rawAccessToken() else {
  1821. return
  1822. }
  1823. let intDelay = Int(ceil(delay))
  1824. if retry {
  1825. AuthLog.logInfo(code: "I-AUT000003", message: "Token auto-refresh re-scheduled in " +
  1826. "\(intDelay / 60):\(intDelay % 60) " +
  1827. "because of error on previous refresh attempt.")
  1828. } else {
  1829. AuthLog.logInfo(code: "I-AUT000004", message: "Token auto-refresh scheduled in " +
  1830. "\(intDelay / 60):\(intDelay % 60) " +
  1831. "for the new token.")
  1832. }
  1833. autoRefreshScheduled = true
  1834. weak var weakSelf = self
  1835. authDispatcher.dispatch(afterDelay: delay, queue: kAuthGlobalWorkQueue) {
  1836. guard let strongSelf = weakSelf else {
  1837. return
  1838. }
  1839. guard strongSelf._currentUser?.rawAccessToken() == accessToken else {
  1840. // Another auto refresh must have been scheduled, so keep _autoRefreshScheduled unchanged.
  1841. return
  1842. }
  1843. strongSelf.autoRefreshScheduled = false
  1844. if strongSelf.isAppInBackground {
  1845. return
  1846. }
  1847. let uid = strongSelf._currentUser?.uid
  1848. strongSelf._currentUser?
  1849. .internalGetToken(forceRefresh: true, backend: strongSelf.backend) { token, error in
  1850. if strongSelf._currentUser?.uid != uid {
  1851. return
  1852. }
  1853. if error != nil {
  1854. // Kicks off exponential back off logic to retry failed attempt. Starts with one minute
  1855. // delay (60 seconds) if this is the first failed attempt.
  1856. let rescheduleDelay = retry ? min(delay * 2, 16 * 60) : 60
  1857. strongSelf.scheduleAutoTokenRefresh(withDelay: rescheduleDelay, retry: true)
  1858. }
  1859. }
  1860. }
  1861. }
  1862. /// Update the current user; initializing the user's internal properties correctly, and
  1863. /// optionally saving the user to disk.
  1864. ///
  1865. /// This method is called during: sign in and sign out events, as well as during class
  1866. /// initialization time. The only time the saveToDisk parameter should be set to NO is during
  1867. /// class initialization time because the user was just read from disk.
  1868. /// - Parameter user: The user to use as the current user (including nil, which is passed at sign
  1869. /// out time.)
  1870. /// - Parameter saveToDisk: Indicates the method should persist the user data to disk.
  1871. func updateCurrentUser(_ user: User?, byForce force: Bool,
  1872. savingToDisk saveToDisk: Bool) throws {
  1873. if user == _currentUser {
  1874. possiblyPostAuthStateChangeNotification()
  1875. }
  1876. if let user {
  1877. if user.tenantID != nil || tenantID != nil, tenantID != user.tenantID {
  1878. throw AuthErrorUtils.tenantIDMismatchError()
  1879. }
  1880. }
  1881. var throwError: Error?
  1882. if saveToDisk {
  1883. do {
  1884. try saveUser(user)
  1885. } catch {
  1886. throwError = error
  1887. }
  1888. }
  1889. if throwError == nil || force {
  1890. _currentUser = user
  1891. possiblyPostAuthStateChangeNotification()
  1892. }
  1893. if let throwError {
  1894. throw throwError
  1895. }
  1896. }
  1897. private func saveUser(_ user: User?) throws {
  1898. if let userAccessGroup {
  1899. guard let apiKey = app?.options.apiKey else {
  1900. fatalError("Internal Auth Error: Missing apiKey in saveUser")
  1901. }
  1902. if let user {
  1903. try storedUserManager.setStoredUser(user: user,
  1904. accessGroup: userAccessGroup,
  1905. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1906. projectIdentifier: apiKey)
  1907. } else {
  1908. try storedUserManager.removeStoredUser(
  1909. accessGroup: userAccessGroup,
  1910. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1911. projectIdentifier: apiKey
  1912. )
  1913. }
  1914. } else {
  1915. let userKey = "\(firebaseAppName)\(kUserKey)"
  1916. if let user {
  1917. let archiver = NSKeyedArchiver(requiringSecureCoding: true)
  1918. archiver.encode(user, forKey: userKey)
  1919. archiver.finishEncoding()
  1920. let archiveData = archiver.encodedData
  1921. // Save the user object's encoded value.
  1922. try keychainServices.setData(archiveData as Data, forKey: userKey)
  1923. } else {
  1924. try keychainServices.removeData(forKey: userKey)
  1925. }
  1926. }
  1927. }
  1928. /// Completes a sign-in flow once we have access and refresh tokens for the user.
  1929. /// - Parameter accessToken: The STS access token.
  1930. /// - Parameter accessTokenExpirationDate: The approximate expiration date of the access token.
  1931. /// - Parameter refreshToken: The STS refresh token.
  1932. /// - Parameter anonymous: Whether or not the user is anonymous.
  1933. @discardableResult
  1934. func completeSignIn(withAccessToken accessToken: String?,
  1935. accessTokenExpirationDate: Date?,
  1936. refreshToken: String?,
  1937. anonymous: Bool) async throws -> User {
  1938. return try await User.retrieveUser(withAuth: self,
  1939. accessToken: accessToken,
  1940. accessTokenExpirationDate: accessTokenExpirationDate,
  1941. refreshToken: refreshToken,
  1942. anonymous: anonymous)
  1943. }
  1944. /// Signs in using an email address and password.
  1945. ///
  1946. /// This is the internal counterpart of this method, which uses a callback that does not
  1947. /// update the current user.
  1948. /// - Parameter email: The user's email address.
  1949. /// - Parameter password: The user's password.
  1950. private func internalSignInAndRetrieveData(withEmail email: String,
  1951. password: String) async throws -> AuthDataResult {
  1952. let credential = EmailAuthCredential(withEmail: email, password: password)
  1953. return try await internalSignInAndRetrieveData(withCredential: credential,
  1954. isReauthentication: false)
  1955. }
  1956. func internalSignInAndRetrieveData(withCredential credential: AuthCredential,
  1957. isReauthentication: Bool) async throws
  1958. -> AuthDataResult {
  1959. if let emailCredential = credential as? EmailAuthCredential {
  1960. // Special case for email/password credentials
  1961. switch emailCredential.emailType {
  1962. case let .link(link):
  1963. // Email link sign in
  1964. return try await internalSignInAndRetrieveData(withEmail: emailCredential.email, link: link)
  1965. case let .password(password):
  1966. // Email password sign in
  1967. let user = try await internalSignInUser(
  1968. withEmail: emailCredential.email,
  1969. password: password
  1970. )
  1971. let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
  1972. profile: nil,
  1973. username: nil,
  1974. isNewUser: false)
  1975. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  1976. }
  1977. }
  1978. #if !os(watchOS)
  1979. if let gameCenterCredential = credential as? GameCenterAuthCredential {
  1980. return try await signInAndRetrieveData(withGameCenterCredential: gameCenterCredential)
  1981. }
  1982. #endif
  1983. #if os(iOS)
  1984. if let phoneCredential = credential as? PhoneAuthCredential {
  1985. // Special case for phone auth credentials
  1986. let operation = isReauthentication ? AuthOperationType.reauth :
  1987. AuthOperationType.signUpOrSignIn
  1988. let response = try await signIn(withPhoneCredential: phoneCredential,
  1989. operation: operation)
  1990. let user = try await completeSignIn(withAccessToken: response.idToken,
  1991. accessTokenExpirationDate: response
  1992. .approximateExpirationDate,
  1993. refreshToken: response.refreshToken,
  1994. anonymous: false)
  1995. let additionalUserInfo = AdditionalUserInfo(providerID: PhoneAuthProvider.id,
  1996. profile: nil,
  1997. username: nil,
  1998. isNewUser: response.isNewUser)
  1999. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  2000. }
  2001. #endif
  2002. let request = VerifyAssertionRequest(providerID: credential.provider,
  2003. requestConfiguration: requestConfiguration)
  2004. request.autoCreate = !isReauthentication
  2005. credential.prepare(request)
  2006. let response = try await backend.call(with: request)
  2007. if response.needConfirmation {
  2008. let email = response.email
  2009. let credential = OAuthCredential(withVerifyAssertionResponse: response)
  2010. throw AuthErrorUtils.accountExistsWithDifferentCredentialError(
  2011. email: email,
  2012. updatedCredential: credential
  2013. )
  2014. }
  2015. guard let providerID = response.providerID, providerID.count > 0 else {
  2016. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: response)
  2017. }
  2018. let user = try await completeSignIn(withAccessToken: response.idToken,
  2019. accessTokenExpirationDate: response
  2020. .approximateExpirationDate,
  2021. refreshToken: response.refreshToken,
  2022. anonymous: false)
  2023. let additionalUserInfo = AdditionalUserInfo(providerID: providerID,
  2024. profile: response.profile,
  2025. username: response.username,
  2026. isNewUser: response.isNewUser)
  2027. let updatedOAuthCredential = OAuthCredential(withVerifyAssertionResponse: response)
  2028. return AuthDataResult(withUser: user,
  2029. additionalUserInfo: additionalUserInfo,
  2030. credential: updatedOAuthCredential)
  2031. }
  2032. #if os(iOS)
  2033. /// Signs in using a phone credential.
  2034. /// - Parameter credential: The Phone Auth credential used to sign in.
  2035. /// - Parameter operation: The type of operation for which this sign-in attempt is initiated.
  2036. private func signIn(withPhoneCredential credential: PhoneAuthCredential,
  2037. operation: AuthOperationType) async throws -> VerifyPhoneNumberResponse {
  2038. switch credential.credentialKind {
  2039. case let .phoneNumber(phoneNumber, temporaryProof):
  2040. let request = VerifyPhoneNumberRequest(temporaryProof: temporaryProof,
  2041. phoneNumber: phoneNumber,
  2042. operation: operation,
  2043. requestConfiguration: requestConfiguration)
  2044. return try await backend.call(with: request)
  2045. case let .verification(verificationID, code):
  2046. guard verificationID.count > 0 else {
  2047. throw AuthErrorUtils.missingVerificationIDError(message: nil)
  2048. }
  2049. guard code.count > 0 else {
  2050. throw AuthErrorUtils.missingVerificationCodeError(message: nil)
  2051. }
  2052. let request = VerifyPhoneNumberRequest(verificationID: verificationID,
  2053. verificationCode: code,
  2054. operation: operation,
  2055. requestConfiguration: requestConfiguration)
  2056. return try await backend.call(with: request)
  2057. }
  2058. }
  2059. #endif
  2060. #if !os(watchOS)
  2061. /// Signs in using a game center credential.
  2062. /// - Parameter credential: The Game Center Auth Credential used to sign in.
  2063. private func signInAndRetrieveData(withGameCenterCredential credential: GameCenterAuthCredential) async throws
  2064. -> AuthDataResult {
  2065. guard let publicKeyURL = credential.publicKeyURL,
  2066. let signature = credential.signature,
  2067. let salt = credential.salt else {
  2068. fatalError(
  2069. "Internal Auth Error: Game Center credential missing publicKeyURL, signature, or salt"
  2070. )
  2071. }
  2072. let request = SignInWithGameCenterRequest(playerID: credential.playerID,
  2073. teamPlayerID: credential.teamPlayerID,
  2074. gamePlayerID: credential.gamePlayerID,
  2075. publicKeyURL: publicKeyURL,
  2076. signature: signature,
  2077. salt: salt,
  2078. timestamp: credential.timestamp,
  2079. displayName: credential.displayName,
  2080. requestConfiguration: requestConfiguration)
  2081. let response = try await backend.call(with: request)
  2082. let user = try await completeSignIn(withAccessToken: response.idToken,
  2083. accessTokenExpirationDate: response
  2084. .approximateExpirationDate,
  2085. refreshToken: response.refreshToken,
  2086. anonymous: false)
  2087. let additionalUserInfo = AdditionalUserInfo(providerID: GameCenterAuthProvider.id,
  2088. profile: nil,
  2089. username: nil,
  2090. isNewUser: response.isNewUser)
  2091. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  2092. }
  2093. #endif
  2094. /// Signs in using an email and email sign-in link.
  2095. /// - Parameter email: The user's email address.
  2096. /// - Parameter link: The email sign-in link.
  2097. private func internalSignInAndRetrieveData(withEmail email: String,
  2098. link: String) async throws -> AuthDataResult {
  2099. guard isSignIn(withEmailLink: link) else {
  2100. fatalError("The link provided is not valid for email/link sign-in. Please check the link by " +
  2101. "calling isSignIn(withEmailLink:) on the Auth instance before attempting to use it " +
  2102. "for email/link sign-in.")
  2103. }
  2104. let queryItems = getQueryItems(link)
  2105. guard let actionCode = queryItems["oobCode"] else {
  2106. fatalError("Missing oobCode in link URL")
  2107. }
  2108. let request = EmailLinkSignInRequest(email: email,
  2109. oobCode: actionCode,
  2110. requestConfiguration: requestConfiguration)
  2111. let response = try await backend.call(with: request)
  2112. let user = try await completeSignIn(withAccessToken: response.idToken,
  2113. accessTokenExpirationDate: response
  2114. .approximateExpirationDate,
  2115. refreshToken: response.refreshToken,
  2116. anonymous: false)
  2117. let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
  2118. profile: nil,
  2119. username: nil,
  2120. isNewUser: response.isNewUser)
  2121. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  2122. }
  2123. private func getQueryItems(_ link: String) -> [String: String] {
  2124. var queryItems = AuthWebUtils.parseURL(link)
  2125. if queryItems.count == 0 {
  2126. let urlComponents = URLComponents(string: link)
  2127. if let query = urlComponents?.query {
  2128. queryItems = AuthWebUtils.parseURL(query)
  2129. }
  2130. }
  2131. return queryItems
  2132. }
  2133. /// Creates a AuthDataResultCallback block which wraps another AuthDataResultCallback;
  2134. /// trying to update the current user before forwarding it's invocations along to a subject
  2135. /// block.
  2136. ///
  2137. /// Typically invoked as part of the complete sign-in flow. For any other uses please
  2138. /// consider alternative ways of updating the current user.
  2139. /// - Parameter callback: Called when the user has been updated or when an error has occurred.
  2140. /// Invoked asynchronously on the main thread in the future.
  2141. /// - Returns: Returns a block that updates the current user.
  2142. func signInFlowAuthDataResultCallback(byDecorating callback:
  2143. ((AuthDataResult?, Error?) -> Void)?) -> (Result<AuthDataResult, Error>) -> Void {
  2144. return { result in
  2145. switch result {
  2146. case let .success(authResult):
  2147. do {
  2148. try self.updateCurrentUser(authResult.user, byForce: false, savingToDisk: true)
  2149. Auth.wrapMainAsync(callback: callback, with: .success(authResult))
  2150. } catch {
  2151. Auth.wrapMainAsync(callback: callback, with: .failure(error))
  2152. }
  2153. case let .failure(error):
  2154. Auth.wrapMainAsync(callback: callback, with: .failure(error))
  2155. }
  2156. }
  2157. }
  2158. private func wrapAsyncRPCTask(_ request: any AuthRPCRequest, _ callback: ((Error?) -> Void)?) {
  2159. Task {
  2160. do {
  2161. let _ = try await self.backend.call(with: request)
  2162. Auth.wrapMainAsync(callback, nil)
  2163. } catch {
  2164. Auth.wrapMainAsync(callback, error)
  2165. }
  2166. }
  2167. }
  2168. class func wrapMainAsync(_ callback: ((Error?) -> Void)?, _ error: Error?) {
  2169. if let callback {
  2170. DispatchQueue.main.async {
  2171. callback(error)
  2172. }
  2173. }
  2174. }
  2175. class func wrapMainAsync<T: Any>(callback: ((T?, Error?) -> Void)?,
  2176. with result: Result<T, Error>) -> Void {
  2177. guard let callback else { return }
  2178. DispatchQueue.main.async {
  2179. switch result {
  2180. case let .success(success): callback(success, nil)
  2181. case let .failure(error): callback(nil, error)
  2182. }
  2183. }
  2184. }
  2185. #if os(iOS)
  2186. func injectRecaptcha<T: AuthRPCRequest>(request: T,
  2187. action: AuthRecaptchaAction) async throws -> T
  2188. .Response {
  2189. let recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: self)
  2190. if recaptchaVerifier.enablementStatus(forProvider: AuthRecaptchaProvider.password) != .off {
  2191. try await recaptchaVerifier.injectRecaptchaFields(request: request,
  2192. provider: AuthRecaptchaProvider.password,
  2193. action: action)
  2194. } else {
  2195. do {
  2196. return try await backend.call(with: request)
  2197. } catch {
  2198. let nsError = error as NSError
  2199. if let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError,
  2200. nsError.code == AuthErrorCode.internalError.rawValue,
  2201. let messages = underlyingError
  2202. .userInfo[AuthErrorUtils.userInfoDeserializedResponseKey] as? [String: AnyHashable],
  2203. let message = messages["message"] as? String,
  2204. message.hasPrefix("MISSING_RECAPTCHA_TOKEN") {
  2205. try await recaptchaVerifier.injectRecaptchaFields(
  2206. request: request,
  2207. provider: AuthRecaptchaProvider.password,
  2208. action: action
  2209. )
  2210. } else {
  2211. throw error
  2212. }
  2213. }
  2214. }
  2215. return try await backend.call(with: request)
  2216. }
  2217. #endif
  2218. // MARK: Internal properties
  2219. /// Allow tests to swap in an alternate mainBundle, including ObjC unit tests via CocoaPods.
  2220. #if FIREBASE_CI
  2221. @objc public var mainBundleUrlTypes: [[String: Any]]!
  2222. #else
  2223. var mainBundleUrlTypes: [[String: Any]]!
  2224. #endif
  2225. /// The configuration object comprising of parameters needed to make a request to Firebase
  2226. /// Auth's backend.
  2227. let requestConfiguration: AuthRequestConfiguration
  2228. let backend: AuthBackend
  2229. #if os(iOS)
  2230. /// The manager for APNs tokens used by phone number auth.
  2231. var tokenManager: AuthAPNSTokenManager!
  2232. /// The manager for app credentials used by phone number auth.
  2233. var appCredentialManager: AuthAppCredentialManager!
  2234. /// The manager for remote notifications used by phone number auth.
  2235. var notificationManager: AuthNotificationManager!
  2236. /// An object that takes care of presenting URLs via the auth instance.
  2237. var authURLPresenter: AuthWebViewControllerDelegate
  2238. #endif // TARGET_OS_IOS
  2239. // MARK: Private properties
  2240. /// The stored user manager.
  2241. private let storedUserManager: AuthStoredUserManager
  2242. /// The Firebase app name.
  2243. private let firebaseAppName: String
  2244. private let authDispatcher: AuthDispatcher
  2245. /// The keychain service.
  2246. private let keychainServices: AuthKeychainServices
  2247. /// The user access (ID) token used last time for posting auth state changed notification.
  2248. ///
  2249. /// - Note: The atomic wrapper can be removed when the SDK is fully
  2250. /// synchronized with structured concurrency.
  2251. private var lastNotifiedUserToken: String? {
  2252. get { lastNotifiedUserTokenLock.withLock { _lastNotifiedUserToken } }
  2253. set { lastNotifiedUserTokenLock.withLock { _lastNotifiedUserToken = newValue } }
  2254. }
  2255. private var _lastNotifiedUserToken: String?
  2256. private var lastNotifiedUserTokenLock = NSLock()
  2257. /// This flag denotes whether or not tokens should be automatically refreshed.
  2258. /// Will only be set to `true` if the another Firebase service is included (additionally to
  2259. /// Firebase Auth).
  2260. private var autoRefreshTokens = false
  2261. /// Whether or not token auto-refresh is currently scheduled.
  2262. private var autoRefreshScheduled = false
  2263. /// A flag that is set to YES if the app is put in the background and no when the app is
  2264. /// returned to the foreground.
  2265. private var isAppInBackground = false
  2266. /// An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification.
  2267. private var applicationDidBecomeActiveObserver: NSObjectProtocol?
  2268. /// An opaque object to act as the observer for
  2269. /// UIApplicationDidEnterBackgroundNotification.
  2270. private var applicationDidEnterBackgroundObserver: NSObjectProtocol?
  2271. /// An opaque object to act as the observer for
  2272. /// UIApplicationProtectedDataDidBecomeAvailable.
  2273. private var protectedDataDidBecomeAvailableObserver: NSObjectProtocol?
  2274. /// Key of user stored in the keychain. Prefixed with a Firebase app name.
  2275. private let kUserKey = "_firebase_user"
  2276. /// Handles returned from `NSNotificationCenter` for blocks which are "auth state did
  2277. /// change" notification listeners.
  2278. ///
  2279. /// Mutations should occur within a @synchronized(self) context.
  2280. private var listenerHandles: NSMutableArray = []
  2281. }