Auth.swift 106 KB

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