NCLoginWeb.swift 14 KB

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