MasterPasswordDialog.cpp raw
 1#include "MasterPasswordDialog.h"
 2#include <QApplication>
 3#include <QFormLayout>
 4#include <QVBoxLayout>
 5#include "VaultManager.h"
 6
 7MasterPasswordDialog::MasterPasswordDialog(bool isSetupMode, QWidget *parent) : QDialog(parent), setupMode(isSetupMode) {
 8	setWindowTitle(setupMode ? "Set Master Password" : "Unlock Vault");
 9	setModal(true);
10
11	auto *layout = new QVBoxLayout(this);
12
13	auto *passLabel = new QLabel("Master password:", this);
14	layout->addWidget(passLabel);
15
16	passwordEdit = new QLineEdit(this);
17	passwordEdit->setEchoMode(QLineEdit::Password);
18	layout->addWidget(passwordEdit);
19
20	if (setupMode) {
21		auto *confirmLabel = new QLabel("Confirm master password:", this);
22		layout->addWidget(confirmLabel);
23		confirmEdit = new QLineEdit(this);
24		confirmEdit->setEchoMode(QLineEdit::Password);
25		layout->addWidget(confirmEdit);
26	} else {
27		confirmEdit = nullptr;
28	}
29
30	errorLabel = new QLabel(this);
31	QPalette pal = errorLabel->palette();
32	pal.setColor(QPalette::WindowText, Qt::red);
33	errorLabel->setPalette(pal);
34	errorLabel->hide();
35	layout->addWidget(errorLabel);
36
37	buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
38	buttonBox->button(QDialogButtonBox::Ok)->setText(setupMode ? "Initialize" : "Unlock");
39
40	connect(buttonBox, &QDialogButtonBox::accepted, this, &MasterPasswordDialog::handleSubmit);
41	connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
42	layout->addWidget(buttonBox);
43
44	passwordEdit->setFocus();
45}
46
47void MasterPasswordDialog::handleSubmit() {
48	QString password = passwordEdit->text();
49	errorLabel->hide();
50
51	if (setupMode) {
52		if (password.isEmpty()) {
53			errorLabel->setText("Password cannot be empty.");
54			errorLabel->show();
55			return;
56		}
57		if (password != confirmEdit->text()) {
58			errorLabel->setText("Passwords do not match.");
59			errorLabel->show();
60			return;
61		}
62		if (VaultManager::instance().setup(password)) {
63			accept();
64		} else {
65			errorLabel->setText("Failed to initialize vault.");
66			errorLabel->show();
67		}
68	} else {
69		if (VaultManager::instance().unlock(password)) {
70			accept();
71		} else {
72			errorLabel->setText("Incorrect password.");
73			errorLabel->show();
74			passwordEdit->clear();
75			passwordEdit->setFocus();
76		}
77	}
78}