NCLogin.swift 20 KB

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