NCLogin.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //
  2. // NCLogin.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 24/02/21.
  6. // Copyright © 2021 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 NCCommunication
  25. class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
  26. @IBOutlet weak var imageBrand: UIImageView!
  27. @IBOutlet weak var baseUrl: UITextField!
  28. @IBOutlet weak var loginAddressDetail: UILabel!
  29. @IBOutlet weak var loginButton: UIButton!
  30. @IBOutlet weak var qrCode: UIButton!
  31. @IBOutlet weak var certificate: UIButton!
  32. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. private var textColor: UIColor = .white
  34. private var textColorOpponent: UIColor = .black
  35. // MARK: - View Life Cycle
  36. override func viewDidLoad() {
  37. super.viewDidLoad()
  38. view.backgroundColor = NCBrandColor.shared.customer
  39. // Text color
  40. if NCBrandColor.shared.customer.isTooLight() {
  41. textColor = .black
  42. textColorOpponent = .white
  43. } else if NCBrandColor.shared.customer.isTooDark() {
  44. textColor = .white
  45. textColorOpponent = .black
  46. } else {
  47. textColor = .white
  48. textColorOpponent = .black
  49. }
  50. // Image Brand
  51. imageBrand.image = UIImage(named: "logo")
  52. // Url
  53. baseUrl.textColor = textColor
  54. baseUrl.layer.cornerRadius = 15.0
  55. baseUrl.layer.borderWidth = 1.0
  56. baseUrl.layer.borderColor = textColor.cgColor
  57. baseUrl.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: baseUrl.frame.height))
  58. baseUrl.leftViewMode = .always
  59. baseUrl.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: baseUrl.frame.height))
  60. baseUrl.rightViewMode = .always
  61. baseUrl.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("_login_url_", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: textColor.withAlphaComponent(0.5)])
  62. baseUrl.delegate = self
  63. // Login button
  64. loginButton.setImage(UIImage(named: "arrow.right")?.image(color: textColor, size: 100), for: .normal)
  65. loginAddressDetail.textColor = textColor
  66. loginAddressDetail.text = NSLocalizedString("_login_address_detail_", comment: "")
  67. // brand
  68. if NCBrandOptions.shared.disable_request_login_url {
  69. baseUrl.text = NCBrandOptions.shared.loginBaseUrl
  70. baseUrl.isHidden = true
  71. }
  72. // qrcode
  73. qrCode.setImage(UIImage(named: "qrcode")?.image(color: textColor, size: 100), for: .normal)
  74. // certificate
  75. certificate.setImage(UIImage(named: "certificate")?.image(color: textColor, size: 100), for: .normal)
  76. certificate.isHidden = true
  77. certificate.isEnabled = false
  78. if NCManageDatabase.shared.getAccounts()?.count ?? 0 == 0 {
  79. } else {
  80. // Cancel Button
  81. let navigationItemCancel = UIBarButtonItem.init(barButtonSystemItem: .stop, target: self, action: #selector(self.actionCancel))
  82. navigationItemCancel.tintColor = textColor
  83. navigationItem.leftBarButtonItem = navigationItemCancel
  84. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
  85. }
  86. self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
  87. }
  88. override func viewDidAppear(_ animated: Bool) {
  89. super.viewDidAppear(animated)
  90. appDelegate.timerErrorNetworking?.invalidate()
  91. }
  92. override func viewDidDisappear(_ animated: Bool) {
  93. super.viewDidDisappear(animated)
  94. appDelegate.startTimerErrorNetworking()
  95. }
  96. // MARK: - NotificationCenter
  97. @objc func applicationDidEnterBackground() {
  98. dismiss(animated: false)
  99. }
  100. // MARK: - TextField
  101. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  102. textField.resignFirstResponder()
  103. return false
  104. }
  105. // MARK: - Action
  106. @objc func actionCancel() {
  107. dismiss(animated: true) { }
  108. }
  109. @IBAction func actionButtonLogin(_ sender: Any) {
  110. guard var url = baseUrl.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
  111. if url.hasSuffix("/") { url = String(url.dropLast()) }
  112. if url.count == 0 { return }
  113. // Check whether baseUrl contain protocol. If not add https:// by default.
  114. if url.hasPrefix("https") == false && url.hasPrefix("http") == false {
  115. url = "https://" + url
  116. }
  117. self.baseUrl.text = url
  118. isUrlValid(url: url)
  119. }
  120. @IBAction func actionQRCode(_ sender: Any) {
  121. let qrCode = NCLoginQRCode.init(delegate: self)
  122. qrCode.scan()
  123. }
  124. @IBAction func actionCertificate(_ sender: Any) {
  125. let pathsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
  126. let fileNameCertificate = pathsDirectory.appendingPathComponent(NCGlobal.shared.certificate).path
  127. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  128. var host = "cloud.nextcloud.com"
  129. if let url = URL(string: NCBrandOptions.shared.loginBaseUrl) {
  130. let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  131. if let hostComponets = urlComponents?.host {
  132. host = hostComponets
  133. }
  134. }
  135. if FileManager.default.fileExists(atPath: fileNameCertificate) {
  136. let certificateToPath = directoryCertificate + "/" + host + ".der"
  137. if NCUtilityFileSystem.shared.moveFile(atPath: fileNameCertificate, toPath: certificateToPath) {
  138. let message = String(format: NSLocalizedString("_certificate_installed_", comment: ""), NCGlobal.shared.certificate)
  139. let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
  140. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
  141. self.present(alertController, animated: true, completion: { })
  142. } else {
  143. let message = String(format: NSLocalizedString("_copy_failed_", comment: ""), NCGlobal.shared.certificate)
  144. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  145. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
  146. self.present(alertController, animated: true, completion: { })
  147. }
  148. } else {
  149. let message = String(format: NSLocalizedString("_certificate_not_found_", comment: ""), NCGlobal.shared.certificate)
  150. let alertController = UIAlertController(title: NSLocalizedString("_file_not_found_", comment: ""), message: message, preferredStyle: .alert)
  151. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
  152. self.present(alertController, animated: true, completion: { })
  153. }
  154. }
  155. // MARK: - Login
  156. func isUrlValid(url: String) {
  157. loginButton.isEnabled = false
  158. //activity.startAnimating()
  159. NCCommunication.shared.getServerStatus(serverUrl: url) { (serverProductName, serverVersion, versionMajor, versionMinor, versionMicro, extendedSupport, errorCode ,errorDescription) in
  160. if errorCode == 0 {
  161. NCNetworking.shared.writeCertificate(url: url)
  162. NCCommunication.shared.getLoginFlowV2(serverUrl: url) { (token, endpoint, login, errorCode, errorDescription) in
  163. self.loginButton.isEnabled = true
  164. //self.activity.stopAnimating()
  165. // Login Flow V2
  166. if errorCode == 0 && NCBrandOptions.shared.use_loginflowv2 && token != nil && endpoint != nil && login != nil {
  167. if let loginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb {
  168. loginWeb.urlBase = url
  169. loginWeb.loginFlowV2Available = true
  170. loginWeb.loginFlowV2Token = token!
  171. loginWeb.loginFlowV2Endpoint = endpoint!
  172. loginWeb.loginFlowV2Login = login!
  173. self.navigationController?.pushViewController(loginWeb, animated: true)
  174. }
  175. // Login Flow
  176. } else if versionMajor >= NCGlobal.shared.nextcloudVersion12 {
  177. if let loginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb {
  178. loginWeb.urlBase = url
  179. self.navigationController?.pushViewController(loginWeb, animated: true)
  180. }
  181. // NO Login flow available
  182. } else if versionMajor < NCGlobal.shared.nextcloudVersion12 {
  183. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_webflow_not_available_", comment: ""), preferredStyle: .alert)
  184. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
  185. self.present(alertController, animated: true, completion: { })
  186. }
  187. }
  188. } else {
  189. self.loginButton.isEnabled = true
  190. //self.activity.stopAnimating()
  191. if errorCode == NSURLErrorServerCertificateUntrusted {
  192. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  193. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
  194. NCNetworking.shared.writeCertificate(url: url)
  195. self.appDelegate.startTimerErrorNetworking()
  196. }))
  197. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
  198. self.appDelegate.startTimerErrorNetworking()
  199. }))
  200. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
  201. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() {
  202. self.present(navigationController, animated: true)
  203. }
  204. }))
  205. self.present(alertController, animated: true, completion: {
  206. self.appDelegate.timerErrorNetworking?.invalidate()
  207. })
  208. } else {
  209. let alertController = UIAlertController(title: NSLocalizedString("_connection_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  210. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
  211. self.present(alertController, animated: true, completion: { })
  212. }
  213. }
  214. }
  215. }
  216. func standardLogin(url: String, user: String, password: String, errorCode: Int, errorDescription: String) {
  217. if errorCode == 0 {
  218. NCNetworking.shared.writeCertificate(url: url)
  219. let account = user + " " + url
  220. if NCManageDatabase.shared.getAccounts() == nil {
  221. NCUtility.shared.removeAllSettings()
  222. }
  223. CCUtility.clearCertificateError(account)
  224. NCManageDatabase.shared.deleteAccount(account)
  225. NCManageDatabase.shared.addAccount(account, urlBase: url, user: user, password: password)
  226. if let activeAccount = NCManageDatabase.shared.setAccountActive(account) {
  227. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  228. }
  229. if CCUtility.getIntro() {
  230. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  231. self.dismiss(animated: true)
  232. } else {
  233. CCUtility.setIntro(true)
  234. if self.presentingViewController == nil {
  235. let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
  236. viewController?.modalPresentationStyle = .fullScreen
  237. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  238. self.appDelegate.window?.rootViewController = viewController
  239. self.appDelegate.window?.makeKey()
  240. } else {
  241. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  242. self.dismiss(animated: true)
  243. }
  244. }
  245. } else if errorCode == NSURLErrorServerCertificateUntrusted {
  246. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  247. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
  248. NCNetworking.shared.writeCertificate(url: url)
  249. self.appDelegate.startTimerErrorNetworking()
  250. }))
  251. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
  252. self.appDelegate.startTimerErrorNetworking()
  253. }))
  254. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
  255. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() {
  256. self.present(navigationController, animated: true)
  257. }
  258. }))
  259. self.present(alertController, animated: true, completion: {
  260. self.appDelegate.timerErrorNetworking?.invalidate()
  261. })
  262. } else {
  263. let message = NSLocalizedString("_not_possible_connect_to_server_", comment: "") + ".\n" + errorDescription
  264. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  265. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in }))
  266. self.present(alertController, animated: true, completion: { })
  267. }
  268. }
  269. // MARK: - QRCode
  270. func dismissQRCode(_ value: String?, metadataType: String?) {
  271. guard var value = value else { return }
  272. let protocolLogin = NCBrandOptions.shared.webLoginAutenticationProtocol + "login/"
  273. if value.hasPrefix(protocolLogin) && value.contains("user:") && value.contains("password:") && value.contains("server:") {
  274. value = value.replacingOccurrences(of: protocolLogin, with: "")
  275. let valueArray = value.components(separatedBy: "&")
  276. if valueArray.count == 3 {
  277. let user = valueArray[0].replacingOccurrences(of: "user:", with: "")
  278. let password = valueArray[1].replacingOccurrences(of: "password:", with: "")
  279. let urlBase = valueArray[2].replacingOccurrences(of: "server:", with: "")
  280. let webDAV = NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account)
  281. let serverUrl = urlBase + "/" + webDAV
  282. loginButton.isEnabled = false
  283. //activity.startAnimating()
  284. NCCommunication.shared.checkServer(serverUrl: serverUrl) { (errorCode, errorDescription) in
  285. //self.activity.stopAnimating()
  286. self.loginButton.isEnabled = true
  287. self.standardLogin(url: urlBase, user: user, password: password, errorCode: errorCode, errorDescription: errorDescription)
  288. }
  289. }
  290. }
  291. }
  292. }