NCLogin.swift 17 KB

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