NCLogin.swift 23 KB

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