#include "auth_dialog.h" #include "repository_manager.h" #include "repository_result.h" #include "role_dto.h" #include "roles_repository.h" #include "schema_metadata.h" #include "user_dto.h" #include "users_repository.h" #include #include #include AuthDialog::AuthDialog(QWidget *parent) : QDialog(parent) { setupUi(this); // WARNING: Models must be initialized before setting up table view if (initializeRepositories()) { setupConnections(); } else { qWarning() << "Initialization failed"; } } bool AuthDialog::initializeRepositories() { RepositoryManager &repositoryManager = RepositoryManager::instance(); SchemaMetadata metadata = SchemaMetadata::defaultSchema(); rolesRepository_ = repositoryManager.getRepositoryAs( metadata.repositoryTableName("roles")); usersRepository_ = repositoryManager.getRepositoryAs( metadata.repositoryTableName("users")); return rolesRepository_ && usersRepository_; } void AuthDialog::setupConnections() { connect(btnLogin, &QPushButton::clicked, this, &AuthDialog::onLoginClicked); connect(btnCancel, &QPushButton::clicked, this, &AuthDialog::onCancelClicked); } void AuthDialog::onCancelClicked() { emit loginFailed(); reject(); } void AuthDialog::onLoginClicked() { QString username = txtUsername->text().trimmed(); QString password = txtPassword->text(); UserDTO userDTO; RepositoryResult result = usersRepository_->getUserByUsername(username, userDTO); bool userExists = result.success; bool passwordMatch = !userExists ? false : verifyPassword(password, userDTO); if (!userExists || !passwordMatch) { QMessageBox::warning(this, QMessageBox::tr("Error"), QMessageBox::tr("Wrong user name or password")); return; } RoleDTO roleDTO; result = rolesRepository_->getRoleById(userDTO.roleId(), roleDTO); if (!result.success) { QMessageBox::warning(this, QMessageBox::tr("Error"), QMessageBox::tr("Role of user not found")); return; } qint32 userId = userDTO.userId(); qint32 accessLevel_ = roleDTO.accessLevel(); emit loginSuccessful(userId, accessLevel_); accept(); } QString AuthDialog::hashPassword(const QString &password, const QString &salt) { QByteArray data = (password + salt).toUtf8(); QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256); return QString(hash.toHex()); } bool AuthDialog::verifyPassword(const QString &password, const UserDTO &userDTO) { QString inputHash = hashPassword(password, userDTO.salt()); return (inputHash == userDTO.passwordHash()); }