Auth.swift 105 KB

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