NCLogin.swift 17 KB

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