NCLoginWeb.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. @objc protocol NCLoginWebDelegate: class {
  25. @objc optional func loginWebDismiss()
  26. }
  27. class NCLoginWeb: UIViewController {
  28. var webView: WKWebView?
  29. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. @objc var urlBase = ""
  31. @objc weak var delegate: NCLoginWebDelegate?
  32. @IBOutlet weak var buttonExit: UIButton!
  33. override func viewDidLoad() {
  34. super.viewDidLoad()
  35. let config = WKWebViewConfiguration()
  36. config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
  37. webView = WKWebView(frame: CGRect.zero, configuration: config)
  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. // ADD k_flowEndpoint for Web Flow
  46. if NCBrandOptions.sharedInstance.use_login_web_personalized == false && urlBase != NCBrandOptions.sharedInstance.linkloginPreferredProviders {
  47. urlBase = urlBase + k_flowEndpoint
  48. }
  49. // button exit
  50. let listAccount = NCManageDatabase.sharedInstance.getAccounts()
  51. if listAccount?.count == 0 {
  52. buttonExit.isHidden = true
  53. } else {
  54. self.view.bringSubviewToFront(buttonExit)
  55. }
  56. loadWebPage(webView: webView!, url: URL(string: urlBase)!)
  57. }
  58. override func viewDidAppear(_ animated: Bool) {
  59. super.viewDidAppear(animated)
  60. // Stop timer error network
  61. appDelegate.timerErrorNetworking.invalidate()
  62. }
  63. override func viewDidDisappear(_ animated: Bool) {
  64. super.viewDidDisappear(animated)
  65. // Start timer error network
  66. appDelegate.startTimerErrorNetworking()
  67. }
  68. func loadWebPage(webView: WKWebView, url: URL) {
  69. let language = NSLocale.preferredLanguages[0] as String
  70. var request = URLRequest(url: url)
  71. request.setValue(CCUtility.getUserAgent(), forHTTPHeaderField: "User-Agent")
  72. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  73. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  74. webView.load(request)
  75. }
  76. @IBAction func touchUpInsideButtonExit(_ sender: UIButton) {
  77. self.dismiss(animated: true) {
  78. self.delegate?.loginWebDismiss?()
  79. }
  80. }
  81. }
  82. extension NCLoginWeb: WKNavigationDelegate {
  83. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  84. guard let url = webView.url else { return }
  85. let urlString: String = url.absoluteString.lowercased()
  86. if (urlString.hasPrefix(NCBrandOptions.sharedInstance.webLoginAutenticationProtocol) == true && urlString.contains("login") == true) {
  87. let keyValue = url.path.components(separatedBy: "&")
  88. if (keyValue.count >= 3) {
  89. if (keyValue[0].contains("server:") && keyValue[1].contains("user:") && keyValue[2].contains("password:")) {
  90. var serverUrl : String = keyValue[0].replacingOccurrences(of: "/server:", with: "")
  91. // Login Flow NC 12
  92. if (NCBrandOptions.sharedInstance.use_login_web_personalized == false && serverUrl.hasPrefix("http://") == false && serverUrl.hasPrefix("https://") == false) {
  93. serverUrl = urlBase
  94. }
  95. if (serverUrl.last == "/") {
  96. serverUrl = String(serverUrl.dropLast())
  97. }
  98. let username : String = keyValue[1].replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
  99. let token : String = keyValue[2].replacingOccurrences(of: "password:", with: "")
  100. let account : String = "\(username) \(serverUrl)"
  101. // NO account found, clear
  102. if NCManageDatabase.sharedInstance.getAccounts() == nil { NCUtility.sharedInstance.removeAllSettings() }
  103. // STOP Intro
  104. CCUtility.setIntro(true)
  105. // Add new account
  106. NCManageDatabase.sharedInstance.deleteAccount(account)
  107. NCManageDatabase.sharedInstance.addAccount(account, url: serverUrl, user: username, password: token)
  108. guard let tableAccount = NCManageDatabase.sharedInstance.setAccountActive(account) else {
  109. self.dismiss(animated: true, completion: nil)
  110. return
  111. }
  112. appDelegate.settingActiveAccount(account, activeUrl: serverUrl, activeUser: username, activeUserID: tableAccount.userID, activePassword: token)
  113. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "initializeMain"), object: nil, userInfo: nil)
  114. self.dismiss(animated: true) {
  115. self.delegate?.loginWebDismiss?()
  116. }
  117. }
  118. }
  119. }
  120. }
  121. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  122. if let serverTrust = challenge.protectionSpace.serverTrust {
  123. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  124. } else {
  125. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  126. }
  127. }
  128. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  129. decisionHandler(.allow)
  130. /*
  131. guard let url = navigationAction.request.url else {
  132. decisionHandler(.allow)
  133. return
  134. }
  135. if String(describing: url).hasPrefix(NCBrandOptions.sharedInstance.webLoginAutenticationProtocol) {
  136. decisionHandler(.allow)
  137. return
  138. } else if navigationAction.request.httpMethod != "GET" || navigationAction.request.value(forHTTPHeaderField: "OCS-APIRequest") != nil {
  139. decisionHandler(.allow)
  140. return
  141. }
  142. decisionHandler(.cancel)
  143. let language = NSLocale.preferredLanguages[0] as String
  144. var request = URLRequest(url: url)
  145. request.setValue(CCUtility.getUserAgent(), forHTTPHeaderField: "User-Agent")
  146. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  147. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  148. webView.load(request)
  149. */
  150. }
  151. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  152. print("didStartProvisionalNavigation");
  153. }
  154. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  155. print("didFinishProvisionalNavigation");
  156. }
  157. }