NCLoginWeb.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 UIKit
  24. import WebKit
  25. import NCCommunication
  26. import FloatingPanel
  27. class NCLoginWeb: UIViewController {
  28. var activityIndicator: UIActivityIndicatorView!
  29. var webView: WKWebView?
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. @objc var urlBase = ""
  32. @objc var loginFlowV2Available = false
  33. @objc var loginFlowV2Token = ""
  34. @objc var loginFlowV2Endpoint = ""
  35. @objc var loginFlowV2Login = ""
  36. // MARK: - View Life Cycle
  37. override func viewDidLoad() {
  38. super.viewDidLoad()
  39. let accountCount = NCManageDatabase.shared.getAccounts()?.count ?? 0
  40. if NCBrandOptions.shared.use_login_web_personalized && accountCount > 0 {
  41. navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
  42. }
  43. if accountCount > 0 {
  44. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "users")!.image(color: NCBrandColor.shared.label, size: 35), style: .plain, target: self, action: #selector(self.changeUser(sender:)))
  45. }
  46. let config = WKWebViewConfiguration()
  47. config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
  48. webView = WKWebView(frame: CGRect.zero, configuration: config)
  49. webView!.navigationDelegate = self
  50. view.addSubview(webView!)
  51. webView!.translatesAutoresizingMaskIntoConstraints = false
  52. webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  53. webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
  54. webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  55. webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  56. // ADD end point for Web Flow
  57. if urlBase != NCBrandOptions.shared.linkloginPreferredProviders {
  58. if loginFlowV2Available {
  59. urlBase = loginFlowV2Login
  60. } else {
  61. urlBase += "/index.php/login/flow"
  62. }
  63. }
  64. activityIndicator = UIActivityIndicatorView(style: .gray)
  65. activityIndicator.center = self.view.center
  66. activityIndicator.startAnimating()
  67. self.view.addSubview(activityIndicator)
  68. if let url = URL(string: urlBase) {
  69. loadWebPage(webView: webView!, url: url)
  70. } else {
  71. NCContentPresenter.shared.messageNotification("_error_", description: "_login_url_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  72. }
  73. }
  74. override func viewDidAppear(_ animated: Bool) {
  75. super.viewDidAppear(animated)
  76. // Stop timer error network
  77. appDelegate.timerErrorNetworking?.invalidate()
  78. }
  79. override func viewDidDisappear(_ animated: Bool) {
  80. super.viewDidDisappear(animated)
  81. // Start timer error network
  82. appDelegate.startTimerErrorNetworking()
  83. }
  84. func loadWebPage(webView: WKWebView, url: URL) {
  85. let language = NSLocale.preferredLanguages[0] as String
  86. var request = URLRequest(url: url)
  87. if let deviceName = "\(UIDevice.current.name) (\(NCBrandOptions.shared.brand) iOS)".cString(using: .utf8),
  88. let deviceUserAgent = String(cString: deviceName, encoding: .ascii) {
  89. webView.customUserAgent = deviceUserAgent
  90. } else {
  91. webView.customUserAgent = CCUtility.getUserAgent()
  92. }
  93. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  94. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  95. webView.load(request)
  96. }
  97. @objc func closeView(sender: UIBarButtonItem) {
  98. self.dismiss(animated: true, completion: nil)
  99. }
  100. @objc func changeUser(sender: UIBarButtonItem) {
  101. toggleMenu()
  102. }
  103. }
  104. extension NCLoginWeb: WKNavigationDelegate {
  105. func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  106. guard let url = webView.url else { return }
  107. let urlString: String = url.absoluteString.lowercased()
  108. // prevent http redirection
  109. if urlBase.lowercased().hasPrefix("https://") && urlString.lowercased().hasPrefix("http://") {
  110. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_prevent_http_redirection_", comment: ""), preferredStyle: .alert)
  111. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  112. _ = self.navigationController?.popViewController(animated: true)
  113. }))
  114. self.present(alertController, animated: true)
  115. return
  116. }
  117. if urlString.hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) == true && urlString.contains("login") == true {
  118. var server: String = ""
  119. var user: String = ""
  120. var password: String = ""
  121. let keyValue = url.path.components(separatedBy: "&")
  122. for value in keyValue {
  123. if value.contains("server:") { server = value }
  124. if value.contains("user:") { user = value }
  125. if value.contains("password:") { password = value }
  126. }
  127. if server != "" && user != "" && password != "" {
  128. let server: String = server.replacingOccurrences(of: "/server:", with: "")
  129. let username: String = user.replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
  130. let password: String = password.replacingOccurrences(of: "password:", with: "")
  131. createAccount(server: server, username: username, password: password)
  132. }
  133. }
  134. }
  135. func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
  136. }
  137. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
  138. var errorMessage = error.localizedDescription
  139. for (key, value) in (error as NSError).userInfo {
  140. let message = "\(key) \(value)\n"
  141. errorMessage += message
  142. }
  143. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorMessage, preferredStyle: .alert)
  144. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  145. self.present(alertController, animated: true)
  146. }
  147. func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  148. if let serverTrust = challenge.protectionSpace.serverTrust {
  149. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  150. } else {
  151. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
  152. }
  153. }
  154. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  155. decisionHandler(.allow)
  156. /* TEST NOT GOOD DON'T WORKS
  157. if let data = navigationAction.request.httpBody {
  158. let str = String(decoding: data, as: UTF8.self)
  159. print(str)
  160. }
  161. guard let url = navigationAction.request.url else {
  162. decisionHandler(.allow)
  163. return
  164. }
  165. if String(describing: url).hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) {
  166. decisionHandler(.allow)
  167. return
  168. } else if navigationAction.request.httpMethod != "GET" || navigationAction.request.value(forHTTPHeaderField: "OCS-APIRequest") != nil {
  169. decisionHandler(.allow)
  170. return
  171. }
  172. decisionHandler(.cancel)
  173. let language = NSLocale.preferredLanguages[0] as String
  174. var request = URLRequest(url: url)
  175. request.setValue(CCUtility.getUserAgent(), forHTTPHeaderField: "User-Agent")
  176. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  177. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  178. webView.load(request)
  179. */
  180. }
  181. func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  182. print("didStartProvisionalNavigation")
  183. }
  184. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  185. activityIndicator.stopAnimating()
  186. print("didFinishProvisionalNavigation")
  187. if loginFlowV2Available {
  188. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  189. NCCommunication.shared.getLoginFlowV2Poll(token: self.loginFlowV2Token, endpoint: self.loginFlowV2Endpoint) { server, loginName, appPassword, errorCode, _ in
  190. if errorCode == 0 && server != nil && loginName != nil && appPassword != nil {
  191. self.createAccount(server: server!, username: loginName!, password: appPassword!)
  192. }
  193. }
  194. }
  195. }
  196. }
  197. // MARK: -
  198. func createAccount(server: String, username: String, password: String) {
  199. var urlBase = server
  200. // Normalized
  201. if urlBase.last == "/" {
  202. urlBase = String(urlBase.dropLast())
  203. }
  204. // Create account
  205. let account: String = "\(username) \(urlBase)"
  206. // NO account found, clear all
  207. if NCManageDatabase.shared.getAccounts() == nil {
  208. NCUtility.shared.removeAllSettings()
  209. }
  210. // Add new account
  211. NCManageDatabase.shared.deleteAccount(account)
  212. NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: username, password: password)
  213. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else {
  214. self.dismiss(animated: true, completion: nil)
  215. return
  216. }
  217. appDelegate.settingAccount(account, urlBase: urlBase, user: username, userId: tableAccount.userId, password: password)
  218. if CCUtility.getIntro() {
  219. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  220. self.dismiss(animated: true)
  221. } else {
  222. CCUtility.setIntro(true)
  223. if self.presentingViewController == nil {
  224. if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() {
  225. viewController.modalPresentationStyle = .fullScreen
  226. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  227. viewController.view.alpha = 0
  228. appDelegate.window?.rootViewController = viewController
  229. appDelegate.window?.makeKeyAndVisible()
  230. UIView.animate(withDuration: 0.5) {
  231. viewController.view.alpha = 1
  232. }
  233. }
  234. } else {
  235. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  236. self.dismiss(animated: true)
  237. }
  238. }
  239. }
  240. }