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