NCLogin.swift 20 KB

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