NCLogin.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 UniformTypeIdentifiers
  24. import UIKit
  25. import NextcloudKit
  26. import SwiftEntryKit
  27. import SwiftUI
  28. class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
  29. @IBOutlet weak var imageBrand: UIImageView!
  30. @IBOutlet weak var imageBrandConstraintY: NSLayoutConstraint!
  31. @IBOutlet weak var baseUrl: UITextField!
  32. @IBOutlet weak var loginAddressDetail: UILabel!
  33. @IBOutlet weak var loginButton: UIButton!
  34. @IBOutlet weak var loginImage: UIImageView!
  35. @IBOutlet weak var qrCode: UIButton!
  36. @IBOutlet weak var certificate: UIButton!
  37. private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  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. var loginFlowV2Token = ""
  44. var loginFlowV2Endpoint = ""
  45. var loginFlowV2Login = ""
  46. /// The URL that will show up on the URL field when this screen appears
  47. var urlBase = ""
  48. var disableUrlField = false
  49. var disableCloseButton = false
  50. // Used for MDM
  51. var configServerUrl: String?
  52. var configUsername: String?
  53. var configPassword: String?
  54. var configAppPassword: String?
  55. private var p12Data: Data?
  56. private var p12Password: String?
  57. // MARK: - View Life Cycle
  58. override func viewDidLoad() {
  59. super.viewDidLoad()
  60. // Text color
  61. if NCBrandColor.shared.customer.isTooLight() {
  62. textColor = .black
  63. textColorOpponent = .white
  64. } else if NCBrandColor.shared.customer.isTooDark() {
  65. textColor = .white
  66. textColorOpponent = .black
  67. } else {
  68. textColor = .white
  69. textColorOpponent = .black
  70. }
  71. // Image Brand
  72. imageBrand.image = UIImage(named: "logo")
  73. // Url
  74. baseUrl.textColor = textColor
  75. baseUrl.tintColor = textColor
  76. baseUrl.layer.cornerRadius = 10
  77. baseUrl.layer.borderWidth = 1
  78. baseUrl.layer.borderColor = textColor.cgColor
  79. baseUrl.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: baseUrl.frame.height))
  80. baseUrl.leftViewMode = .always
  81. baseUrl.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: baseUrl.frame.height))
  82. baseUrl.rightViewMode = .always
  83. baseUrl.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("_login_url_", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: textColor.withAlphaComponent(0.5)])
  84. baseUrl.delegate = self
  85. baseUrl.isEnabled = !disableUrlField
  86. // Login button
  87. loginAddressDetail.textColor = textColor
  88. loginAddressDetail.text = String.localizedStringWithFormat(NSLocalizedString("_login_address_detail_", comment: ""), NCBrandOptions.shared.brand)
  89. // Login Image
  90. loginImage.image = UIImage(named: "arrow.right")?.image(color: textColor, size: 100)
  91. // brand
  92. if NCBrandOptions.shared.disable_request_login_url {
  93. baseUrl.text = NCBrandOptions.shared.loginBaseUrl
  94. baseUrl.isEnabled = false
  95. baseUrl.isUserInteractionEnabled = false
  96. baseUrl.alpha = 0.5
  97. }
  98. // qrcode
  99. qrCode.setImage(UIImage(systemName: "qrcode.viewfinder")?.image(color: textColor, size: 100), for: .normal)
  100. // certificate
  101. certificate.setImage(UIImage(named: "certificate")?.image(color: textColor, size: 100), for: .normal)
  102. certificate.isHidden = true
  103. certificate.isEnabled = false
  104. // navigation
  105. let navBarAppearance = UINavigationBarAppearance()
  106. navBarAppearance.configureWithTransparentBackground()
  107. navBarAppearance.shadowColor = .clear
  108. navBarAppearance.shadowImage = UIImage()
  109. navBarAppearance.titleTextAttributes = [.foregroundColor: textColor]
  110. navBarAppearance.largeTitleTextAttributes = [.foregroundColor: textColor]
  111. self.navigationController?.navigationBar.standardAppearance = navBarAppearance
  112. self.navigationController?.view.backgroundColor = NCBrandColor.shared.customer
  113. self.navigationController?.navigationBar.tintColor = textColor
  114. if !NCManageDatabase.shared.getAllAccount().isEmpty && !disableCloseButton {
  115. let navigationItemCancel = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(self.actionCancel))
  116. navigationItemCancel.tintColor = textColor
  117. navigationItem.leftBarButtonItem = navigationItemCancel
  118. }
  119. if let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) {
  120. // Nextcloud update share accounts
  121. if let error = appDelegate.updateShareAccounts() {
  122. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create share accounts \(error.localizedDescription)")
  123. }
  124. // Nextcloud get share accounts
  125. if let shareAccounts = NKShareAccounts().getShareAccount(at: dirGroupApps, application: UIApplication.shared) {
  126. var accountTemp = [NKShareAccounts.DataAccounts]()
  127. for shareAccount in shareAccounts {
  128. if NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "urlBase == %@ AND user == %@", shareAccount.url, shareAccount.user)) == nil {
  129. accountTemp.append(shareAccount)
  130. }
  131. }
  132. if !accountTemp.isEmpty {
  133. self.shareAccounts = accountTemp
  134. let image = NCUtility().loadImage(named: "person.badge.plus")
  135. let navigationItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(openShareAccountsViewController))
  136. navigationItem.tintColor = textColor
  137. self.navigationItem.rightBarButtonItem = navigationItem
  138. }
  139. }
  140. }
  141. self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
  142. view.backgroundColor = NCBrandColor.shared.customer
  143. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  144. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  145. handleLoginWithAppConfig()
  146. baseUrl.text = urlBase
  147. }
  148. override func viewDidAppear(_ animated: Bool) {
  149. super.viewDidAppear(animated)
  150. appDelegate.timerErrorNetworkingDisabled = true
  151. if self.shareAccounts != nil, let image = UIImage(systemName: "person.badge.plus")?.withTintColor(.white, renderingMode: .alwaysOriginal), let backgroundColor = NCBrandColor.shared.brandElement.lighter(by: 10) {
  152. let title = String(format: NSLocalizedString("_apps_nextcloud_detect_", comment: ""), NCBrandOptions.shared.brand)
  153. let description = String(format: NSLocalizedString("_add_existing_account_", comment: ""), NCBrandOptions.shared.brand)
  154. NCContentPresenter().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
  155. if identifier == "ok" {
  156. self.openShareAccountsViewController()
  157. }
  158. }
  159. }
  160. }
  161. override func viewDidDisappear(_ animated: Bool) {
  162. super.viewDidDisappear(animated)
  163. appDelegate.timerErrorNetworkingDisabled = false
  164. }
  165. private func handleLoginWithAppConfig() {
  166. let accountCount = NCManageDatabase.shared.getAccounts()?.count ?? 0
  167. // load AppConfig
  168. if (NCBrandOptions.shared.disable_multiaccount == false) || (NCBrandOptions.shared.disable_multiaccount == true && accountCount == 0) {
  169. if let configurationManaged = UserDefaults.standard.dictionary(forKey: "com.apple.configuration.managed"), NCBrandOptions.shared.use_AppConfig {
  170. if let serverUrl = configurationManaged[NCGlobal.shared.configuration_serverUrl] as? String {
  171. self.configServerUrl = serverUrl
  172. }
  173. if let username = configurationManaged[NCGlobal.shared.configuration_username] as? String, !username.isEmpty, username.lowercased() != "username" {
  174. self.configUsername = username
  175. }
  176. if let password = configurationManaged[NCGlobal.shared.configuration_password] as? String, !password.isEmpty, password.lowercased() != "password" {
  177. self.configPassword = password
  178. }
  179. if let apppassword = configurationManaged[NCGlobal.shared.configuration_apppassword] as? String, !apppassword.isEmpty, apppassword.lowercased() != "apppassword" {
  180. self.configAppPassword = apppassword
  181. }
  182. }
  183. }
  184. // AppConfig
  185. if let url = configServerUrl {
  186. if let user = self.configUsername, let password = configAppPassword {
  187. return createAccount(urlBase: url, user: user, password: password)
  188. } else if let user = self.configUsername, let password = configPassword {
  189. return getAppPassword(urlBase: url, user: user, password: password)
  190. } else {
  191. urlBase = url
  192. }
  193. }
  194. }
  195. // MARK: - TextField
  196. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  197. textField.resignFirstResponder()
  198. actionButtonLogin(self)
  199. return false
  200. }
  201. func textFieldDidBeginEditing(_ textField: UITextField) {
  202. self.activeTextField = textField
  203. }
  204. // MARK: - Keyboard notification
  205. @objc internal func keyboardWillShow(_ notification: Notification?) {
  206. activeTextfieldDiff = 0
  207. if let info = notification?.userInfo, let centerObject = self.activeTextField.superview?.convert(self.activeTextField.center, to: nil) {
  208. let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
  209. if let keyboardFrame = info[frameEndUserInfoKey] as? CGRect {
  210. let diff = keyboardFrame.origin.y - centerObject.y - self.activeTextField.frame.height
  211. if diff < 0 {
  212. activeTextfieldDiff = diff
  213. imageBrandConstraintY.constant += diff
  214. }
  215. }
  216. }
  217. }
  218. @objc func keyboardWillHide(_ notification: Notification) {
  219. imageBrandConstraintY.constant -= activeTextfieldDiff
  220. }
  221. // MARK: - Action
  222. @objc func actionCancel() {
  223. dismiss(animated: true) { }
  224. }
  225. @IBAction func actionButtonLogin(_ sender: Any) {
  226. NCNetworking.shared.p12Data = nil
  227. NCNetworking.shared.p12Password = nil
  228. login()
  229. }
  230. @IBAction func actionQRCode(_ sender: Any) {
  231. let qrCode = NCLoginQRCode(delegate: self)
  232. qrCode.scan()
  233. }
  234. @IBAction func actionCertificate(_ sender: Any) {
  235. }
  236. // MARK: - Share accounts View Controller
  237. @objc func openShareAccountsViewController() {
  238. if let shareAccounts = self.shareAccounts, let vc = UIStoryboard(name: "NCShareAccounts", bundle: nil).instantiateInitialViewController() as? NCShareAccounts {
  239. vc.accounts = shareAccounts
  240. vc.enableTimerProgress = false
  241. vc.dismissDidEnterBackground = false
  242. vc.delegate = self
  243. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  244. let numberCell = shareAccounts.count
  245. let height = min(CGFloat(numberCell * Int(vc.heightCell) + 45), screenHeighMax)
  246. let popup = NCPopupViewController(contentController: vc, popupWidth: 300, popupHeight: height + 20)
  247. self.present(popup, animated: true)
  248. }
  249. }
  250. // MARK: - Login
  251. private func login() {
  252. guard var url = baseUrl.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
  253. if url.hasSuffix("/") { url = String(url.dropLast()) }
  254. if url.isEmpty { return }
  255. // Check whether baseUrl contain protocol. If not add https:// by default.
  256. if url.hasPrefix("https") == false && url.hasPrefix("http") == false {
  257. url = "https://" + url
  258. }
  259. self.baseUrl.text = url
  260. isUrlValid(url: url)
  261. }
  262. func isUrlValid(url: String, user: String? = nil) {
  263. loginButton.isEnabled = false
  264. NextcloudKit.shared.getServerStatus(serverUrl: url) { serverInfoResult in
  265. switch serverInfoResult {
  266. case .success(let serverInfo):
  267. if let host = URL(string: url)?.host {
  268. NCNetworking.shared.writeCertificate(host: host)
  269. }
  270. NextcloudKit.shared.getLoginFlowV2(serverUrl: url) { token, endpoint, login, _, error in
  271. self.loginButton.isEnabled = true
  272. // Login Flow V2
  273. if error == .success, let token, let endpoint, let login {
  274. let vc = UIHostingController(rootView: NCLoginPoll(loginFlowV2Token: token, loginFlowV2Endpoint: endpoint, loginFlowV2Login: login))
  275. self.present(vc, animated: true)
  276. } else if serverInfo.versionMajor < NCGlobal.shared.nextcloudVersion12 { // No login flow available
  277. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_webflow_not_available_", comment: ""), preferredStyle: .alert)
  278. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  279. self.present(alertController, animated: true, completion: { })
  280. }
  281. }
  282. case .failure(let error):
  283. self.loginButton.isEnabled = true
  284. if error.errorCode == NSURLErrorServerCertificateUntrusted {
  285. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  286. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  287. if let host = URL(string: url)?.host {
  288. NCNetworking.shared.writeCertificate(host: host)
  289. }
  290. }))
  291. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  292. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  293. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  294. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  295. if let host = URL(string: url)?.host {
  296. viewController.host = host
  297. }
  298. self.present(navigationController, animated: true)
  299. }
  300. }))
  301. self.present(alertController, animated: true)
  302. } else {
  303. let alertController = UIAlertController(title: NSLocalizedString("_connection_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  304. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  305. self.present(alertController, animated: true, completion: { })
  306. }
  307. }
  308. }
  309. }
  310. // MARK: - QRCode
  311. func dismissQRCode(_ value: String?, metadataType: String?) {
  312. guard var value = value else { return }
  313. let protocolLogin = NCBrandOptions.shared.webLoginAutenticationProtocol + "login/"
  314. if value.hasPrefix(protocolLogin) && value.contains("user:") && value.contains("password:") && value.contains("server:") {
  315. value = value.replacingOccurrences(of: protocolLogin, with: "")
  316. let valueArray = value.components(separatedBy: "&")
  317. if valueArray.count == 3 {
  318. let user = valueArray[0].replacingOccurrences(of: "user:", with: "")
  319. let password = valueArray[1].replacingOccurrences(of: "password:", with: "")
  320. let urlBase = valueArray[2].replacingOccurrences(of: "server:", with: "")
  321. let serverUrl = urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav
  322. loginButton.isEnabled = false
  323. NextcloudKit.shared.checkServer(serverUrl: serverUrl) { error in
  324. self.loginButton.isEnabled = true
  325. if error == .success {
  326. self.createAccount(urlBase: urlBase, user: user, password: password)
  327. } else {
  328. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  329. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  330. self.present(alertController, animated: true)
  331. }
  332. }
  333. }
  334. }
  335. }
  336. private func getAppPassword(urlBase: String, user: String, password: String) {
  337. NextcloudKit.shared.getAppPassword(url: urlBase, user: user, password: password) { token, _, error in
  338. if error == .success, let password = token {
  339. self.createAccount(urlBase: urlBase, user: user, password: password)
  340. } else {
  341. NCContentPresenter().showError(error: error)
  342. self.dismiss(animated: true, completion: nil)
  343. }
  344. }
  345. }
  346. private func createAccount(urlBase: String, user: String, password: String) {
  347. if let host = URL(string: urlBase)?.host {
  348. NCNetworking.shared.writeCertificate(host: host)
  349. }
  350. self.appDelegate.createAccount(urlBase: urlBase, user: user, password: password) { error in
  351. if error == .success {
  352. let window = UIApplication.shared.firstWindow
  353. if window?.rootViewController is NCMainTabBarController {
  354. self.dismiss(animated: true)
  355. } else {
  356. if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as? NCMainTabBarController {
  357. controller.modalPresentationStyle = .fullScreen
  358. controller.view.alpha = 0
  359. window?.rootViewController = controller
  360. window?.makeKeyAndVisible()
  361. UIView.animate(withDuration: 0.5) {
  362. controller.view.alpha = 1
  363. }
  364. }
  365. }
  366. } else {
  367. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  368. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  369. self.present(alertController, animated: true)
  370. }
  371. }
  372. }
  373. }
  374. extension NCLogin: NCShareAccountsDelegate {
  375. func selected(url: String, user: String) {
  376. isUrlValid(url: url, user: user)
  377. }
  378. }
  379. extension NCLogin: ClientCertificateDelegate, UIDocumentPickerDelegate {
  380. func didAskForClientCertificate() {
  381. let alertNoCertFound = UIAlertController(title: NSLocalizedString("_no_client_cert_found_", comment: ""), message: NSLocalizedString("_no_client_cert_found_desc_", comment: ""), preferredStyle: .alert)
  382. alertNoCertFound.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  383. alertNoCertFound.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  384. let documentProviderMenu = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pkcs12])
  385. documentProviderMenu.delegate = self
  386. self.present(documentProviderMenu, animated: true, completion: nil)
  387. }))
  388. present(alertNoCertFound, animated: true)
  389. }
  390. func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  391. let alertEnterPassword = UIAlertController(title: NSLocalizedString("_client_cert_enter_password_", comment: ""), message: "", preferredStyle: .alert)
  392. alertEnterPassword.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  393. alertEnterPassword.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  394. // let documentProviderMenu = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pkcs12])
  395. NCNetworking.shared.p12Data = try? Data(contentsOf: urls[0])
  396. NCNetworking.shared.p12Password = alertEnterPassword.textFields?[0].text
  397. self.login()
  398. }))
  399. alertEnterPassword.addTextField { textField in
  400. textField.isSecureTextEntry = true
  401. }
  402. present(alertEnterPassword, animated: true)
  403. }
  404. func onIncorrectPassword() {
  405. NCNetworking.shared.p12Data = nil
  406. NCNetworking.shared.p12Password = nil
  407. let alertWrongPassword = UIAlertController(title: NSLocalizedString("_client_cert_wrong_password_", comment: ""), message: "", preferredStyle: .alert)
  408. alertWrongPassword.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default))
  409. present(alertWrongPassword, animated: true)
  410. }
  411. }