Auth.swift 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  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. Task {
  827. do {
  828. let response = try await self.injectRecaptcha(
  829. request: request,
  830. action: AuthRecaptchaAction.signUpPassword
  831. )
  832. self.internalCreateUserWithEmail(
  833. request: request,
  834. inResponse: response,
  835. decoratedCallback: decoratedCallback
  836. )
  837. } catch {
  838. DispatchQueue.main.async {
  839. decoratedCallback(.failure(error))
  840. }
  841. return
  842. }
  843. }
  844. #else
  845. self.internalCreateUserWithEmail(
  846. request: request,
  847. decoratedCallback: decoratedCallback
  848. )
  849. #endif
  850. }
  851. }
  852. private func internalCreateUserWithEmail(request: SignUpNewUserRequest,
  853. inResponse: SignUpNewUserResponse? = nil,
  854. decoratedCallback: @escaping (Result<
  855. AuthDataResult,
  856. Error
  857. >)
  858. -> Void) {
  859. Task {
  860. do {
  861. var response: SignUpNewUserResponse
  862. if let inResponse {
  863. response = inResponse
  864. } else {
  865. response = try await self.backend.call(with: request)
  866. }
  867. let user = try await self.completeSignIn(
  868. withAccessToken: response.idToken,
  869. accessTokenExpirationDate: response.approximateExpirationDate,
  870. refreshToken: response.refreshToken,
  871. anonymous: false
  872. )
  873. let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
  874. profile: nil,
  875. username: nil,
  876. isNewUser: true)
  877. decoratedCallback(
  878. .success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
  879. )
  880. } catch {
  881. decoratedCallback(.failure(error))
  882. }
  883. }
  884. }
  885. /// Creates and, on success, signs in a user with the given email address and password.
  886. ///
  887. /// Possible error codes:
  888. /// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
  889. /// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up
  890. /// already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user
  891. /// used, and prompt the user to sign in with one of those.
  892. /// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts
  893. /// are not enabled. Enable them in the Auth section of the Firebase console.
  894. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  895. /// considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo
  896. /// dictionary object will contain more detailed explanation that can be shown to the user.
  897. /// - Parameter email: The user's email address.
  898. /// - Parameter password: The user's desired password.
  899. /// - Returns: The `AuthDataResult` after the successful signin.
  900. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  901. @discardableResult
  902. open func createUser(withEmail email: String, password: String) async throws -> AuthDataResult {
  903. return try await withCheckedThrowingContinuation { continuation in
  904. self.createUser(withEmail: email, password: password) { result, error in
  905. if let result {
  906. continuation.resume(returning: result)
  907. } else {
  908. continuation.resume(throwing: error!)
  909. }
  910. }
  911. }
  912. }
  913. /// Resets the password given a code sent to the user outside of the app and a new password
  914. /// for the user.
  915. ///
  916. /// Possible error codes:
  917. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  918. /// considered too weak.
  919. /// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign
  920. /// in with the specified identity provider.
  921. /// * `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired.
  922. /// * `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid.
  923. /// - Parameter code: The reset code.
  924. /// - Parameter newPassword: The new password.
  925. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  926. /// Invoked asynchronously on the main thread in the future.
  927. @objc open func confirmPasswordReset(withCode code: String, newPassword: String,
  928. completion: @escaping (Error?) -> Void) {
  929. kAuthGlobalWorkQueue.async {
  930. let request = ResetPasswordRequest(oobCode: code,
  931. newPassword: newPassword,
  932. requestConfiguration: self.requestConfiguration)
  933. self.wrapAsyncRPCTask(request, completion)
  934. }
  935. }
  936. /// Resets the password given a code sent to the user outside of the app and a new password
  937. /// for the user.
  938. ///
  939. /// Possible error codes:
  940. /// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
  941. /// considered too weak.
  942. /// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign
  943. /// in with the specified identity provider.
  944. /// * `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired.
  945. /// * `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid.
  946. /// - Parameter code: The reset code.
  947. /// - Parameter newPassword: The new password.
  948. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  949. open func confirmPasswordReset(withCode code: String, newPassword: String) async throws {
  950. return try await withCheckedThrowingContinuation { continuation in
  951. self.confirmPasswordReset(withCode: code, newPassword: newPassword) { error in
  952. if let error {
  953. continuation.resume(throwing: error)
  954. } else {
  955. continuation.resume()
  956. }
  957. }
  958. }
  959. }
  960. /// Checks the validity of an out of band code.
  961. /// - Parameter code: The out of band code to check validity.
  962. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  963. /// Invoked
  964. /// asynchronously on the main thread in the future.
  965. @objc open func checkActionCode(_ code: String,
  966. completion: @escaping (ActionCodeInfo?, Error?) -> Void) {
  967. kAuthGlobalWorkQueue.async {
  968. let request = ResetPasswordRequest(oobCode: code,
  969. newPassword: nil,
  970. requestConfiguration: self.requestConfiguration)
  971. Task {
  972. do {
  973. let response = try await self.backend.call(with: request)
  974. let operation = ActionCodeInfo.actionCodeOperation(forRequestType: response.requestType)
  975. guard let email = response.email else {
  976. fatalError("Internal Auth Error: Failed to get a ResetPasswordResponse")
  977. }
  978. let actionCodeInfo = ActionCodeInfo(withOperation: operation,
  979. email: email,
  980. newEmail: response.verifiedEmail)
  981. Auth.wrapMainAsync(callback: completion, with: .success(actionCodeInfo))
  982. } catch {
  983. Auth.wrapMainAsync(callback: completion, with: .failure(error))
  984. }
  985. }
  986. }
  987. }
  988. /// Checks the validity of an out of band code.
  989. /// - Parameter code: The out of band code to check validity.
  990. /// - Returns: An `ActionCodeInfo`.
  991. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  992. open func checkActionCode(_ code: String) async throws -> ActionCodeInfo {
  993. return try await withCheckedThrowingContinuation { continuation in
  994. self.checkActionCode(code) { info, error in
  995. if let info {
  996. continuation.resume(returning: info)
  997. } else {
  998. continuation.resume(throwing: error!)
  999. }
  1000. }
  1001. }
  1002. }
  1003. /// Checks the validity of a verify password reset code.
  1004. /// - Parameter code: The password reset code to be verified.
  1005. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1006. /// Invoked asynchronously on the main thread in the future.
  1007. @objc open func verifyPasswordResetCode(_ code: String,
  1008. completion: @escaping (String?, Error?) -> Void) {
  1009. checkActionCode(code) { info, error in
  1010. if let error {
  1011. completion(nil, error)
  1012. return
  1013. }
  1014. completion(info?.email, nil)
  1015. }
  1016. }
  1017. /// Checks the validity of a verify password reset code.
  1018. /// - Parameter code: The password reset code to be verified.
  1019. /// - Returns: An email.
  1020. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1021. open func verifyPasswordResetCode(_ code: String) async throws -> String {
  1022. return try await withCheckedThrowingContinuation { continuation in
  1023. self.verifyPasswordResetCode(code) { code, error in
  1024. if let code {
  1025. continuation.resume(returning: code)
  1026. } else {
  1027. continuation.resume(throwing: error!)
  1028. }
  1029. }
  1030. }
  1031. }
  1032. /// Applies out of band code.
  1033. ///
  1034. /// This method will not work for out of band codes which require an additional parameter,
  1035. /// such as password reset code.
  1036. /// - Parameter code: The out of band code to be applied.
  1037. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1038. /// Invoked asynchronously on the main thread in the future.
  1039. @objc open func applyActionCode(_ code: String, completion: @escaping (Error?) -> Void) {
  1040. kAuthGlobalWorkQueue.async {
  1041. let request = SetAccountInfoRequest(requestConfiguration: self.requestConfiguration)
  1042. request.oobCode = code
  1043. self.wrapAsyncRPCTask(request, completion)
  1044. }
  1045. }
  1046. /// Applies out of band code.
  1047. ///
  1048. /// This method will not work for out of band codes which require an additional parameter,
  1049. /// such as password reset code.
  1050. /// - Parameter code: The out of band code to be applied.
  1051. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1052. open func applyActionCode(_ code: String) async throws {
  1053. return try await withCheckedThrowingContinuation { continuation in
  1054. self.applyActionCode(code) { error in
  1055. if let error {
  1056. continuation.resume(throwing: error)
  1057. } else {
  1058. continuation.resume()
  1059. }
  1060. }
  1061. }
  1062. }
  1063. /// Initiates a password reset for the given email address.
  1064. ///
  1065. /// This method does not throw an
  1066. /// error when there's no user account with the given email address and [Email Enumeration
  1067. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  1068. /// is enabled.
  1069. ///
  1070. /// Possible error codes:
  1071. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  1072. /// sent in the request.
  1073. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  1074. /// the console for this action.
  1075. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  1076. /// sending update email.
  1077. /// - Parameter email: The email address of the user.
  1078. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1079. /// Invoked
  1080. /// asynchronously on the main thread in the future.
  1081. @objc open func sendPasswordReset(withEmail email: String,
  1082. completion: ((Error?) -> Void)? = nil) {
  1083. sendPasswordReset(withEmail: email, actionCodeSettings: nil, completion: completion)
  1084. }
  1085. /// Initiates a password reset for the given email address and `ActionCodeSettings` object.
  1086. ///
  1087. /// This method does not throw an
  1088. /// error when there's no user account with the given email address and [Email Enumeration
  1089. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  1090. /// is enabled.
  1091. ///
  1092. /// Possible error codes:
  1093. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  1094. /// sent in the request.
  1095. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  1096. /// the console for this action.
  1097. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  1098. /// sending update email.
  1099. /// * `AuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing when
  1100. /// `handleCodeInApp` is set to true.
  1101. /// * `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name
  1102. /// is missing when the `androidInstallApp` flag is set to true.
  1103. /// * `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the
  1104. /// continue URL is not allowlisted in the Firebase console.
  1105. /// * `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the
  1106. /// continue URL is not valid.
  1107. /// - Parameter email: The email address of the user.
  1108. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1109. /// handling action codes.
  1110. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1111. /// Invoked asynchronously on the main thread in the future.
  1112. @objc open func sendPasswordReset(withEmail email: String,
  1113. actionCodeSettings: ActionCodeSettings?,
  1114. completion: ((Error?) -> Void)? = nil) {
  1115. kAuthGlobalWorkQueue.async {
  1116. let request = GetOOBConfirmationCodeRequest.passwordResetRequest(
  1117. email: email,
  1118. actionCodeSettings: actionCodeSettings,
  1119. requestConfiguration: self.requestConfiguration
  1120. )
  1121. #if os(iOS)
  1122. Task {
  1123. do {
  1124. _ = try await self.injectRecaptcha(
  1125. request: request,
  1126. action: AuthRecaptchaAction.getOobCode
  1127. )
  1128. Auth.wrapMainAsync(completion, nil)
  1129. } catch {
  1130. Auth.wrapMainAsync(completion, error)
  1131. }
  1132. }
  1133. #else
  1134. self.wrapAsyncRPCTask(request, completion)
  1135. #endif
  1136. }
  1137. }
  1138. /// Initiates a password reset for the given email address and `ActionCodeSettings` object.
  1139. ///
  1140. /// This method does not throw an
  1141. /// error when there's no user account with the given email address and [Email Enumeration
  1142. /// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
  1143. /// is enabled.
  1144. ///
  1145. /// Possible error codes:
  1146. /// * `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was
  1147. /// sent in the request.
  1148. /// * `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in
  1149. /// the console for this action.
  1150. /// * `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for
  1151. /// sending update email.
  1152. /// * `AuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing when
  1153. /// `handleCodeInApp` is set to true.
  1154. /// * `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name
  1155. /// is missing when the `androidInstallApp` flag is set to true.
  1156. /// * `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the
  1157. /// continue URL is not allowlisted in the Firebase console.
  1158. /// * `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the
  1159. /// continue URL is not valid.
  1160. /// - Parameter email: The email address of the user.
  1161. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1162. /// handling action codes.
  1163. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1164. open func sendPasswordReset(withEmail email: String,
  1165. actionCodeSettings: ActionCodeSettings? = nil) async throws {
  1166. return try await withCheckedThrowingContinuation { continuation in
  1167. self.sendPasswordReset(withEmail: email, actionCodeSettings: actionCodeSettings) { error in
  1168. if let error {
  1169. continuation.resume(throwing: error)
  1170. } else {
  1171. continuation.resume()
  1172. }
  1173. }
  1174. }
  1175. }
  1176. /// Sends a sign in with email link to provided email address.
  1177. /// - Parameter email: The email address of the user.
  1178. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1179. /// handling action codes.
  1180. /// - Parameter completion: Optionally; a block which is invoked when the request finishes.
  1181. /// Invoked asynchronously on the main thread in the future.
  1182. @objc open func sendSignInLink(toEmail email: String,
  1183. actionCodeSettings: ActionCodeSettings,
  1184. completion: ((Error?) -> Void)? = nil) {
  1185. if !actionCodeSettings.handleCodeInApp {
  1186. fatalError("The handleCodeInApp flag in ActionCodeSettings must be true for Email-link " +
  1187. "Authentication.")
  1188. }
  1189. kAuthGlobalWorkQueue.async {
  1190. let request = GetOOBConfirmationCodeRequest.signInWithEmailLinkRequest(
  1191. email,
  1192. actionCodeSettings: actionCodeSettings,
  1193. requestConfiguration: self.requestConfiguration
  1194. )
  1195. #if os(iOS)
  1196. Task {
  1197. do {
  1198. _ = try await self.injectRecaptcha(
  1199. request: request,
  1200. action: AuthRecaptchaAction.getOobCode
  1201. )
  1202. Auth.wrapMainAsync(completion, nil)
  1203. } catch {
  1204. Auth.wrapMainAsync(completion, error)
  1205. }
  1206. }
  1207. #else
  1208. self.wrapAsyncRPCTask(request, completion)
  1209. #endif
  1210. }
  1211. }
  1212. /// Sends a sign in with email link to provided email address.
  1213. /// - Parameter email: The email address of the user.
  1214. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to
  1215. /// handling action codes.
  1216. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1217. open func sendSignInLink(toEmail email: String,
  1218. actionCodeSettings: ActionCodeSettings) async throws {
  1219. return try await withCheckedThrowingContinuation { continuation in
  1220. self.sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in
  1221. if let error {
  1222. continuation.resume(throwing: error)
  1223. } else {
  1224. continuation.resume()
  1225. }
  1226. }
  1227. }
  1228. }
  1229. /// Signs out the current user.
  1230. ///
  1231. /// Possible error codes:
  1232. /// * `AuthErrorCodeKeychainError` - Indicates an error occurred when accessing the
  1233. /// keychain. The `NSLocalizedFailureReasonErrorKey` field in the `userInfo`
  1234. /// dictionary will contain more information about the error encountered.
  1235. @objc(signOut:) open func signOut() throws {
  1236. try kAuthGlobalWorkQueue.sync {
  1237. guard self._currentUser != nil else {
  1238. return
  1239. }
  1240. return try self.updateCurrentUser(nil, byForce: false, savingToDisk: true)
  1241. }
  1242. }
  1243. /// Checks if link is an email sign-in link.
  1244. /// - Parameter link: The email sign-in link.
  1245. /// - Returns: `true` when the link passed matches the expected format of an email sign-in link.
  1246. @objc open func isSignIn(withEmailLink link: String) -> Bool {
  1247. guard link.count > 0 else {
  1248. return false
  1249. }
  1250. let queryItems = getQueryItems(link)
  1251. if let _ = queryItems["oobCode"],
  1252. let mode = queryItems["mode"],
  1253. mode == "signIn" {
  1254. return true
  1255. }
  1256. return false
  1257. }
  1258. #if os(iOS) && !targetEnvironment(macCatalyst)
  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. @objc(initializeRecaptchaConfigWithCompletion:)
  1264. open func initializeRecaptchaConfig(completion: ((Error?) -> Void)?) {
  1265. Task {
  1266. do {
  1267. try await initializeRecaptchaConfig()
  1268. if let completion {
  1269. completion(nil)
  1270. }
  1271. } catch {
  1272. if let completion {
  1273. completion(error)
  1274. }
  1275. }
  1276. }
  1277. }
  1278. /// Initializes reCAPTCHA using the settings configured for the project or tenant.
  1279. ///
  1280. /// If you change the tenant ID of the `Auth` instance, the configuration will be
  1281. /// reloaded.
  1282. open func initializeRecaptchaConfig() async throws {
  1283. // Trigger recaptcha verification flow to initialize the recaptcha client and
  1284. // config. Recaptcha token will be returned.
  1285. let verifier = AuthRecaptchaVerifier.shared(auth: self)
  1286. _ = try await verifier.verify(forceRefresh: true, action: AuthRecaptchaAction.defaultAction)
  1287. }
  1288. #endif
  1289. /// Registers a block as an "auth state did change" listener.
  1290. ///
  1291. /// To be invoked when:
  1292. /// * The block is registered as a listener,
  1293. /// * A user with a different UID from the current user has signed in, or
  1294. /// * The current user has signed out.
  1295. ///
  1296. /// The block is invoked immediately after adding it according to its standard invocation
  1297. /// semantics, asynchronously on the main thread. Users should pay special attention to
  1298. /// making sure the block does not inadvertently retain objects which should not be retained by
  1299. /// the long-lived block. The block itself will be retained by `Auth` until it is
  1300. /// unregistered or until the `Auth` instance is otherwise deallocated.
  1301. /// - Parameter listener: The block to be invoked. The block is always invoked asynchronously on
  1302. /// the main thread, even for it's initial invocation after having been added as a listener.
  1303. /// - Returns: A handle useful for manually unregistering the block as a listener.
  1304. @objc(addAuthStateDidChangeListener:)
  1305. open func addStateDidChangeListener(_ listener: @escaping (Auth, User?) -> Void)
  1306. -> NSObjectProtocol {
  1307. var firstInvocation = true
  1308. var previousUserID: String?
  1309. return addIDTokenDidChangeListener { auth, user in
  1310. let shouldCallListener = firstInvocation || previousUserID != user?.uid
  1311. firstInvocation = false
  1312. previousUserID = user?.uid
  1313. if shouldCallListener {
  1314. listener(auth, user)
  1315. }
  1316. }
  1317. }
  1318. /// Unregisters a block as an "auth state did change" listener.
  1319. /// - Parameter listenerHandle: The handle for the listener.
  1320. @objc(removeAuthStateDidChangeListener:)
  1321. open func removeStateDidChangeListener(_ listenerHandle: NSObjectProtocol) {
  1322. NotificationCenter.default.removeObserver(listenerHandle)
  1323. objc_sync_enter(Auth.self)
  1324. defer { objc_sync_exit(Auth.self) }
  1325. listenerHandles.remove(listenerHandle)
  1326. }
  1327. /// Registers a block as an "ID token did change" listener.
  1328. ///
  1329. /// To be invoked when:
  1330. /// * The block is registered as a listener,
  1331. /// * A user with a different UID from the current user has signed in,
  1332. /// * The ID token of the current user has been refreshed, or
  1333. /// * The current user has signed out.
  1334. ///
  1335. /// The block is invoked immediately after adding it according to its standard invocation
  1336. /// semantics, asynchronously on the main thread. Users should pay special attention to
  1337. /// making sure the block does not inadvertently retain objects which should not be retained by
  1338. /// the long-lived block. The block itself will be retained by `Auth` until it is
  1339. /// unregistered or until the `Auth` instance is otherwise deallocated.
  1340. /// - Parameter listener: The block to be invoked. The block is always invoked asynchronously on
  1341. /// the main thread, even for it's initial invocation after having been added as a listener.
  1342. /// - Returns: A handle useful for manually unregistering the block as a listener.
  1343. @objc open func addIDTokenDidChangeListener(_ listener: @escaping (Auth, User?) -> Void)
  1344. -> NSObjectProtocol {
  1345. let handle = NotificationCenter.default.addObserver(
  1346. forName: Auth.authStateDidChangeNotification,
  1347. object: self,
  1348. queue: OperationQueue.main
  1349. ) { notification in
  1350. if let auth = notification.object as? Auth {
  1351. listener(auth, auth._currentUser)
  1352. }
  1353. }
  1354. objc_sync_enter(Auth.self)
  1355. listenerHandles.add(listener)
  1356. objc_sync_exit(Auth.self)
  1357. DispatchQueue.main.async {
  1358. listener(self, self._currentUser)
  1359. }
  1360. return handle
  1361. }
  1362. /// Unregisters a block as an "ID token did change" listener.
  1363. /// - Parameter listenerHandle: The handle for the listener.
  1364. @objc open func removeIDTokenDidChangeListener(_ listenerHandle: NSObjectProtocol) {
  1365. NotificationCenter.default.removeObserver(listenerHandle)
  1366. objc_sync_enter(Auth.self)
  1367. listenerHandles.remove(listenerHandle)
  1368. objc_sync_exit(Auth.self)
  1369. }
  1370. /// Sets `languageCode` to the app's current language.
  1371. @objc open func useAppLanguage() {
  1372. kAuthGlobalWorkQueue.sync {
  1373. self.requestConfiguration.languageCode = Locale.preferredLanguages.first
  1374. }
  1375. }
  1376. /// Configures Firebase Auth to connect to an emulated host instead of the remote backend.
  1377. @objc open func useEmulator(withHost host: String, port: Int) {
  1378. guard host.count > 0 else {
  1379. fatalError("Cannot connect to empty host")
  1380. }
  1381. // If host is an IPv6 address, it should be formatted with surrounding brackets.
  1382. let formattedHost = host.contains(":") ? "[\(host)]" : host
  1383. kAuthGlobalWorkQueue.sync {
  1384. self.requestConfiguration.emulatorHostAndPort = "\(formattedHost):\(port)"
  1385. #if os(iOS)
  1386. self.settings?.appVerificationDisabledForTesting = true
  1387. #endif
  1388. }
  1389. }
  1390. /// Revoke the users token with authorization code.
  1391. /// - Parameter authorizationCode: The authorization code used to perform the revocation.
  1392. /// - Parameter completion: (Optional) the block invoked when the request to revoke the token is
  1393. /// complete, or fails. Invoked asynchronously on the main thread in the future.
  1394. @objc open func revokeToken(withAuthorizationCode authorizationCode: String,
  1395. completion: ((Error?) -> Void)? = nil) {
  1396. _currentUser?.internalGetToken(backend: backend) { idToken, error in
  1397. if let error {
  1398. Auth.wrapMainAsync(completion, error)
  1399. return
  1400. }
  1401. guard let idToken else {
  1402. fatalError("Internal Auth Error: Both idToken and error are nil")
  1403. }
  1404. let request = RevokeTokenRequest(withToken: authorizationCode,
  1405. idToken: idToken,
  1406. requestConfiguration: self.requestConfiguration)
  1407. self.wrapAsyncRPCTask(request, completion)
  1408. }
  1409. }
  1410. /// Revoke the users token with authorization code.
  1411. /// - Parameter authorizationCode: The authorization code used to perform the revocation.
  1412. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  1413. open func revokeToken(withAuthorizationCode authorizationCode: String) async throws {
  1414. return try await withCheckedThrowingContinuation { continuation in
  1415. self.revokeToken(withAuthorizationCode: authorizationCode) { error in
  1416. if let error {
  1417. continuation.resume(throwing: error)
  1418. } else {
  1419. continuation.resume()
  1420. }
  1421. }
  1422. }
  1423. }
  1424. /// Switch userAccessGroup and current user to the given accessGroup and the user stored in it.
  1425. @objc open func useUserAccessGroup(_ accessGroup: String?) throws {
  1426. // self.storedUserManager is initialized asynchronously. Make sure it is done.
  1427. kAuthGlobalWorkQueue.sync {}
  1428. return try internalUseUserAccessGroup(accessGroup)
  1429. }
  1430. private func internalUseUserAccessGroup(_ accessGroup: String?) throws {
  1431. storedUserManager.setStoredUserAccessGroup(accessGroup: accessGroup)
  1432. let user = try getStoredUser(forAccessGroup: accessGroup)
  1433. try updateCurrentUser(user, byForce: false, savingToDisk: false)
  1434. if userAccessGroup == nil, accessGroup != nil {
  1435. let userKey = "\(firebaseAppName)\(kUserKey)"
  1436. try keychainServices.removeData(forKey: userKey)
  1437. }
  1438. userAccessGroup = accessGroup
  1439. lastNotifiedUserToken = user?.rawAccessToken()
  1440. }
  1441. /// Get the stored user in the given accessGroup.
  1442. ///
  1443. /// This API is not supported on tvOS when `shareAuthStateAcrossDevices` is set to `true`.
  1444. /// and will return `nil`.
  1445. /// Please refer to https://github.com/firebase/firebase-ios-sdk/issues/8878 for details.
  1446. @available(swift 1000.0) // Objective-C only API
  1447. @objc(getStoredUserForAccessGroup:error:)
  1448. open func __getStoredUser(forAccessGroup accessGroup: String?,
  1449. error outError: NSErrorPointer) -> User? {
  1450. do {
  1451. return try getStoredUser(forAccessGroup: accessGroup)
  1452. } catch {
  1453. outError?.pointee = error as NSError
  1454. return nil
  1455. }
  1456. }
  1457. /// Get the stored user in the given accessGroup.
  1458. ///
  1459. /// This API is not supported on tvOS when `shareAuthStateAcrossDevices` is set to `true`.
  1460. /// and will return `nil`.
  1461. ///
  1462. /// Please refer to https://github.com/firebase/firebase-ios-sdk/issues/8878 for details.
  1463. open func getStoredUser(forAccessGroup accessGroup: String?) throws -> User? {
  1464. var user: User?
  1465. if let accessGroup {
  1466. #if os(tvOS)
  1467. if shareAuthStateAcrossDevices {
  1468. AuthLog.logError(code: "I-AUT000001",
  1469. message: "Getting a stored user for a given access group is not supported " +
  1470. "on tvOS when `shareAuthStateAcrossDevices` is set to `true` (#8878)." +
  1471. "This case will return `nil`.")
  1472. return nil
  1473. }
  1474. #endif
  1475. guard let apiKey = app?.options.apiKey else {
  1476. fatalError("Internal Auth Error: missing apiKey")
  1477. }
  1478. user = try storedUserManager.getStoredUser(
  1479. accessGroup: accessGroup,
  1480. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1481. projectIdentifier: apiKey
  1482. )
  1483. } else {
  1484. let userKey = "\(firebaseAppName)\(kUserKey)"
  1485. if let encodedUserData = try keychainServices.data(forKey: userKey) {
  1486. let unarchiver = try NSKeyedUnarchiver(forReadingFrom: encodedUserData)
  1487. user = unarchiver.decodeObject(of: User.self, forKey: userKey)
  1488. }
  1489. }
  1490. user?.auth = self
  1491. return user
  1492. }
  1493. #if os(iOS)
  1494. /// The APNs token used for phone number authentication.
  1495. ///
  1496. /// The type of the token (production or sandbox) will be automatically
  1497. /// detected based on your provisioning profile.
  1498. ///
  1499. /// This property is available on iOS only.
  1500. ///
  1501. /// If swizzling is disabled, the APNs Token must be set for phone number auth to work,
  1502. /// by either setting this property or by calling `setAPNSToken(_:type:)`.
  1503. @objc(APNSToken) open var apnsToken: Data? {
  1504. kAuthGlobalWorkQueue.sync {
  1505. self.tokenManager.token?.data
  1506. }
  1507. }
  1508. /// Sets the APNs token along with its type.
  1509. ///
  1510. /// This method is available on iOS only.
  1511. ///
  1512. /// If swizzling is disabled, the APNs Token must be set for phone number auth to work,
  1513. /// by either setting calling this method or by setting the `APNSToken` property.
  1514. @objc open func setAPNSToken(_ token: Data, type: AuthAPNSTokenType) {
  1515. kAuthGlobalWorkQueue.sync {
  1516. self.tokenManager.token = AuthAPNSToken(withData: token, type: type)
  1517. }
  1518. }
  1519. /// Whether the specific remote notification is handled by `Auth` .
  1520. ///
  1521. /// This method is available on iOS only.
  1522. ///
  1523. /// If swizzling is disabled, related remote notifications must be forwarded to this method
  1524. /// for phone number auth to work.
  1525. /// - Parameter userInfo: A dictionary that contains information related to the
  1526. /// notification in question.
  1527. /// - Returns: Whether or the notification is handled. A return value of `true` means the
  1528. /// notification is for Firebase Auth so the caller should ignore the notification from further
  1529. /// processing, and `false` means the notification is for the app (or another library) so
  1530. /// the caller should continue handling this notification as usual.
  1531. @objc open func canHandleNotification(_ userInfo: [AnyHashable: Any]) -> Bool {
  1532. kAuthGlobalWorkQueue.sync {
  1533. self.notificationManager.canHandle(notification: userInfo)
  1534. }
  1535. }
  1536. /// Whether the specific URL is handled by `Auth` .
  1537. ///
  1538. /// This method is available on iOS only.
  1539. ///
  1540. /// If swizzling is disabled, URLs received by the application delegate must be forwarded
  1541. /// to this method for phone number auth to work.
  1542. /// - Parameter url: The URL received by the application delegate from any of the openURL
  1543. /// method.
  1544. /// - Returns: Whether or the URL is handled. `true` means the URL is for Firebase Auth
  1545. /// so the caller should ignore the URL from further processing, and `false` means the
  1546. /// the URL is for the app (or another library) so the caller should continue handling
  1547. /// this URL as usual.
  1548. @objc(canHandleURL:) open func canHandle(_ url: URL) -> Bool {
  1549. kAuthGlobalWorkQueue.sync {
  1550. guard let authURLPresenter = self.authURLPresenter as? AuthURLPresenter else {
  1551. return false
  1552. }
  1553. return authURLPresenter.canHandle(url: url)
  1554. }
  1555. }
  1556. #endif
  1557. /// The name of the `NSNotificationCenter` notification which is posted when the auth state
  1558. /// changes (for example, a new token has been produced, a user signs in or signs out).
  1559. ///
  1560. /// The object parameter of the notification is the sender `Auth` instance.
  1561. public static let authStateDidChangeNotification =
  1562. NSNotification.Name(rawValue: "FIRAuthStateDidChangeNotification")
  1563. // MARK: Internal methods
  1564. init(app: FirebaseApp,
  1565. keychainStorageProvider: AuthKeychainStorage = AuthKeychainStorageReal.shared,
  1566. backend: AuthBackend = .init(rpcIssuer: AuthBackendRPCIssuer()),
  1567. authDispatcher: AuthDispatcher = .init()) {
  1568. self.app = app
  1569. mainBundleUrlTypes = Bundle.main
  1570. .object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]]
  1571. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  1572. in: app.container)
  1573. guard let apiKey = app.options.apiKey else {
  1574. fatalError("Missing apiKey for Auth initialization")
  1575. }
  1576. firebaseAppName = app.name
  1577. #if os(iOS)
  1578. authURLPresenter = AuthURLPresenter()
  1579. settings = AuthSettings()
  1580. GULAppDelegateSwizzler.proxyOriginalDelegateIncludingAPNSMethods()
  1581. GULSceneDelegateSwizzler.proxyOriginalSceneDelegate()
  1582. #endif
  1583. requestConfiguration = AuthRequestConfiguration(apiKey: apiKey,
  1584. appID: app.options.googleAppID,
  1585. auth: nil,
  1586. heartbeatLogger: app.heartbeatLogger,
  1587. appCheck: appCheck)
  1588. self.backend = backend
  1589. self.authDispatcher = authDispatcher
  1590. let keychainServiceName = Auth.keychainServiceName(for: app)
  1591. keychainServices = AuthKeychainServices(service: keychainServiceName,
  1592. storage: keychainStorageProvider)
  1593. storedUserManager = AuthStoredUserManager(
  1594. serviceName: keychainServiceName,
  1595. keychainServices: keychainServices
  1596. )
  1597. super.init()
  1598. requestConfiguration.auth = self
  1599. protectedDataInitialization()
  1600. }
  1601. private func protectedDataInitialization() {
  1602. // Continue with the rest of initialization in the work thread.
  1603. kAuthGlobalWorkQueue.async { [weak self] in
  1604. // Load current user from Keychain.
  1605. guard let self else {
  1606. return
  1607. }
  1608. do {
  1609. if let storedUserAccessGroup = self.storedUserManager.getStoredUserAccessGroup() {
  1610. try self.internalUseUserAccessGroup(storedUserAccessGroup)
  1611. } else {
  1612. let user = try self.getUser()
  1613. if let user {
  1614. self.tenantID = user.tenantID
  1615. }
  1616. try self.updateCurrentUser(user, byForce: false, savingToDisk: false)
  1617. if let user {
  1618. self.lastNotifiedUserToken = user.rawAccessToken()
  1619. }
  1620. }
  1621. } catch {
  1622. #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
  1623. if (error as NSError).code == AuthErrorCode.keychainError.rawValue {
  1624. // If there's a keychain error, assume it is due to the keychain being accessed
  1625. // before the device is unlocked as a result of prewarming, and listen for the
  1626. // UIApplicationProtectedDataDidBecomeAvailable notification.
  1627. self.addProtectedDataDidBecomeAvailableObserver()
  1628. }
  1629. #endif
  1630. AuthLog.logError(code: "I-AUT000001",
  1631. message: "Error loading saved user when starting up: \(error)")
  1632. }
  1633. #if os(iOS)
  1634. if GULAppEnvironmentUtil.isAppExtension() {
  1635. // iOS App extensions should not call [UIApplication sharedApplication], even if
  1636. // UIApplication responds to it.
  1637. return
  1638. }
  1639. // Using reflection here to avoid build errors in extensions.
  1640. let sel = NSSelectorFromString("sharedApplication")
  1641. guard UIApplication.responds(to: sel),
  1642. let rawApplication = UIApplication.perform(sel),
  1643. let application = rawApplication.takeUnretainedValue() as? UIApplication else {
  1644. return
  1645. }
  1646. // Initialize for phone number auth.
  1647. self.tokenManager = AuthAPNSTokenManager(withApplication: application)
  1648. self.appCredentialManager = AuthAppCredentialManager(withKeychain: self.keychainServices)
  1649. self.notificationManager = AuthNotificationManager(
  1650. withApplication: application,
  1651. appCredentialManager: self.appCredentialManager
  1652. )
  1653. GULAppDelegateSwizzler.registerAppDelegateInterceptor(self)
  1654. GULSceneDelegateSwizzler.registerSceneDelegateInterceptor(self)
  1655. #endif
  1656. }
  1657. }
  1658. #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
  1659. private func addProtectedDataDidBecomeAvailableObserver() {
  1660. protectedDataDidBecomeAvailableObserver =
  1661. NotificationCenter.default.addObserver(
  1662. forName: UIApplication.protectedDataDidBecomeAvailableNotification,
  1663. object: nil,
  1664. queue: nil
  1665. ) { [weak self] notification in
  1666. guard let self else { return }
  1667. if let observer = self.protectedDataDidBecomeAvailableObserver {
  1668. NotificationCenter.default.removeObserver(
  1669. observer,
  1670. name: UIApplication.protectedDataDidBecomeAvailableNotification,
  1671. object: nil
  1672. )
  1673. }
  1674. self.protectedDataInitialization()
  1675. }
  1676. }
  1677. #endif
  1678. deinit {
  1679. let defaultCenter = NotificationCenter.default
  1680. while listenerHandles.count > 0 {
  1681. let handleToRemove = listenerHandles.lastObject
  1682. defaultCenter.removeObserver(handleToRemove as Any)
  1683. listenerHandles.removeLastObject()
  1684. }
  1685. #if os(iOS)
  1686. defaultCenter.removeObserver(applicationDidBecomeActiveObserver as Any,
  1687. name: UIApplication.didBecomeActiveNotification,
  1688. object: nil)
  1689. defaultCenter.removeObserver(applicationDidEnterBackgroundObserver as Any,
  1690. name: UIApplication.didEnterBackgroundNotification,
  1691. object: nil)
  1692. #endif
  1693. }
  1694. private func getUser() throws -> User? {
  1695. var user: User?
  1696. if let userAccessGroup {
  1697. guard let apiKey = app?.options.apiKey else {
  1698. fatalError("Internal Auth Error: missing apiKey")
  1699. }
  1700. user = try storedUserManager.getStoredUser(
  1701. accessGroup: userAccessGroup,
  1702. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1703. projectIdentifier: apiKey
  1704. )
  1705. } else {
  1706. let userKey = "\(firebaseAppName)\(kUserKey)"
  1707. guard let encodedUserData = try keychainServices.data(forKey: userKey) else {
  1708. return nil
  1709. }
  1710. let unarchiver = try NSKeyedUnarchiver(forReadingFrom: encodedUserData)
  1711. user = unarchiver.decodeObject(of: User.self, forKey: userKey)
  1712. }
  1713. user?.auth = self
  1714. return user
  1715. }
  1716. /// Gets the keychain service name global data for the particular app by name.
  1717. /// - Parameter appName: The name of the Firebase app to get keychain service name for.
  1718. class func keychainServiceForAppID(_ appID: String) -> String {
  1719. return "firebase_auth_\(appID)"
  1720. }
  1721. func updateKeychain(withUser user: User?) -> Error? {
  1722. if user != _currentUser {
  1723. // No-op if the user is no longer signed in. This is not considered an error as we don't check
  1724. // whether the user is still current on other callbacks of user operations either.
  1725. return nil
  1726. }
  1727. do {
  1728. try saveUser(user)
  1729. possiblyPostAuthStateChangeNotification()
  1730. } catch {
  1731. return error
  1732. }
  1733. return nil
  1734. }
  1735. /// A map from Firebase app name to keychain service names.
  1736. ///
  1737. /// This map is needed for looking up the keychain service name after the FirebaseApp instance
  1738. /// is deleted, to remove the associated keychain item. Accessing should occur within a
  1739. /// @synchronized([FIRAuth class]) context.
  1740. fileprivate static var gKeychainServiceNameForAppName: [String: String] = [:]
  1741. /// Gets the keychain service name global data for the particular app by
  1742. /// name, creating an entry for one if it does not exist.
  1743. /// - Parameter app: The Firebase app to get the keychain service name for.
  1744. /// - Returns: The keychain service name for the given app.
  1745. static func keychainServiceName(for app: FirebaseApp) -> String {
  1746. objc_sync_enter(Auth.self)
  1747. defer { objc_sync_exit(Auth.self) }
  1748. let appName = app.name
  1749. if let serviceName = gKeychainServiceNameForAppName[appName] {
  1750. return serviceName
  1751. } else {
  1752. let serviceName = "firebase_auth_\(app.options.googleAppID)"
  1753. gKeychainServiceNameForAppName[appName] = serviceName
  1754. return serviceName
  1755. }
  1756. }
  1757. /// Deletes the keychain service name global data for the particular app by name.
  1758. /// - Parameter appName: The name of the Firebase app to delete keychain service name for.
  1759. /// - Returns: The deleted keychain service name, if any.
  1760. static func deleteKeychainServiceNameForAppName(_ appName: String) -> String? {
  1761. objc_sync_enter(Auth.self)
  1762. defer { objc_sync_exit(Auth.self) }
  1763. guard let serviceName = gKeychainServiceNameForAppName[appName] else {
  1764. return nil
  1765. }
  1766. gKeychainServiceNameForAppName.removeValue(forKey: appName)
  1767. return serviceName
  1768. }
  1769. func signOutByForce(withUserID userID: String) throws {
  1770. guard _currentUser?.uid == userID else {
  1771. return
  1772. }
  1773. try updateCurrentUser(nil, byForce: true, savingToDisk: true)
  1774. }
  1775. // MARK: Private methods
  1776. /// Posts the auth state change notification if current user's token has been changed.
  1777. private func possiblyPostAuthStateChangeNotification() {
  1778. let token = _currentUser?.rawAccessToken()
  1779. if lastNotifiedUserToken == token ||
  1780. (token != nil && lastNotifiedUserToken == token) {
  1781. return
  1782. }
  1783. lastNotifiedUserToken = token
  1784. if autoRefreshTokens {
  1785. // Schedule new refresh task after successful attempt.
  1786. scheduleAutoTokenRefresh()
  1787. }
  1788. var internalNotificationParameters: [String: Any] = [:]
  1789. if let app = app {
  1790. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationAppKey] = app
  1791. }
  1792. if let token, token.count > 0 {
  1793. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationTokenKey] = token
  1794. }
  1795. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationUIDKey] = _currentUser?
  1796. .uid
  1797. let notifications = NotificationCenter.default
  1798. DispatchQueue.main.async {
  1799. notifications.post(name: NSNotification.Name.FIRAuthStateDidChangeInternal,
  1800. object: self,
  1801. userInfo: internalNotificationParameters)
  1802. notifications.post(name: Auth.authStateDidChangeNotification, object: self)
  1803. }
  1804. }
  1805. /// Schedules a task to automatically refresh tokens on the current user. The0 token refresh
  1806. /// is scheduled 5 minutes before the scheduled expiration time.
  1807. ///
  1808. /// If the token expires in less than 5 minutes, schedule the token refresh immediately.
  1809. private func scheduleAutoTokenRefresh() {
  1810. let tokenExpirationInterval =
  1811. (_currentUser?.accessTokenExpirationDate()?.timeIntervalSinceNow ?? 0) - 5 * 60
  1812. scheduleAutoTokenRefresh(withDelay: max(tokenExpirationInterval, 0), retry: false)
  1813. }
  1814. /// Schedules a task to automatically refresh tokens on the current user.
  1815. /// - Parameter delay: The delay in seconds after which the token refresh task should be scheduled
  1816. /// to be executed.
  1817. /// - Parameter retry: Flag to determine whether the invocation is a retry attempt or not.
  1818. private func scheduleAutoTokenRefresh(withDelay delay: TimeInterval, retry: Bool) {
  1819. guard let accessToken = _currentUser?.rawAccessToken() else {
  1820. return
  1821. }
  1822. let intDelay = Int(ceil(delay))
  1823. if retry {
  1824. AuthLog.logInfo(code: "I-AUT000003", message: "Token auto-refresh re-scheduled in " +
  1825. "\(intDelay / 60):\(intDelay % 60) " +
  1826. "because of error on previous refresh attempt.")
  1827. } else {
  1828. AuthLog.logInfo(code: "I-AUT000004", message: "Token auto-refresh scheduled in " +
  1829. "\(intDelay / 60):\(intDelay % 60) " +
  1830. "for the new token.")
  1831. }
  1832. autoRefreshScheduled = true
  1833. weak var weakSelf = self
  1834. authDispatcher.dispatch(afterDelay: delay, queue: kAuthGlobalWorkQueue) {
  1835. guard let strongSelf = weakSelf else {
  1836. return
  1837. }
  1838. guard strongSelf._currentUser?.rawAccessToken() == accessToken else {
  1839. // Another auto refresh must have been scheduled, so keep _autoRefreshScheduled unchanged.
  1840. return
  1841. }
  1842. strongSelf.autoRefreshScheduled = false
  1843. if strongSelf.isAppInBackground {
  1844. return
  1845. }
  1846. let uid = strongSelf._currentUser?.uid
  1847. strongSelf._currentUser?
  1848. .internalGetToken(forceRefresh: true, backend: strongSelf.backend) { token, error in
  1849. if strongSelf._currentUser?.uid != uid {
  1850. return
  1851. }
  1852. if error != nil {
  1853. // Kicks off exponential back off logic to retry failed attempt. Starts with one minute
  1854. // delay (60 seconds) if this is the first failed attempt.
  1855. let rescheduleDelay = retry ? min(delay * 2, 16 * 60) : 60
  1856. strongSelf.scheduleAutoTokenRefresh(withDelay: rescheduleDelay, retry: true)
  1857. }
  1858. }
  1859. }
  1860. }
  1861. /// Update the current user; initializing the user's internal properties correctly, and
  1862. /// optionally saving the user to disk.
  1863. ///
  1864. /// This method is called during: sign in and sign out events, as well as during class
  1865. /// initialization time. The only time the saveToDisk parameter should be set to NO is during
  1866. /// class initialization time because the user was just read from disk.
  1867. /// - Parameter user: The user to use as the current user (including nil, which is passed at sign
  1868. /// out time.)
  1869. /// - Parameter saveToDisk: Indicates the method should persist the user data to disk.
  1870. func updateCurrentUser(_ user: User?, byForce force: Bool,
  1871. savingToDisk saveToDisk: Bool) throws {
  1872. if user == _currentUser {
  1873. possiblyPostAuthStateChangeNotification()
  1874. }
  1875. if let user {
  1876. if user.tenantID != nil || tenantID != nil, tenantID != user.tenantID {
  1877. throw AuthErrorUtils.tenantIDMismatchError()
  1878. }
  1879. }
  1880. var throwError: Error?
  1881. if saveToDisk {
  1882. do {
  1883. try saveUser(user)
  1884. } catch {
  1885. throwError = error
  1886. }
  1887. }
  1888. if throwError == nil || force {
  1889. _currentUser = user
  1890. possiblyPostAuthStateChangeNotification()
  1891. }
  1892. if let throwError {
  1893. throw throwError
  1894. }
  1895. }
  1896. private func saveUser(_ user: User?) throws {
  1897. if let userAccessGroup {
  1898. guard let apiKey = app?.options.apiKey else {
  1899. fatalError("Internal Auth Error: Missing apiKey in saveUser")
  1900. }
  1901. if let user {
  1902. try storedUserManager.setStoredUser(user: user,
  1903. accessGroup: userAccessGroup,
  1904. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1905. projectIdentifier: apiKey)
  1906. } else {
  1907. try storedUserManager.removeStoredUser(
  1908. accessGroup: userAccessGroup,
  1909. shareAuthStateAcrossDevices: shareAuthStateAcrossDevices,
  1910. projectIdentifier: apiKey
  1911. )
  1912. }
  1913. } else {
  1914. let userKey = "\(firebaseAppName)\(kUserKey)"
  1915. if let user {
  1916. let archiver = NSKeyedArchiver(requiringSecureCoding: true)
  1917. archiver.encode(user, forKey: userKey)
  1918. archiver.finishEncoding()
  1919. let archiveData = archiver.encodedData
  1920. // Save the user object's encoded value.
  1921. try keychainServices.setData(archiveData as Data, forKey: userKey)
  1922. } else {
  1923. try keychainServices.removeData(forKey: userKey)
  1924. }
  1925. }
  1926. }
  1927. /// Completes a sign-in flow once we have access and refresh tokens for the user.
  1928. /// - Parameter accessToken: The STS access token.
  1929. /// - Parameter accessTokenExpirationDate: The approximate expiration date of the access token.
  1930. /// - Parameter refreshToken: The STS refresh token.
  1931. /// - Parameter anonymous: Whether or not the user is anonymous.
  1932. @discardableResult
  1933. func completeSignIn(withAccessToken accessToken: String?,
  1934. accessTokenExpirationDate: Date?,
  1935. refreshToken: String?,
  1936. anonymous: Bool) async throws -> User {
  1937. return try await User.retrieveUser(withAuth: self,
  1938. accessToken: accessToken,
  1939. accessTokenExpirationDate: accessTokenExpirationDate,
  1940. refreshToken: refreshToken,
  1941. anonymous: anonymous)
  1942. }
  1943. /// Signs in using an email address and password.
  1944. ///
  1945. /// This is the internal counterpart of this method, which uses a callback that does not
  1946. /// update the current user.
  1947. /// - Parameter email: The user's email address.
  1948. /// - Parameter password: The user's password.
  1949. private func internalSignInAndRetrieveData(withEmail email: String,
  1950. password: String) async throws -> AuthDataResult {
  1951. let credential = EmailAuthCredential(withEmail: email, password: password)
  1952. return try await internalSignInAndRetrieveData(withCredential: credential,
  1953. isReauthentication: false)
  1954. }
  1955. func internalSignInAndRetrieveData(withCredential credential: AuthCredential,
  1956. isReauthentication: Bool) async throws
  1957. -> AuthDataResult {
  1958. if let emailCredential = credential as? EmailAuthCredential {
  1959. // Special case for email/password credentials
  1960. switch emailCredential.emailType {
  1961. case let .link(link):
  1962. // Email link sign in
  1963. return try await internalSignInAndRetrieveData(withEmail: emailCredential.email, link: link)
  1964. case let .password(password):
  1965. // Email password sign in
  1966. let user = try await internalSignInUser(
  1967. withEmail: emailCredential.email,
  1968. password: password
  1969. )
  1970. let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
  1971. profile: nil,
  1972. username: nil,
  1973. isNewUser: false)
  1974. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  1975. }
  1976. }
  1977. #if !os(watchOS)
  1978. if let gameCenterCredential = credential as? GameCenterAuthCredential {
  1979. return try await signInAndRetrieveData(withGameCenterCredential: gameCenterCredential)
  1980. }
  1981. #endif
  1982. #if os(iOS)
  1983. if let phoneCredential = credential as? PhoneAuthCredential {
  1984. // Special case for phone auth credentials
  1985. let operation = isReauthentication ? AuthOperationType.reauth :
  1986. AuthOperationType.signUpOrSignIn
  1987. let response = try await signIn(withPhoneCredential: phoneCredential,
  1988. operation: operation)
  1989. let user = try await completeSignIn(withAccessToken: response.idToken,
  1990. accessTokenExpirationDate: response
  1991. .approximateExpirationDate,
  1992. refreshToken: response.refreshToken,
  1993. anonymous: false)
  1994. let additionalUserInfo = AdditionalUserInfo(providerID: PhoneAuthProvider.id,
  1995. profile: nil,
  1996. username: nil,
  1997. isNewUser: response.isNewUser)
  1998. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  1999. }
  2000. #endif
  2001. let request = VerifyAssertionRequest(providerID: credential.provider,
  2002. requestConfiguration: requestConfiguration)
  2003. request.autoCreate = !isReauthentication
  2004. credential.prepare(request)
  2005. let response = try await backend.call(with: request)
  2006. if response.needConfirmation {
  2007. let email = response.email
  2008. let credential = OAuthCredential(withVerifyAssertionResponse: response)
  2009. throw AuthErrorUtils.accountExistsWithDifferentCredentialError(
  2010. email: email,
  2011. updatedCredential: credential
  2012. )
  2013. }
  2014. guard let providerID = response.providerID, providerID.count > 0 else {
  2015. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: response)
  2016. }
  2017. let user = try await completeSignIn(withAccessToken: response.idToken,
  2018. accessTokenExpirationDate: response
  2019. .approximateExpirationDate,
  2020. refreshToken: response.refreshToken,
  2021. anonymous: false)
  2022. let additionalUserInfo = AdditionalUserInfo(providerID: providerID,
  2023. profile: response.profile,
  2024. username: response.username,
  2025. isNewUser: response.isNewUser)
  2026. let updatedOAuthCredential = OAuthCredential(withVerifyAssertionResponse: response)
  2027. return AuthDataResult(withUser: user,
  2028. additionalUserInfo: additionalUserInfo,
  2029. credential: updatedOAuthCredential)
  2030. }
  2031. #if os(iOS)
  2032. /// Signs in using a phone credential.
  2033. /// - Parameter credential: The Phone Auth credential used to sign in.
  2034. /// - Parameter operation: The type of operation for which this sign-in attempt is initiated.
  2035. private func signIn(withPhoneCredential credential: PhoneAuthCredential,
  2036. operation: AuthOperationType) async throws -> VerifyPhoneNumberResponse {
  2037. switch credential.credentialKind {
  2038. case let .phoneNumber(phoneNumber, temporaryProof):
  2039. let request = VerifyPhoneNumberRequest(temporaryProof: temporaryProof,
  2040. phoneNumber: phoneNumber,
  2041. operation: operation,
  2042. requestConfiguration: requestConfiguration)
  2043. return try await backend.call(with: request)
  2044. case let .verification(verificationID, code):
  2045. guard verificationID.count > 0 else {
  2046. throw AuthErrorUtils.missingVerificationIDError(message: nil)
  2047. }
  2048. guard code.count > 0 else {
  2049. throw AuthErrorUtils.missingVerificationCodeError(message: nil)
  2050. }
  2051. let request = VerifyPhoneNumberRequest(verificationID: verificationID,
  2052. verificationCode: code,
  2053. operation: operation,
  2054. requestConfiguration: requestConfiguration)
  2055. return try await backend.call(with: request)
  2056. }
  2057. }
  2058. #endif
  2059. #if !os(watchOS)
  2060. /// Signs in using a game center credential.
  2061. /// - Parameter credential: The Game Center Auth Credential used to sign in.
  2062. private func signInAndRetrieveData(withGameCenterCredential credential: GameCenterAuthCredential) async throws
  2063. -> AuthDataResult {
  2064. guard let publicKeyURL = credential.publicKeyURL,
  2065. let signature = credential.signature,
  2066. let salt = credential.salt else {
  2067. fatalError(
  2068. "Internal Auth Error: Game Center credential missing publicKeyURL, signature, or salt"
  2069. )
  2070. }
  2071. let request = SignInWithGameCenterRequest(playerID: credential.playerID,
  2072. teamPlayerID: credential.teamPlayerID,
  2073. gamePlayerID: credential.gamePlayerID,
  2074. publicKeyURL: publicKeyURL,
  2075. signature: signature,
  2076. salt: salt,
  2077. timestamp: credential.timestamp,
  2078. displayName: credential.displayName,
  2079. requestConfiguration: requestConfiguration)
  2080. let response = try await backend.call(with: request)
  2081. let user = try await completeSignIn(withAccessToken: response.idToken,
  2082. accessTokenExpirationDate: response
  2083. .approximateExpirationDate,
  2084. refreshToken: response.refreshToken,
  2085. anonymous: false)
  2086. let additionalUserInfo = AdditionalUserInfo(providerID: GameCenterAuthProvider.id,
  2087. profile: nil,
  2088. username: nil,
  2089. isNewUser: response.isNewUser)
  2090. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  2091. }
  2092. #endif
  2093. /// Signs in using an email and email sign-in link.
  2094. /// - Parameter email: The user's email address.
  2095. /// - Parameter link: The email sign-in link.
  2096. private func internalSignInAndRetrieveData(withEmail email: String,
  2097. link: String) async throws -> AuthDataResult {
  2098. guard isSignIn(withEmailLink: link) else {
  2099. fatalError("The link provided is not valid for email/link sign-in. Please check the link by " +
  2100. "calling isSignIn(withEmailLink:) on the Auth instance before attempting to use it " +
  2101. "for email/link sign-in.")
  2102. }
  2103. let queryItems = getQueryItems(link)
  2104. guard let actionCode = queryItems["oobCode"] else {
  2105. fatalError("Missing oobCode in link URL")
  2106. }
  2107. let request = EmailLinkSignInRequest(email: email,
  2108. oobCode: actionCode,
  2109. requestConfiguration: requestConfiguration)
  2110. let response = try await backend.call(with: request)
  2111. let user = try await completeSignIn(withAccessToken: response.idToken,
  2112. accessTokenExpirationDate: response
  2113. .approximateExpirationDate,
  2114. refreshToken: response.refreshToken,
  2115. anonymous: false)
  2116. let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
  2117. profile: nil,
  2118. username: nil,
  2119. isNewUser: response.isNewUser)
  2120. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo)
  2121. }
  2122. private func getQueryItems(_ link: String) -> [String: String] {
  2123. var queryItems = AuthWebUtils.parseURL(link)
  2124. if queryItems.count == 0 {
  2125. let urlComponents = URLComponents(string: link)
  2126. if let query = urlComponents?.query {
  2127. queryItems = AuthWebUtils.parseURL(query)
  2128. }
  2129. }
  2130. return queryItems
  2131. }
  2132. /// Creates a AuthDataResultCallback block which wraps another AuthDataResultCallback;
  2133. /// trying to update the current user before forwarding it's invocations along to a subject
  2134. /// block.
  2135. ///
  2136. /// Typically invoked as part of the complete sign-in flow. For any other uses please
  2137. /// consider alternative ways of updating the current user.
  2138. /// - Parameter callback: Called when the user has been updated or when an error has occurred.
  2139. /// Invoked asynchronously on the main thread in the future.
  2140. /// - Returns: Returns a block that updates the current user.
  2141. func signInFlowAuthDataResultCallback(byDecorating callback:
  2142. ((AuthDataResult?, Error?) -> Void)?) -> (Result<AuthDataResult, Error>) -> Void {
  2143. return { result in
  2144. switch result {
  2145. case let .success(authResult):
  2146. do {
  2147. try self.updateCurrentUser(authResult.user, byForce: false, savingToDisk: true)
  2148. Auth.wrapMainAsync(callback: callback, with: .success(authResult))
  2149. } catch {
  2150. Auth.wrapMainAsync(callback: callback, with: .failure(error))
  2151. }
  2152. case let .failure(error):
  2153. Auth.wrapMainAsync(callback: callback, with: .failure(error))
  2154. }
  2155. }
  2156. }
  2157. private func wrapAsyncRPCTask(_ request: any AuthRPCRequest, _ callback: ((Error?) -> Void)?) {
  2158. Task {
  2159. do {
  2160. let _ = try await self.backend.call(with: request)
  2161. Auth.wrapMainAsync(callback, nil)
  2162. } catch {
  2163. Auth.wrapMainAsync(callback, error)
  2164. }
  2165. }
  2166. }
  2167. class func wrapMainAsync(_ callback: ((Error?) -> Void)?, _ error: Error?) {
  2168. if let callback {
  2169. DispatchQueue.main.async {
  2170. callback(error)
  2171. }
  2172. }
  2173. }
  2174. class func wrapMainAsync<T: Any>(callback: ((T?, Error?) -> Void)?,
  2175. with result: Result<T, Error>) -> Void {
  2176. guard let callback else { return }
  2177. DispatchQueue.main.async {
  2178. switch result {
  2179. case let .success(success): callback(success, nil)
  2180. case let .failure(error): callback(nil, error)
  2181. }
  2182. }
  2183. }
  2184. #if os(iOS)
  2185. func injectRecaptcha<T: AuthRPCRequest>(request: T,
  2186. action: AuthRecaptchaAction) async throws -> T
  2187. .Response {
  2188. let recaptchaVerifier = AuthRecaptchaVerifier.shared(auth: self)
  2189. if recaptchaVerifier.enablementStatus(forProvider: AuthRecaptchaProvider.password) != .off {
  2190. try await recaptchaVerifier.injectRecaptchaFields(request: request,
  2191. provider: AuthRecaptchaProvider.password,
  2192. action: action)
  2193. } else {
  2194. do {
  2195. return try await backend.call(with: request)
  2196. } catch {
  2197. let nsError = error as NSError
  2198. if let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError,
  2199. nsError.code == AuthErrorCode.internalError.rawValue,
  2200. let messages = underlyingError
  2201. .userInfo[AuthErrorUtils.userInfoDeserializedResponseKey] as? [String: AnyHashable],
  2202. let message = messages["message"] as? String,
  2203. message.hasPrefix("MISSING_RECAPTCHA_TOKEN") {
  2204. try await recaptchaVerifier.injectRecaptchaFields(
  2205. request: request,
  2206. provider: AuthRecaptchaProvider.password,
  2207. action: action
  2208. )
  2209. } else {
  2210. throw error
  2211. }
  2212. }
  2213. }
  2214. return try await backend.call(with: request)
  2215. }
  2216. #endif
  2217. // MARK: Internal properties
  2218. /// Allow tests to swap in an alternate mainBundle, including ObjC unit tests via CocoaPods.
  2219. #if FIREBASE_CI
  2220. @objc public var mainBundleUrlTypes: [[String: Any]]!
  2221. #else
  2222. var mainBundleUrlTypes: [[String: Any]]!
  2223. #endif
  2224. /// The configuration object comprising of parameters needed to make a request to Firebase
  2225. /// Auth's backend.
  2226. let requestConfiguration: AuthRequestConfiguration
  2227. let backend: AuthBackend
  2228. #if os(iOS)
  2229. /// The manager for APNs tokens used by phone number auth.
  2230. var tokenManager: AuthAPNSTokenManager!
  2231. /// The manager for app credentials used by phone number auth.
  2232. var appCredentialManager: AuthAppCredentialManager!
  2233. /// The manager for remote notifications used by phone number auth.
  2234. var notificationManager: AuthNotificationManager!
  2235. /// An object that takes care of presenting URLs via the auth instance.
  2236. var authURLPresenter: AuthWebViewControllerDelegate
  2237. #endif // TARGET_OS_IOS
  2238. // MARK: Private properties
  2239. /// The stored user manager.
  2240. private let storedUserManager: AuthStoredUserManager
  2241. /// The Firebase app name.
  2242. private let firebaseAppName: String
  2243. private let authDispatcher: AuthDispatcher
  2244. /// The keychain service.
  2245. private let keychainServices: AuthKeychainServices
  2246. /// The user access (ID) token used last time for posting auth state changed notification.
  2247. ///
  2248. /// - Note: The atomic wrapper can be removed when the SDK is fully
  2249. /// synchronized with structured concurrency.
  2250. private var lastNotifiedUserToken: String? {
  2251. get { lastNotifiedUserTokenLock.withLock { _lastNotifiedUserToken } }
  2252. set { lastNotifiedUserTokenLock.withLock { _lastNotifiedUserToken = newValue } }
  2253. }
  2254. private var _lastNotifiedUserToken: String?
  2255. private var lastNotifiedUserTokenLock = NSLock()
  2256. /// This flag denotes whether or not tokens should be automatically refreshed.
  2257. /// Will only be set to `true` if the another Firebase service is included (additionally to
  2258. /// Firebase Auth).
  2259. private var autoRefreshTokens = false
  2260. /// Whether or not token auto-refresh is currently scheduled.
  2261. private var autoRefreshScheduled = false
  2262. /// A flag that is set to YES if the app is put in the background and no when the app is
  2263. /// returned to the foreground.
  2264. private var isAppInBackground = false
  2265. /// An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification.
  2266. private var applicationDidBecomeActiveObserver: NSObjectProtocol?
  2267. /// An opaque object to act as the observer for
  2268. /// UIApplicationDidEnterBackgroundNotification.
  2269. private var applicationDidEnterBackgroundObserver: NSObjectProtocol?
  2270. /// An opaque object to act as the observer for
  2271. /// UIApplicationProtectedDataDidBecomeAvailable.
  2272. private var protectedDataDidBecomeAvailableObserver: NSObjectProtocol?
  2273. /// Key of user stored in the keychain. Prefixed with a Firebase app name.
  2274. private let kUserKey = "_firebase_user"
  2275. /// Handles returned from `NSNotificationCenter` for blocks which are "auth state did
  2276. /// change" notification listeners.
  2277. ///
  2278. /// Mutations should occur within a @synchronized(self) context.
  2279. private var listenerHandles: NSMutableArray = []
  2280. }