NCLogin.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. // MARK: - View Life Cycle
  41. override func viewDidLoad() {
  42. super.viewDidLoad()
  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. // navigation
  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. self.navigationController?.navigationBar.tintColor = textColor
  94. if NCManageDatabase.shared.getAccounts()?.count ?? 0 == 0 {
  95. } else {
  96. // Cancel Button
  97. let navigationItemCancel = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.actionCancel))
  98. navigationItemCancel.tintColor = textColor
  99. navigationItem.leftBarButtonItem = navigationItemCancel
  100. }
  101. self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
  102. view.backgroundColor = NCBrandColor.shared.customer
  103. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  104. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  105. }
  106. override func viewDidAppear(_ animated: Bool) {
  107. super.viewDidAppear(animated)
  108. appDelegate.timerErrorNetworking?.invalidate()
  109. // test
  110. createTalkAccount()
  111. if let talkAccounts = readTalkAccounts(), let image = UIImage(named: "talk"), let backgroundColor = NCBrandColor.shared.brandElement.lighter(by: 10) {
  112. NCContentPresenter.shared.alertAction(image: image, backgroundColor: backgroundColor, textColor: textColor, title: "Talk is intalled", description: "Hei I have fount talk user, ...", textCancelButton: "cancel", textOkButton: "ok", attributes: EKAttributes.topFloat) { identifier in
  113. if identifier == "ok" {
  114. if let vc = UIStoryboard(name: "NCTalkAccounts", bundle: nil).instantiateInitialViewController() as? NCTalkAccounts {
  115. vc.accounts = talkAccounts
  116. vc.enableTimerProgress = false
  117. vc.dismissDidEnterBackground = false
  118. vc.delegate = self
  119. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  120. let numberCell = talkAccounts.count
  121. let height = min(CGFloat(numberCell * Int(vc.heightCell) + 45), screenHeighMax)
  122. let popup = NCPopupViewController(contentController: vc, popupWidth: 300, popupHeight: height+20)
  123. popup.backgroundAlpha = 0.8
  124. self.present(popup, animated: true)
  125. }
  126. }
  127. }
  128. }
  129. }
  130. override func viewDidDisappear(_ animated: Bool) {
  131. super.viewDidDisappear(animated)
  132. appDelegate.startTimerErrorNetworking()
  133. }
  134. // MARK: - TextField
  135. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  136. textField.resignFirstResponder()
  137. actionButtonLogin(self)
  138. return false
  139. }
  140. func textFieldDidBeginEditing(_ textField: UITextField) {
  141. self.activeTextField = textField
  142. }
  143. // MARK: - Keyboard notification
  144. @objc internal func keyboardWillShow(_ notification: Notification?) {
  145. activeTextfieldDiff = 0
  146. if let info = notification?.userInfo, let centerObject = self.activeTextField.superview?.convert(self.activeTextField.center, to: nil) {
  147. let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
  148. if let keyboardFrame = info[frameEndUserInfoKey] as? CGRect {
  149. let diff = keyboardFrame.origin.y - centerObject.y - self.activeTextField.frame.height
  150. if diff < 0 {
  151. activeTextfieldDiff = diff
  152. imageBrandConstraintY.constant += diff
  153. }
  154. }
  155. }
  156. }
  157. @objc func keyboardWillHide(_ notification: Notification) {
  158. imageBrandConstraintY.constant -= activeTextfieldDiff
  159. }
  160. // MARK: - Action
  161. @objc func actionCancel() {
  162. dismiss(animated: true) { }
  163. }
  164. @IBAction func actionButtonLogin(_ sender: Any) {
  165. guard var url = baseUrl.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
  166. if url.hasSuffix("/") { url = String(url.dropLast()) }
  167. if url.count == 0 { return }
  168. // Check whether baseUrl contain protocol. If not add https:// by default.
  169. if url.hasPrefix("https") == false && url.hasPrefix("http") == false {
  170. url = "https://" + url
  171. }
  172. self.baseUrl.text = url
  173. isUrlValid(url: url)
  174. }
  175. @IBAction func actionQRCode(_ sender: Any) {
  176. let qrCode = NCLoginQRCode(delegate: self)
  177. qrCode.scan()
  178. }
  179. @IBAction func actionCertificate(_ sender: Any) {
  180. }
  181. // MARK: - Login
  182. func isUrlValid(url: String, user: String? = nil) {
  183. loginButton.isEnabled = false
  184. NextcloudKit.shared.getServerStatus(serverUrl: url) { _, _, versionMajor, _, _, _, _, error in
  185. if error == .success {
  186. if let host = URL(string: url)?.host {
  187. NCNetworking.shared.writeCertificate(host: host)
  188. }
  189. NextcloudKit.shared.getLoginFlowV2(serverUrl: url) { token, endpoint, login, data, error in
  190. self.loginButton.isEnabled = true
  191. // Login Flow V2
  192. if error == .success && NCBrandOptions.shared.use_loginflowv2 && token != nil && endpoint != nil && login != nil {
  193. if let loginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb {
  194. loginWeb.urlBase = url
  195. loginWeb.user = user
  196. loginWeb.loginFlowV2Available = true
  197. loginWeb.loginFlowV2Token = token!
  198. loginWeb.loginFlowV2Endpoint = endpoint!
  199. loginWeb.loginFlowV2Login = login!
  200. self.navigationController?.pushViewController(loginWeb, animated: true)
  201. }
  202. // Login Flow
  203. } else if versionMajor >= NCGlobal.shared.nextcloudVersion12 {
  204. if let loginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb {
  205. loginWeb.urlBase = url
  206. loginWeb.user = user
  207. self.navigationController?.pushViewController(loginWeb, animated: true)
  208. }
  209. // NO Login flow available
  210. } else if versionMajor < NCGlobal.shared.nextcloudVersion12 {
  211. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_webflow_not_available_", comment: ""), preferredStyle: .alert)
  212. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  213. self.present(alertController, animated: true, completion: { })
  214. }
  215. }
  216. } else {
  217. self.loginButton.isEnabled = true
  218. if error.errorCode == NSURLErrorServerCertificateUntrusted {
  219. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  220. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  221. if let host = URL(string: url)?.host {
  222. NCNetworking.shared.writeCertificate(host: host)
  223. }
  224. }))
  225. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  226. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  227. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  228. let viewController = navigationController.topViewController as! NCViewCertificateDetails
  229. if let host = URL(string: url)?.host {
  230. viewController.host = host
  231. }
  232. self.present(navigationController, animated: true)
  233. }
  234. }))
  235. self.present(alertController, animated: true)
  236. } else {
  237. let alertController = UIAlertController(title: NSLocalizedString("_connection_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  238. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  239. self.present(alertController, animated: true, completion: { })
  240. }
  241. }
  242. }
  243. }
  244. // MARK: - QRCode
  245. func dismissQRCode(_ value: String?, metadataType: String?) {
  246. guard var value = value else { return }
  247. let protocolLogin = NCBrandOptions.shared.webLoginAutenticationProtocol + "login/"
  248. if value.hasPrefix(protocolLogin) && value.contains("user:") && value.contains("password:") && value.contains("server:") {
  249. value = value.replacingOccurrences(of: protocolLogin, with: "")
  250. let valueArray = value.components(separatedBy: "&")
  251. if valueArray.count == 3 {
  252. let user = valueArray[0].replacingOccurrences(of: "user:", with: "")
  253. let password = valueArray[1].replacingOccurrences(of: "password:", with: "")
  254. let urlBase = valueArray[2].replacingOccurrences(of: "server:", with: "")
  255. let serverUrl = urlBase + "/" + NCGlobal.shared.dav
  256. loginButton.isEnabled = false
  257. NextcloudKit.shared.checkServer(serverUrl: serverUrl) { error in
  258. self.loginButton.isEnabled = true
  259. self.standardLogin(url: urlBase, user: user, password: password, error: error)
  260. }
  261. }
  262. }
  263. }
  264. func standardLogin(url: String, user: String, password: String, error: NKError) {
  265. if error == .success {
  266. if let host = URL(string: url)?.host {
  267. NCNetworking.shared.writeCertificate(host: host)
  268. }
  269. let account = user + " " + url
  270. if NCManageDatabase.shared.getAccounts() == nil {
  271. NCUtility.shared.removeAllSettings()
  272. }
  273. NCManageDatabase.shared.deleteAccount(account)
  274. NCManageDatabase.shared.addAccount(account, urlBase: url, user: user, password: password)
  275. if let activeAccount = NCManageDatabase.shared.setAccountActive(account) {
  276. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  277. }
  278. if CCUtility.getIntro() {
  279. self.dismiss(animated: true)
  280. } else {
  281. CCUtility.setIntro(true)
  282. if self.presentingViewController == nil {
  283. let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
  284. viewController?.modalPresentationStyle = .fullScreen
  285. self.appDelegate.window?.rootViewController = viewController
  286. self.appDelegate.window?.makeKey()
  287. } else {
  288. self.dismiss(animated: true)
  289. }
  290. }
  291. } else if error.errorCode == NSURLErrorServerCertificateUntrusted {
  292. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  293. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  294. if let host = URL(string: url)?.host {
  295. NCNetworking.shared.writeCertificate(host: host)
  296. }
  297. }))
  298. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  299. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  300. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() {
  301. self.present(navigationController, animated: true)
  302. }
  303. }))
  304. self.present(alertController, animated: true)
  305. } else {
  306. let message = NSLocalizedString("_not_possible_connect_to_server_", comment: "") + ".\n" + error.errorDescription
  307. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  308. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  309. self.present(alertController, animated: true, completion: { })
  310. }
  311. }
  312. func readTalkAccounts() -> [dataAccountFile]? {
  313. guard let dirGroupTalk = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupsTalk) else { return nil }
  314. let url = dirGroupTalk.appendingPathComponent(NCGlobal.shared.appDatabaseTalk + "/" + NCGlobal.shared.fileAccounts)
  315. if FileManager.default.fileExists(atPath: url.path) {
  316. return NCUtility.shared.readDataAccountFile(at: url)
  317. }
  318. return nil
  319. }
  320. func createTalkAccount() -> Error? {
  321. guard let dirGroupTalk = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupsTalk) else { return nil }
  322. let url = dirGroupTalk.appendingPathComponent(NCGlobal.shared.appDatabaseTalk + "/" + NCGlobal.shared.fileAccounts)
  323. let tableAccount = NCManageDatabase.shared.getAllAccount()
  324. var accounts = [dataAccountFile]()
  325. for account in tableAccount {
  326. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  327. let avatar = String(CCUtility.getDirectoryUserData()) + "/" + userBaseUrl + "-\(account.user).png"
  328. let userData = dataAccountFile(withUrl: account.urlBase, user: account.user, alias: account.alias, avatar: avatar)
  329. accounts.append(userData)
  330. }
  331. return NCUtility.shared.createDataAccountFile(at: url, accounts: accounts)
  332. }
  333. }
  334. extension NCLogin: NCTalkAccountsDelegate {
  335. func selected(url: String, user: String) {
  336. isUrlValid(url: url, user: user)
  337. }
  338. }