NCLoginWeb.swift 11 KB

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