NCLogin.swift 19 KB

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