NCLogin.swift 19 KB

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