NCLogin.swift 23 KB

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