tokenary/Tokenary macOS/Screens/PasswordViewController.swift

99 lines
2.9 KiB
Swift
Raw Normal View History

2021-11-30 15:56:00 +03:00
// Copyright © 2021 Tokenary. All rights reserved.
2021-06-19 00:38:05 +03:00
import Cocoa
class PasswordViewController: NSViewController {
static func with(mode: Mode, reason: AuthenticationReason? = nil, completion: ((Bool) -> Void)?) -> PasswordViewController {
2021-06-19 00:38:05 +03:00
let new = instantiate(PasswordViewController.self)
new.mode = mode
new.reason = reason
2021-06-19 00:38:05 +03:00
new.completion = completion
return new
}
enum Mode {
case create, repeatAfterCreate, enter
}
private let keychain = Keychain.shared
2021-06-19 00:38:05 +03:00
private var mode = Mode.create
private var reason: AuthenticationReason?
2021-06-19 00:38:05 +03:00
private var passwordToRepeat: String?
private var completion: ((Bool) -> Void)?
2021-06-19 19:34:55 +03:00
@IBOutlet weak var reasonLabel: NSTextField!
2021-06-19 00:38:05 +03:00
@IBOutlet weak var cancelButton: NSButton!
@IBOutlet weak var okButton: NSButton!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var passwordTextField: NSSecureTextField! {
didSet {
passwordTextField.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
switchToMode(mode)
if let reason = reason, reason != .start {
reasonLabel.stringValue = "to " + reason.title.lowercased()
} else {
2021-06-19 19:34:55 +03:00
reasonLabel.stringValue = ""
}
2021-06-20 11:00:58 +03:00
}
2021-06-19 00:38:05 +03:00
func switchToMode(_ mode: Mode) {
self.mode = mode
switch mode {
case .create:
2021-09-01 21:47:15 +03:00
titleLabel.stringValue = Strings.createPassword
2021-06-19 00:38:05 +03:00
passwordToRepeat = nil
case .repeatAfterCreate:
2021-09-01 21:47:15 +03:00
titleLabel.stringValue = Strings.repeatPassword
2021-06-19 00:38:05 +03:00
passwordToRepeat = passwordTextField.stringValue
case .enter:
2021-09-01 21:47:15 +03:00
titleLabel.stringValue = Strings.enterPassword
2021-06-19 00:38:05 +03:00
}
passwordTextField.stringValue = ""
okButton.isEnabled = false
}
@IBAction func actionButtonTapped(_ sender: Any) {
switch mode {
case .create:
switchToMode(.repeatAfterCreate)
case .repeatAfterCreate:
let repeated = passwordTextField.stringValue
if repeated == passwordToRepeat {
keychain.save(password: repeated)
2021-06-19 00:38:05 +03:00
completion?(true)
}
case .enter:
if keychain.password == passwordTextField.stringValue {
completion?(true)
}
2021-06-19 00:38:05 +03:00
}
}
@IBAction func cancelButtonTapped(_ sender: NSButton) {
switch mode {
case .create:
view.window?.contentViewController = WelcomeViewController.new(completion: completion)
case .repeatAfterCreate:
switchToMode(.create)
case .enter:
completion?(false)
2021-06-19 00:38:05 +03:00
}
}
}
extension PasswordViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
2021-12-07 20:35:14 +03:00
okButton.isEnabled = passwordTextField.stringValue.isOkAsPassword
2021-06-19 00:38:05 +03:00
}
}