NCLogin.swift 23 KB

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