NCLoginProvider.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. //
  2. // NCLoginProvider.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 21/08/2019.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. @preconcurrency import WebKit
  25. import NextcloudKit
  26. import FloatingPanel
  27. class NCLoginProvider: UIViewController {
  28. var webView: WKWebView?
  29. let utility = NCUtility()
  30. var titleView: String = ""
  31. var urlBase = ""
  32. // MARK: - View Life Cycle
  33. override func viewDidLoad() {
  34. super.viewDidLoad()
  35. navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
  36. webView = WKWebView(frame: CGRect.zero, configuration: WKWebViewConfiguration())
  37. webView!.navigationDelegate = self
  38. view.addSubview(webView!)
  39. webView!.translatesAutoresizingMaskIntoConstraints = false
  40. webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  41. webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
  42. webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  43. webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  44. if let url = URL(string: urlBase) {
  45. loadWebPage(webView: webView!, url: url)
  46. } else {
  47. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_login_url_error_")
  48. NCContentPresenter().showError(error: error, priority: .max)
  49. }
  50. if let host = URL(string: urlBase)?.host {
  51. titleView = host
  52. if let activeTableAccount = NCManageDatabase.shared.getActiveTableAccount(), NCKeychain().getPassword(account: activeTableAccount.account).isEmpty {
  53. titleView = NSLocalizedString("_user_", comment: "") + " " + activeTableAccount.userId + " " + NSLocalizedString("_in_", comment: "") + " " + host
  54. }
  55. }
  56. self.title = titleView
  57. }
  58. override func viewDidDisappear(_ animated: Bool) {
  59. super.viewDidDisappear(animated)
  60. NCActivityIndicator.shared.stop()
  61. }
  62. func loadWebPage(webView: WKWebView, url: URL) {
  63. let language = NSLocale.preferredLanguages[0] as String
  64. var request = URLRequest(url: url)
  65. if let deviceName = "\(UIDevice.current.name) (\(NCBrandOptions.shared.brand) iOS)".cString(using: .utf8),
  66. let deviceUserAgent = String(cString: deviceName, encoding: .ascii) {
  67. webView.customUserAgent = deviceUserAgent
  68. } else {
  69. webView.customUserAgent = userAgent
  70. }
  71. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  72. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  73. webView.load(request)
  74. }
  75. @objc func closeView(sender: UIBarButtonItem) {
  76. self.dismiss(animated: true, completion: nil)
  77. }
  78. }
  79. extension NCLoginProvider: WKNavigationDelegate {
  80. func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  81. guard let url = webView.url else { return }
  82. let urlString: String = url.absoluteString.lowercased()
  83. // prevent http redirection
  84. if urlBase.lowercased().hasPrefix("https://") && urlString.lowercased().hasPrefix("http://") {
  85. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_prevent_http_redirection_", comment: ""), preferredStyle: .alert)
  86. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  87. _ = self.navigationController?.popViewController(animated: true)
  88. }))
  89. self.present(alertController, animated: true)
  90. return
  91. }
  92. if urlString.hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) == true && urlString.contains("login") == true {
  93. var server: String = ""
  94. var user: String = ""
  95. var password: String = ""
  96. let keyValue = url.path.components(separatedBy: "&")
  97. for value in keyValue {
  98. if value.contains("server:") { server = value }
  99. if value.contains("user:") { user = value }
  100. if value.contains("password:") { password = value }
  101. }
  102. if !server.isEmpty, !user.isEmpty, !password.isEmpty {
  103. let server: String = server.replacingOccurrences(of: "/server:", with: "")
  104. let username: String = user.replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
  105. let password: String = password.replacingOccurrences(of: "password:", with: "")
  106. createAccount(server: server, username: username, password: password)
  107. }
  108. }
  109. }
  110. func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  111. DispatchQueue.global().async {
  112. if let serverTrust = challenge.protectionSpace.serverTrust {
  113. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  114. } else {
  115. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
  116. }
  117. }
  118. }
  119. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  120. decisionHandler(.allow)
  121. }
  122. func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  123. NCActivityIndicator.shared.startActivity(style: .medium, blurEffect: false)
  124. }
  125. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  126. NCActivityIndicator.shared.stop()
  127. }
  128. // MARK: -
  129. func createAccount(server: String, username: String, password: String) {
  130. var urlBase = server
  131. if urlBase.last == "/" { urlBase = String(urlBase.dropLast()) }
  132. let account: String = "\(username) \(urlBase)"
  133. let user = username
  134. NextcloudKit.shared.getUserProfile(account: account) { account, userProfile, _, error in
  135. if error == .success, let userProfile {
  136. NextcloudKit.shared.appendSession(account: account,
  137. urlBase: urlBase,
  138. user: user,
  139. userId: user,
  140. password: password,
  141. userAgent: userAgent,
  142. nextcloudVersion: NCCapabilities.shared.getCapabilities(account: account).capabilityServerVersionMajor,
  143. groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  144. NCSession.shared.appendSession(account: account, urlBase: urlBase, user: user, userId: userProfile.userId)
  145. NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: user, userId: userProfile.userId, password: password)
  146. NCAccount().changeAccount(account, userProfile: userProfile, controller: nil) { }
  147. let window = UIApplication.shared.firstWindow
  148. if let controller = window?.rootViewController as? NCMainTabBarController {
  149. controller.account = account
  150. self.dismiss(animated: true)
  151. } else {
  152. if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as? NCMainTabBarController {
  153. controller.account = account
  154. controller.modalPresentationStyle = .fullScreen
  155. controller.view.alpha = 0
  156. window?.rootViewController = controller
  157. window?.makeKeyAndVisible()
  158. if let scene = window?.windowScene {
  159. SceneManager.shared.register(scene: scene, withRootViewController: controller)
  160. }
  161. UIView.animate(withDuration: 0.5) {
  162. controller.view.alpha = 1
  163. }
  164. }
  165. }
  166. } else {
  167. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  168. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  169. self.present(alertController, animated: true)
  170. }
  171. }
  172. }
  173. }