NCLoginProvider.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. import WebKit
  25. import NextcloudKit
  26. import FloatingPanel
  27. class NCLoginProvider: UIViewController {
  28. var webView: WKWebView?
  29. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  30. let utility = NCUtility()
  31. var titleView: String = ""
  32. var urlBase = ""
  33. // MARK: - View Life Cycle
  34. override func viewDidLoad() {
  35. super.viewDidLoad()
  36. navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
  37. webView = WKWebView(frame: CGRect.zero, configuration: WKWebViewConfiguration())
  38. webView!.navigationDelegate = self
  39. view.addSubview(webView!)
  40. webView!.translatesAutoresizingMaskIntoConstraints = false
  41. webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  42. webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
  43. webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  44. webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  45. if let url = URL(string: urlBase) {
  46. loadWebPage(webView: webView!, url: url)
  47. } else {
  48. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_login_url_error_")
  49. NCContentPresenter().showError(error: error, priority: .max)
  50. }
  51. if let host = URL(string: urlBase)?.host {
  52. titleView = host
  53. if let account = NCManageDatabase.shared.getActiveAccount(), NCKeychain().getPassword(account: account.account).isEmpty {
  54. titleView = NSLocalizedString("_user_", comment: "") + " " + account.userId + " " + NSLocalizedString("_in_", comment: "") + " " + host
  55. }
  56. }
  57. self.title = titleView
  58. }
  59. override func viewDidAppear(_ animated: Bool) {
  60. super.viewDidAppear(animated)
  61. // Stop timer error network
  62. appDelegate.timerErrorNetworkingDisabled = true
  63. }
  64. override func viewDidDisappear(_ animated: Bool) {
  65. super.viewDidDisappear(animated)
  66. NCActivityIndicator.shared.stop()
  67. appDelegate.timerErrorNetworkingDisabled = false
  68. }
  69. func loadWebPage(webView: WKWebView, url: URL) {
  70. let language = NSLocale.preferredLanguages[0] as String
  71. var request = URLRequest(url: url)
  72. if let deviceName = "\(UIDevice.current.name) (\(NCBrandOptions.shared.brand) iOS)".cString(using: .utf8),
  73. let deviceUserAgent = String(cString: deviceName, encoding: .ascii) {
  74. webView.customUserAgent = deviceUserAgent
  75. } else {
  76. webView.customUserAgent = userAgent
  77. }
  78. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  79. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  80. webView.load(request)
  81. }
  82. @objc func closeView(sender: UIBarButtonItem) {
  83. self.dismiss(animated: true, completion: nil)
  84. }
  85. }
  86. extension NCLoginProvider: WKNavigationDelegate {
  87. func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  88. guard let url = webView.url else { return }
  89. let urlString: String = url.absoluteString.lowercased()
  90. // prevent http redirection
  91. if urlBase.lowercased().hasPrefix("https://") && urlString.lowercased().hasPrefix("http://") {
  92. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_prevent_http_redirection_", comment: ""), preferredStyle: .alert)
  93. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  94. _ = self.navigationController?.popViewController(animated: true)
  95. }))
  96. self.present(alertController, animated: true)
  97. return
  98. }
  99. if urlString.hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) == true && urlString.contains("login") == true {
  100. var server: String = ""
  101. var user: String = ""
  102. var password: String = ""
  103. let keyValue = url.path.components(separatedBy: "&")
  104. for value in keyValue {
  105. if value.contains("server:") { server = value }
  106. if value.contains("user:") { user = value }
  107. if value.contains("password:") { password = value }
  108. }
  109. if !server.isEmpty, !user.isEmpty, !password.isEmpty {
  110. let server: String = server.replacingOccurrences(of: "/server:", with: "")
  111. let username: String = user.replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
  112. let password: String = password.replacingOccurrences(of: "password:", with: "")
  113. createAccount(server: server, username: username, password: password)
  114. }
  115. }
  116. }
  117. func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  118. DispatchQueue.global().async {
  119. if let serverTrust = challenge.protectionSpace.serverTrust {
  120. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  121. } else {
  122. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
  123. }
  124. }
  125. }
  126. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  127. decisionHandler(.allow)
  128. }
  129. func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  130. NCActivityIndicator.shared.startActivity(style: .medium, blurEffect: false)
  131. }
  132. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  133. NCActivityIndicator.shared.stop()
  134. }
  135. // MARK: -
  136. func createAccount(server: String, username: String, password: String) {
  137. var urlBase = server
  138. if urlBase.last == "/" { urlBase = String(urlBase.dropLast()) }
  139. let account: String = "\(username) \(urlBase)"
  140. let user = username
  141. NextcloudKit.shared.setup(account: account, user: user, userId: user, password: password, urlBase: urlBase)
  142. NextcloudKit.shared.getUserProfile { _, userProfile, _, error in
  143. if error == .success, let userProfile {
  144. NCManageDatabase.shared.deleteAccount(account)
  145. NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: user, userId: userProfile.userId, password: password)
  146. self.appDelegate.changeAccount(account, userProfile: userProfile) { }
  147. let window = UIApplication.shared.firstWindow
  148. if window?.rootViewController is NCMainTabBarController {
  149. self.dismiss(animated: true)
  150. } else {
  151. if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as? NCMainTabBarController {
  152. controller.modalPresentationStyle = .fullScreen
  153. controller.view.alpha = 0
  154. window?.rootViewController = controller
  155. window?.makeKeyAndVisible()
  156. UIView.animate(withDuration: 0.5) {
  157. controller.view.alpha = 1
  158. }
  159. }
  160. }
  161. } else {
  162. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  163. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  164. self.present(alertController, animated: true)
  165. }
  166. }
  167. }
  168. }