NCLoginWeb.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. //
  2. // NCLoginWeb.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 Foundation
  24. class NCLoginWeb: UIViewController {
  25. var activityIndicator: UIActivityIndicatorView!
  26. var webView: WKWebView?
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. @objc var urlBase = ""
  29. override func viewDidLoad() {
  30. super.viewDidLoad()
  31. if (NCBrandOptions.sharedInstance.use_login_web_personalized) {
  32. if let accountCount = NCManageDatabase.sharedInstance.getAccounts()?.count {
  33. if(accountCount > 0) {
  34. self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
  35. }
  36. }
  37. }
  38. let config = WKWebViewConfiguration()
  39. config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
  40. webView = WKWebView(frame: CGRect.zero, configuration: config)
  41. webView!.navigationDelegate = self
  42. view.addSubview(webView!)
  43. webView!.translatesAutoresizingMaskIntoConstraints = false
  44. webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  45. webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
  46. webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  47. webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  48. // ADD k_flowEndpoint for Web Flow
  49. if urlBase != NCBrandOptions.sharedInstance.linkloginPreferredProviders {
  50. urlBase = urlBase + k_flowEndpoint
  51. }
  52. activityIndicator = UIActivityIndicatorView(style: .gray)
  53. activityIndicator.center = self.view.center
  54. activityIndicator.startAnimating()
  55. self.view.addSubview(activityIndicator)
  56. if let url = URL(string: urlBase) {
  57. loadWebPage(webView: webView!, url: url)
  58. } else {
  59. NCContentPresenter.shared.messageNotification("_error_", description: "_login_url_error_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: 0)
  60. }
  61. }
  62. override func viewDidAppear(_ animated: Bool) {
  63. super.viewDidAppear(animated)
  64. // Stop timer error network
  65. appDelegate.timerErrorNetworking.invalidate()
  66. }
  67. override func viewDidDisappear(_ animated: Bool) {
  68. super.viewDidDisappear(animated)
  69. // Start timer error network
  70. appDelegate.startTimerErrorNetworking()
  71. }
  72. func loadWebPage(webView: WKWebView, url: URL) {
  73. let language = NSLocale.preferredLanguages[0] as String
  74. var request = URLRequest(url: url)
  75. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  76. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  77. webView.customUserAgent = CCUtility.getUserAgent()
  78. webView.load(request)
  79. }
  80. @objc func closeView(sender: UIBarButtonItem) {
  81. self.dismiss(animated: true, completion: nil)
  82. }
  83. }
  84. extension NCLoginWeb: WKNavigationDelegate {
  85. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  86. guard let url = webView.url else { return }
  87. let urlString: String = url.absoluteString.lowercased()
  88. if (urlString.hasPrefix(NCBrandOptions.sharedInstance.webLoginAutenticationProtocol) == true && urlString.contains("login") == true) {
  89. var server: String = ""
  90. var user: String = ""
  91. var password: String = ""
  92. let keyValue = url.path.components(separatedBy: "&")
  93. for value in keyValue {
  94. if value.contains("server:") { server = value }
  95. if value.contains("user:") { user = value }
  96. if value.contains("password:") { password = value }
  97. }
  98. if server != "" && user != "" && password != "" {
  99. var serverUrl: String = server.replacingOccurrences(of: "/server:", with: "")
  100. // Login Flow NC 12
  101. if (NCBrandOptions.sharedInstance.use_login_web_personalized == false && serverUrl.hasPrefix("http://") == false && serverUrl.hasPrefix("https://") == false) {
  102. serverUrl = urlBase
  103. }
  104. if (serverUrl.last == "/") {
  105. serverUrl = String(serverUrl.dropLast())
  106. }
  107. let username: String = user.replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
  108. let token: String = password.replacingOccurrences(of: "password:", with: "")
  109. let account : String = "\(username) \(serverUrl)"
  110. // NO account found, clear
  111. if NCManageDatabase.sharedInstance.getAccounts() == nil { NCUtility.sharedInstance.removeAllSettings() }
  112. // Add new account
  113. NCManageDatabase.sharedInstance.deleteAccount(account)
  114. NCManageDatabase.sharedInstance.addAccount(account, url: serverUrl, user: username, password: token)
  115. guard let tableAccount = NCManageDatabase.sharedInstance.setAccountActive(account) else {
  116. self.dismiss(animated: true, completion: nil)
  117. return
  118. }
  119. appDelegate.settingActiveAccount(account, activeUrl: serverUrl, activeUser: username, activeUserID: tableAccount.userID, activePassword: token)
  120. if (CCUtility.getIntro()) {
  121. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "initializeMain"), object: nil, userInfo: nil)
  122. self.dismiss(animated: true)
  123. } else {
  124. CCUtility.setIntro(true)
  125. if (self.presentingViewController == nil) {
  126. let splitController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
  127. splitController?.modalPresentationStyle = .fullScreen
  128. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "initializeMain"), object: nil, userInfo: nil)
  129. splitController!.view.alpha = 0
  130. appDelegate.window.rootViewController = splitController!
  131. appDelegate.window.makeKeyAndVisible()
  132. UIView.animate(withDuration: 0.5) {
  133. splitController!.view.alpha = 1
  134. }
  135. } else {
  136. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "initializeMain"), object: nil, userInfo: nil)
  137. self.dismiss(animated: true)
  138. }
  139. }
  140. }
  141. }
  142. }
  143. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  144. if let serverTrust = challenge.protectionSpace.serverTrust {
  145. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  146. } else {
  147. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  148. }
  149. }
  150. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  151. decisionHandler(.allow)
  152. /* TEST NOT GOOD DON'T WORKS
  153. guard let url = navigationAction.request.url else {
  154. decisionHandler(.allow)
  155. return
  156. }
  157. if String(describing: url).hasPrefix(NCBrandOptions.sharedInstance.webLoginAutenticationProtocol) {
  158. decisionHandler(.allow)
  159. return
  160. } else if navigationAction.request.httpMethod != "GET" || navigationAction.request.value(forHTTPHeaderField: "OCS-APIRequest") != nil {
  161. decisionHandler(.allow)
  162. return
  163. }
  164. decisionHandler(.cancel)
  165. let language = NSLocale.preferredLanguages[0] as String
  166. var request = URLRequest(url: url)
  167. request.setValue(CCUtility.getUserAgent(), forHTTPHeaderField: "User-Agent")
  168. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  169. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  170. webView.load(request)
  171. */
  172. }
  173. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  174. print("didStartProvisionalNavigation");
  175. }
  176. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  177. activityIndicator.stopAnimating()
  178. print("didFinishProvisionalNavigation");
  179. }
  180. }