Auth.swift 105 KB

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