NCLogin.swift 21 KB

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