NCLoginWeb.swift 13 KB

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