NCLoginWeb.swift 14 KB

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