-
-
Notifications
You must be signed in to change notification settings - Fork 992
Expand file tree
/
Copy pathNCLogin.swift
More file actions
528 lines (446 loc) · 23.8 KB
/
NCLogin.swift
File metadata and controls
528 lines (446 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// SPDX-FileCopyrightText: Nextcloud GmbH
// SPDX-FileCopyrightText: 2025 Marino Faggiana
// SPDX-FileCopyrightText: 2025 Milen Pivchev
// SPDX-License-Identifier: GPL-3.0-or-later
import UniformTypeIdentifiers
import UIKit
import NextcloudKit
import SwiftUI
import SafariServices
import LucidBanner
class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate {
@IBOutlet weak var imageBrand: UIImageView!
@IBOutlet weak var imageBrandConstraintY: NSLayoutConstraint!
@IBOutlet weak var baseUrlTextField: UITextField!
@IBOutlet weak var loginAddressDetail: UILabel!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var qrCode: UIButton!
@IBOutlet weak var certificate: UIButton!
@IBOutlet weak var enforceServersButton: UIButton!
@IBOutlet weak var enforceServersDropdownImage: UIImageView!
private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
private var textColor: UIColor = .white
private var textColorOpponent: UIColor = .black
private var activeTextfieldDiff: CGFloat = 0
private var activeTextField = UITextField()
private var shareAccounts: [NKShareAccounts.DataAccounts]?
/// Controller
var controller: NCMainTabBarController?
/// The URL that will show up on the URL field when this screen appears
var urlBase = ""
// Used for MDM
var configServerUrl: String?
var configUsername: String?
var configPassword: String?
var configAppPassword: String?
private var p12Data: Data?
private var p12Password: String?
private var QRCodeCheck: Bool = false
private var activeLoginProvider: NCLoginProvider?
// LucidBanner
var banner: LucidBanner?
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Text color
if NCBrandColor.shared.customer.isTooLight() {
textColor = .black
textColorOpponent = .white
} else if NCBrandColor.shared.customer.isTooDark() {
textColor = .white
textColorOpponent = .black
} else {
textColor = .white
textColorOpponent = .black
}
// Image Brand
imageBrand.image = UIImage(named: "logo")
// Url
baseUrlTextField.textColor = textColor
baseUrlTextField.tintColor = textColor
baseUrlTextField.layer.cornerRadius = 10
baseUrlTextField.layer.borderWidth = 1
baseUrlTextField.layer.borderColor = textColor.cgColor
baseUrlTextField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: baseUrlTextField.frame.height))
baseUrlTextField.leftViewMode = .always
baseUrlTextField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: baseUrlTextField.frame.height))
baseUrlTextField.rightViewMode = .always
baseUrlTextField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("_login_url_", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: textColor.withAlphaComponent(0.5)])
baseUrlTextField.delegate = self
baseUrlTextField.isEnabled = !NCBrandOptions.shared.disable_request_login_url
// Login button
loginAddressDetail.textColor = textColor
loginAddressDetail.text = String.localizedStringWithFormat(NSLocalizedString("_login_address_detail_", comment: ""), NCBrandOptions.shared.brand)
// QR code button
qrCode.tintColor = NCBrandColor.shared.customer.isTooLight() ? .black : .white
// brand
if NCBrandOptions.shared.disable_request_login_url {
baseUrlTextField.isEnabled = false
baseUrlTextField.isUserInteractionEnabled = false
baseUrlTextField.alpha = 0.5
urlBase = NCBrandOptions.shared.loginBaseUrl
}
// certificate
certificate.setImage(UIImage(named: "certificate")?.image(color: textColor, size: 100), for: .normal)
certificate.isHidden = true
certificate.isEnabled = false
// navigation
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithTransparentBackground()
navBarAppearance.shadowColor = .clear
navBarAppearance.shadowImage = UIImage()
navBarAppearance.titleTextAttributes = [.foregroundColor: textColor]
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: textColor]
self.navigationController?.navigationBar.standardAppearance = navBarAppearance
self.navigationController?.view.backgroundColor = NCBrandColor.shared.customer
self.navigationController?.navigationBar.tintColor = textColor
if let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) {
// Nextcloud update share accounts
Task {
await NCAccount().updateAppsShareAccounts()
}
// Nextcloud get share accounts
if let shareAccounts = NKShareAccounts().getShareAccount(at: dirGroupApps, application: UIApplication.shared) {
var accountTemp = [NKShareAccounts.DataAccounts]()
for shareAccount in shareAccounts {
if NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "urlBase == %@ AND user == %@", shareAccount.url, shareAccount.user)) == nil {
accountTemp.append(shareAccount)
}
}
if !accountTemp.isEmpty {
self.shareAccounts = accountTemp
let image = NCUtility().loadImage(named: "person.badge.plus")
let navigationItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(openShareAccountsViewController(_:)))
navigationItem.tintColor = textColor
self.navigationItem.rightBarButtonItem = navigationItem
}
}
}
self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
view.backgroundColor = NCBrandColor.shared.customer
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
handleLoginWithAppConfig()
baseUrlTextField.text = urlBase
enforceServersButton.setTitle(NSLocalizedString("_select_server_", comment: ""), for: .normal)
let enforceServers = NCBrandOptions.shared.enforce_servers
if !enforceServers.isEmpty {
baseUrlTextField.isHidden = true
enforceServersDropdownImage.isHidden = false
enforceServersButton.isHidden = false
let actions = enforceServers.map { server in
UIAction(title: server.name, handler: { [self] _ in
enforceServersButton.setTitle(server.name, for: .normal)
baseUrlTextField.text = server.url
})
}
enforceServersButton.layer.cornerRadius = 10
enforceServersButton.menu = .init(title: NSLocalizedString("_servers_", comment: ""), children: actions)
enforceServersButton.showsMenuAsPrimaryAction = true
enforceServersButton.configuration?.titleTextAttributesTransformer =
UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = UIFont.systemFont(ofSize: 13)
return outgoing
}
}
NCNetworking.shared.certificateDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !NCManageDatabase.shared.getAllTableAccount().isEmpty,
self.navigationController?.viewControllers.count ?? 0 == 1 {
let navigationItemCancel = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(actionCancel(_:)))
navigationItemCancel.tintColor = textColor
navigationItem.leftBarButtonItem = navigationItemCancel
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.shareAccounts != nil,
let windowScene = view.window?.windowScene {
let title = String(format: NSLocalizedString("_apps_nextcloud_detect_", comment: ""), NCBrandOptions.shared.brand)
let subtitle = String(format: NSLocalizedString("_add_existing_account_", comment: ""), NCBrandOptions.shared.brand)
self.banner = LucidBannerRegistry.shared.banner(for: windowScene)
showAlertActionBanner(lucidBanner: banner,
title: title,
subtitle: subtitle) {
self.openShareAccountsViewController(nil)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.banner?.dismiss()
}
private func handleLoginWithAppConfig() {
let accountCount = NCManageDatabase.shared.getAccounts()?.count ?? 0
// load AppConfig
if (NCBrandOptions.shared.disable_multiaccount == false) || (NCBrandOptions.shared.disable_multiaccount == true && accountCount == 0) {
if let configurationManaged = UserDefaults.standard.dictionary(forKey: "com.apple.configuration.managed"), NCBrandOptions.shared.use_AppConfig {
if let serverUrl = configurationManaged[NCGlobal.shared.configuration_serverUrl] as? String {
self.configServerUrl = serverUrl
}
if let username = configurationManaged[NCGlobal.shared.configuration_username] as? String, !username.isEmpty, username.lowercased() != "username" {
self.configUsername = username
}
if let password = configurationManaged[NCGlobal.shared.configuration_password] as? String, !password.isEmpty, password.lowercased() != "password" {
self.configPassword = password
}
if let apppassword = configurationManaged[NCGlobal.shared.configuration_apppassword] as? String, !apppassword.isEmpty, apppassword.lowercased() != "apppassword" {
self.configAppPassword = apppassword
}
}
}
// AppConfig
if let url = configServerUrl {
Task {
if let user = self.configUsername, let password = configAppPassword {
await createAccount(urlBase: url, user: user, password: password)
return
} else if let user = self.configUsername, let password = configPassword {
await getAppPassword(urlBase: url, user: user, password: password)
return
} else {
urlBase = url
}
}
}
}
// MARK: - TextField
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
actionButtonLogin(self)
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.activeTextField = textField
}
// MARK: - Keyboard notification
@objc internal func keyboardWillShow(_ notification: Notification?) {
activeTextfieldDiff = 0
if let info = notification?.userInfo, let centerObject = self.activeTextField.superview?.convert(self.activeTextField.center, to: nil) {
let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
if let keyboardFrame = info[frameEndUserInfoKey] as? CGRect {
let diff = keyboardFrame.origin.y - centerObject.y - self.activeTextField.frame.height
if diff < 0 {
activeTextfieldDiff = diff
imageBrandConstraintY.constant += diff
}
}
}
}
@objc func keyboardWillHide(_ notification: Notification) {
imageBrandConstraintY.constant -= activeTextfieldDiff
}
// MARK: - Action
@objc func actionCancel(_ sender: Any?) {
dismiss(animated: true) { }
}
@IBAction func actionButtonLogin(_ sender: Any) {
NCNetworking.shared.p12Data = nil
NCNetworking.shared.p12Password = nil
login()
}
@IBAction func actionQRCode(_ sender: Any) {
let qrCode = NCLoginQRCode(delegate: self)
qrCode.scan()
}
@IBAction func actionCertificate(_ sender: Any) {
}
// MARK: - Share accounts View Controller
@objc func openShareAccountsViewController(_ sender: Any?) {
if let shareAccounts = self.shareAccounts, let vc = UIStoryboard(name: "NCShareAccounts", bundle: nil).instantiateInitialViewController() as? NCShareAccounts {
vc.accounts = shareAccounts
vc.enableTimerProgress = false
vc.dismissDidEnterBackground = false
vc.delegate = self
let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
let numberCell = shareAccounts.count
let height = min(CGFloat(numberCell * Int(vc.heightCell) + 45), screenHeighMax)
let popup = NCPopupViewController(contentController: vc, popupWidth: 300, popupHeight: height + 20)
self.present(popup, animated: true)
}
}
// MARK: - Login
private func login() {
guard var url = baseUrlTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
if url.hasSuffix("/") { url = String(url.dropLast()) }
if url.isEmpty { return }
// Check whether baseUrl contain protocol. If not add https:// by default.
if url.hasPrefix("https") == false && url.hasPrefix("http") == false {
url = "https://" + url
}
self.baseUrlTextField.text = url
isUrlValid(url: url)
}
func isUrlValid(url: String, user: String? = nil) {
loginButton.isEnabled = false
loginButton.hideButtonAndShowSpinner()
NextcloudKit.shared.getServerStatus(serverUrl: url) { [self] _, serverInfoResult in
switch serverInfoResult {
case .success:
if let host = URL(string: url)?.host {
NCNetworking.shared.writeCertificate(host: host)
}
let loginOptions = NKRequestOptions(customUserAgent: userAgent)
NextcloudKit.shared.getLoginFlowV2(serverUrl: url, options: loginOptions) { [self] token, endpoint, login, _, error in
// Login Flow V2
if error == .success, let token, let endpoint, let login {
nkLog(debug: "Successfully received login flow information.")
let loginProvider = NCLoginProvider()
loginProvider.initialURLString = login
loginProvider.delegate = self
loginProvider.controller = self.controller
loginProvider.presentingViewController = self
loginProvider.startPolling(loginFlowV2Token: token, loginFlowV2Endpoint: endpoint, loginFlowV2Login: login)
loginProvider.startAuthentication()
self.activeLoginProvider = loginProvider
}
}
case .failure(let error):
loginButton.hideSpinnerAndShowButton()
loginButton.isEnabled = true
if error.errorCode == NSURLErrorServerCertificateUntrusted {
let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
if let host = URL(string: url)?.host {
NCNetworking.shared.writeCertificate(host: host)
}
}))
alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
let viewController = navigationController.topViewController as? NCViewCertificateDetails {
if let host = URL(string: url)?.host {
viewController.host = host
}
self.present(navigationController, animated: true)
}
}))
self.present(alertController, animated: true)
} else {
let alertController = UIAlertController(title: NSLocalizedString("_connection_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
self.present(alertController, animated: true, completion: { })
}
}
}
}
// MARK: - QRCode
func dismissQRCode(_ value: String?, metadataType: String?) {
guard let value, !QRCodeCheck else {
return
}
QRCodeCheck = true
Task { @MainActor in
let protocolLogin = NCBrandOptions.shared.webLoginAutenticationProtocol + "login/"
let protocolLoginOneTime = NCBrandOptions.shared.webLoginAutenticationProtocol + "onetime-login/"
var parameters: String = ""
if value.hasPrefix(protocolLoginOneTime) {
parameters = value.replacingOccurrences(of: protocolLoginOneTime, with: "")
} else if value.hasPrefix(protocolLogin) {
parameters = value.replacingOccurrences(of: protocolLogin, with: "")
} else {
QRCodeCheck = false
return
}
guard parameters.contains("user:"),
parameters.contains("password:"),
parameters.contains("server:") else {
QRCodeCheck = false
return
}
let parametersArray = parameters.components(separatedBy: "&")
let user = parametersArray[0].replacingOccurrences(of: "user:", with: "")
let password = parametersArray[1].replacingOccurrences(of: "password:", with: "")
let server = parametersArray[2].replacingOccurrences(of: "server:", with: "")
if value.hasPrefix(protocolLoginOneTime) {
let results = await NextcloudKit.shared.getAppPasswordOnetimeAsync(url: server, user: user, onetimeToken: password)
if results.error == .success, let token = results.token {
await createAccount(urlBase: server, user: user, password: token)
} else {
let windowScene = SceneManager.shared.getWindowScene(controller: self.controller)
await showErrorBanner(windowScene: windowScene, text: results.error.errorDescription, errorCode: results.error.errorCode)
dismiss(animated: true, completion: nil)
}
} else if value.hasPrefix(protocolLogin) {
await self.createAccount(urlBase: server, user: user, password: password)
}
}
}
private func getAppPassword(urlBase: String, user: String, password: String) async {
let results = await NextcloudKit.shared.getAppPasswordAsync(url: urlBase, user: user, password: password)
if results.error == .success, let password = results.token {
await self.createAccount(urlBase: urlBase, user: user, password: password)
} else {
let windowScene = SceneManager.shared.getWindowScene(controller: self.controller)
await showErrorBanner(windowScene: windowScene, text: results.error.errorDescription, errorCode: results.error.errorCode)
dismiss(animated: true, completion: nil)
}
}
@MainActor
private func createAccount(urlBase: String, user: String, password: String) async {
if self.controller == nil {
self.controller = UIApplication.shared.mainAppWindow?.rootViewController as? NCMainTabBarController
}
if let host = URL(string: urlBase)?.host {
NCNetworking.shared.writeCertificate(host: host)
}
await NCAccount().createAccount(viewController: self, urlBase: urlBase, user: user, password: password, controller: self.controller)
}
}
// MARK: - NCShareAccountsDelegate
extension NCLogin: NCShareAccountsDelegate {
func selected(url: String, user: String) {
isUrlValid(url: url, user: user)
}
}
// MARK: - UIDocumentPickerDelegate
extension NCLogin: ClientCertificateDelegate, UIDocumentPickerDelegate {
func didAskForClientCertificate() {
let alertNoCertFound = UIAlertController(title: NSLocalizedString("_no_client_cert_found_", comment: ""), message: NSLocalizedString("_no_client_cert_found_desc_", comment: ""), preferredStyle: .alert)
alertNoCertFound.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
alertNoCertFound.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
let documentProviderMenu = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pkcs12])
documentProviderMenu.delegate = self
self.present(documentProviderMenu, animated: true, completion: nil)
}))
DispatchQueue.main.async {
self.present(alertNoCertFound, animated: true)
}
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
let alertEnterPassword = UIAlertController(title: NSLocalizedString("_client_cert_enter_password_", comment: ""), message: "", preferredStyle: .alert)
alertEnterPassword.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
alertEnterPassword.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
NCNetworking.shared.p12Data = try? Data(contentsOf: urls[0])
NCNetworking.shared.p12Password = alertEnterPassword.textFields?[0].text
self.login()
}))
alertEnterPassword.addTextField { textField in
textField.isSecureTextEntry = true
}
DispatchQueue.main.async {
self.present(alertEnterPassword, animated: true)
}
}
func onIncorrectPassword() {
NCNetworking.shared.p12Data = nil
NCNetworking.shared.p12Password = nil
let alertWrongPassword = UIAlertController(title: NSLocalizedString("_client_cert_wrong_password_", comment: ""), message: "", preferredStyle: .alert)
alertWrongPassword.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default))
DispatchQueue.main.async {
self.present(alertWrongPassword, animated: true)
}
}
}
// MARK: - NCLoginProviderDelegate
extension NCLogin: NCLoginProviderDelegate {
func onBack() {
loginButton.isEnabled = true
loginButton.hideSpinnerAndShowButton()
activeLoginProvider?.cancel()
activeLoginProvider = nil
}
}