NCLoginWeb.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. 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 account = ""
  33. @objc var loginFlowV2Available = false
  34. @objc var loginFlowV2Token = ""
  35. @objc var loginFlowV2Endpoint = ""
  36. @objc var loginFlowV2Login = ""
  37. // MARK: - Life Cycle
  38. override func viewDidLoad() {
  39. super.viewDidLoad()
  40. let accountCount = NCManageDatabase.shared.getAccounts()?.count ?? 0
  41. if NCBrandOptions.shared.use_login_web_personalized && accountCount > 0 {
  42. navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .stop, target: self, action: #selector(self.closeView(sender:)))
  43. }
  44. if accountCount > 0 {
  45. navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "users")!.image(color: NCBrandColor.shared.textView, size: 35), style: .plain, target: self, action: #selector(self.changeUser(sender:)))
  46. }
  47. let config = WKWebViewConfiguration()
  48. config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
  49. webView = WKWebView(frame: CGRect.zero, configuration: config)
  50. webView!.navigationDelegate = self
  51. view.addSubview(webView!)
  52. webView!.translatesAutoresizingMaskIntoConstraints = false
  53. webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  54. webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
  55. webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  56. webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  57. // ADD end point for Web Flow
  58. if urlBase != NCBrandOptions.shared.linkloginPreferredProviders {
  59. if loginFlowV2Available {
  60. urlBase = loginFlowV2Login
  61. } else {
  62. urlBase = urlBase + "/index.php/login/flow"
  63. }
  64. }
  65. activityIndicator = UIActivityIndicatorView(style: .gray)
  66. activityIndicator.center = self.view.center
  67. activityIndicator.startAnimating()
  68. self.view.addSubview(activityIndicator)
  69. if let url = URL(string: urlBase) {
  70. loadWebPage(webView: webView!, url: url)
  71. } else {
  72. NCContentPresenter.shared.messageNotification("_error_", description: "_login_url_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorInternalError, forced: true)
  73. }
  74. }
  75. override func viewDidAppear(_ animated: Bool) {
  76. super.viewDidAppear(animated)
  77. // Stop timer error network
  78. appDelegate.timerErrorNetworking?.invalidate()
  79. }
  80. override func viewDidDisappear(_ animated: Bool) {
  81. super.viewDidDisappear(animated)
  82. // Start timer error network
  83. appDelegate.startTimerErrorNetworking()
  84. }
  85. func loadWebPage(webView: WKWebView, url: URL) {
  86. let language = NSLocale.preferredLanguages[0] as String
  87. var request = URLRequest(url: url)
  88. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  89. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  90. webView.customUserAgent = CCUtility.getUserAgent()
  91. webView.load(request)
  92. }
  93. @objc func closeView(sender: UIBarButtonItem) {
  94. self.dismiss(animated: true, completion: nil)
  95. }
  96. @objc func changeUser(sender: UIBarButtonItem) {
  97. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  98. mainMenuViewController.actions = self.initUsersMenu()
  99. let menuPanelController = NCMenuPanelController()
  100. menuPanelController.parentPresenter = self
  101. menuPanelController.delegate = mainMenuViewController
  102. menuPanelController.set(contentViewController: mainMenuViewController)
  103. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  104. self.present(menuPanelController, animated: true, completion: nil)
  105. }
  106. // MARK: -
  107. private func initUsersMenu() -> [NCMenuAction] {
  108. var actions = [NCMenuAction]()
  109. let accounts = NCManageDatabase.shared.getAllAccount()
  110. var avatar = UIImage(named: "avatarCredentials")!.image(color: NCBrandColor.shared.icon, size: 50)
  111. for account in accounts {
  112. let title = account.user + " " + (URL(string: account.urlBase)?.host ?? "")
  113. var fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(account.user, urlBase: account.urlBase) + "_" + account.user
  114. fileNamePath = fileNamePath + ".png"
  115. if var userImage = UIImage(contentsOfFile: fileNamePath) {
  116. userImage = userImage.resizeImage(size: CGSize(width: 50, height: 50), isAspectRation: true)!
  117. let userImageView = UIImageView(image: userImage)
  118. userImageView.avatar(roundness: 2, borderWidth: 1, borderColor: NCBrandColor.shared.avatarBorder, backgroundColor: .clear)
  119. UIGraphicsBeginImageContext(userImageView.bounds.size)
  120. userImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
  121. if let newAvatar = UIGraphicsGetImageFromCurrentImageContext() {
  122. avatar = newAvatar
  123. }
  124. UIGraphicsEndImageContext()
  125. }
  126. actions.append(
  127. NCMenuAction(
  128. title: title,
  129. icon: avatar,
  130. onTitle: title,
  131. onIcon: avatar,
  132. selected: account.active == true,
  133. on: account.active == true,
  134. action: { menuAction in
  135. if self.account != account.account {
  136. NCManageDatabase.shared.setAccountActive(account.account)
  137. self.dismiss(animated: true) {
  138. self.appDelegate.settingAccount(account.account, urlBase: account.urlBase, user: account.user, userId: account.userId, password: CCUtility.getPassword(account.account))
  139. self.appDelegate.initializeMain()
  140. }
  141. }
  142. }
  143. )
  144. )
  145. }
  146. return actions
  147. }
  148. }
  149. extension NCLoginWeb: WKNavigationDelegate {
  150. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  151. guard let url = webView.url else { return }
  152. let urlString: String = url.absoluteString.lowercased()
  153. if (urlString.hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) == true && urlString.contains("login") == true) {
  154. var server: String = ""
  155. var user: String = ""
  156. var password: String = ""
  157. let keyValue = url.path.components(separatedBy: "&")
  158. for value in keyValue {
  159. if value.contains("server:") { server = value }
  160. if value.contains("user:") { user = value }
  161. if value.contains("password:") { password = value }
  162. }
  163. if server != "" && user != "" && password != "" {
  164. let server: String = server.replacingOccurrences(of: "/server:", with: "")
  165. let username: String = user.replacingOccurrences(of: "user:", with: "").replacingOccurrences(of: "+", with: " ")
  166. let password: String = password.replacingOccurrences(of: "password:", with: "")
  167. createAccount(server: server, username: username, password: password)
  168. }
  169. }
  170. }
  171. public 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. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  179. decisionHandler(.allow)
  180. /* TEST NOT GOOD DON'T WORKS
  181. guard let url = navigationAction.request.url else {
  182. decisionHandler(.allow)
  183. return
  184. }
  185. if String(describing: url).hasPrefix(NCBrandOptions.shared.webLoginAutenticationProtocol) {
  186. decisionHandler(.allow)
  187. return
  188. } else if navigationAction.request.httpMethod != "GET" || navigationAction.request.value(forHTTPHeaderField: "OCS-APIRequest") != nil {
  189. decisionHandler(.allow)
  190. return
  191. }
  192. decisionHandler(.cancel)
  193. let language = NSLocale.preferredLanguages[0] as String
  194. var request = URLRequest(url: url)
  195. request.setValue(CCUtility.getUserAgent(), forHTTPHeaderField: "User-Agent")
  196. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  197. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  198. webView.load(request)
  199. */
  200. }
  201. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  202. print("didStartProvisionalNavigation");
  203. }
  204. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  205. activityIndicator.stopAnimating()
  206. print("didFinishProvisionalNavigation");
  207. if loginFlowV2Available {
  208. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  209. NCCommunication.shared.getLoginFlowV2Poll(token: self.loginFlowV2Token, endpoint: self.loginFlowV2Endpoint) { (server, loginName, appPassword, errorCode, errorDescription) in
  210. if errorCode == 0 && server != nil && loginName != nil && appPassword != nil {
  211. self.createAccount(server: server!, username: loginName!, password: appPassword!)
  212. }
  213. }
  214. }
  215. }
  216. }
  217. //MARK: -
  218. func createAccount(server: String, username: String, password: String) {
  219. var urlBase = server
  220. // NO account found, clear all
  221. if NCManageDatabase.shared.getAccounts() == nil { NCUtility.shared.removeAllSettings() }
  222. // Normalized
  223. if (urlBase.last == "/") {
  224. urlBase = String(urlBase.dropLast())
  225. }
  226. // Create account
  227. let account: String = "\(username) \(urlBase)"
  228. // Add new account
  229. NCManageDatabase.shared.deleteAccount(account)
  230. NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: username, password: password)
  231. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else {
  232. self.dismiss(animated: true, completion: nil)
  233. return
  234. }
  235. appDelegate.settingAccount(account, urlBase: urlBase, user: username, userId: tableAccount.userId, password: password)
  236. if (CCUtility.getIntro()) {
  237. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  238. self.dismiss(animated: true)
  239. } else {
  240. CCUtility.setIntro(true)
  241. if (self.presentingViewController == nil) {
  242. if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() {
  243. viewController.modalPresentationStyle = .fullScreen
  244. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  245. viewController.view.alpha = 0
  246. appDelegate.window?.rootViewController = viewController
  247. appDelegate.window?.makeKeyAndVisible()
  248. UIView.animate(withDuration: 0.5) {
  249. viewController.view.alpha = 1
  250. }
  251. }
  252. } else {
  253. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  254. self.dismiss(animated: true)
  255. }
  256. }
  257. }
  258. }