NCLogin.swift 23 KB

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