keepassxc/src/browser/BrowserService.cpp

1316 lines
42 KiB
C++
Raw Normal View History

2017-12-12 10:15:23 +02:00
/*
* Copyright (C) 2023 KeePassXC Team <team@keepassxc.org>
* Copyright (C) 2017 Sami Vänttinen <sami.vanttinen@protonmail.com>
* Copyright (C) 2013 Francois Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2017-12-12 10:15:23 +02:00
2021-07-11 22:10:29 -04:00
#include "BrowserService.h"
#include "BrowserAction.h"
2018-03-31 16:01:30 -04:00
#include "BrowserEntryConfig.h"
#include "BrowserEntrySaveDialog.h"
#include "BrowserHost.h"
#include "BrowserMessageBuilder.h"
2018-03-31 16:01:30 -04:00
#include "BrowserSettings.h"
#include "core/Tools.h"
2023-10-14 16:18:27 +03:00
#include "core/UrlTools.h"
#include "gui/MainWindow.h"
Customize buttons on MessageBox and confirm before recycling (#2376) * Add confirmation prompt before moving groups to the recycling bin Spawn a yes/no QMessage box when "Delete Group" is selected on a group that is not already in the recycle bin (note: the prompt for deletion from the recycle bin was already implemented). This follows the same pattern and language as entry deletion. Fixes #2125 * Make prompts for destructive operations use action words on buttons Replace yes/no, yes/cancel (and other such buttons on prompts that cause data to be destroyed) use language that indicates the action that it is going to take. This makes destructive/unsafe and/or irreversible operations more clear to the user. Address feedback on PR #2376 * Refactor MessageBox class to allow for custom buttons Replaces arguments and return values of type QMessageBox::StandardButton(s) with MessageBox::Button(s), which reimplements the entire set of QMessageBox::StandardButton and allows for custom KeePassXC buttons, such as "Skip". Modifies all calls to MessageBox functions to use MessageBox::Button(s). Addresses feedback on #2376 * Remove MessageBox::addButton in favor of map lookup Replaced the switch statement mechanism in MessageBox::addButton with a map lookup to address CodeFactor Complex Method issue. This has a side-effect of a small performance/cleanliness increase, as an extra QPushButton is no longer created/destroyed (to obtain it's label text) everytime a MessageBox button based on QMessageBox::StandardButton is created; now the text is obtained once, at application start up.
2018-12-19 20:14:11 -08:00
#include "gui/MessageBox.h"
#include "gui/osutils/OSUtils.h"
#ifdef Q_OS_MACOS
#include "gui/osutils/macutils/MacUtils.h"
#endif
2017-12-12 10:15:23 +02:00
2021-07-11 22:10:29 -04:00
#include <QCheckBox>
#include <QCryptographicHash>
#include <QHostAddress>
#include <QInputDialog>
#include <QJsonArray>
#include <QJsonObject>
#include <QListWidget>
#include <QLocalSocket>
2021-07-11 22:10:29 -04:00
#include <QProgressDialog>
#include <QUrl>
const QString BrowserService::KEEPASSXCBROWSER_NAME = QStringLiteral("KeePassXC-Browser Settings");
const QString BrowserService::KEEPASSXCBROWSER_OLD_NAME = QStringLiteral("keepassxc-browser Settings");
static const QString KEEPASSXCBROWSER_GROUP_NAME = QStringLiteral("KeePassXC-Browser Passwords");
2018-03-31 16:01:30 -04:00
static int KEEPASSXCBROWSER_DEFAULT_ICON = 1;
// These are for the settings and password conversion
static const QString KEEPASSHTTP_NAME = QStringLiteral("KeePassHttp Settings");
static const QString KEEPASSHTTP_GROUP_NAME = QStringLiteral("KeePassHttp Passwords");
// Extra entry related options saved in custom data
const QString BrowserService::OPTION_SKIP_AUTO_SUBMIT = QStringLiteral("BrowserSkipAutoSubmit");
const QString BrowserService::OPTION_HIDE_ENTRY = QStringLiteral("BrowserHideEntry");
const QString BrowserService::OPTION_ONLY_HTTP_AUTH = QStringLiteral("BrowserOnlyHttpAuth");
const QString BrowserService::OPTION_NOT_HTTP_AUTH = QStringLiteral("BrowserNotHttpAuth");
const QString BrowserService::OPTION_OMIT_WWW = QStringLiteral("BrowserOmitWww");
// Multiple URL's
const QString BrowserService::ADDITIONAL_URL = QStringLiteral("KP2A_URL");
2017-12-12 10:15:23 +02:00
Q_GLOBAL_STATIC(BrowserService, s_browserService);
BrowserService::BrowserService()
: QObject()
, m_browserHost(new BrowserHost)
2022-10-26 10:24:49 +03:00
, m_dialogActive(false)
, m_bringToFrontRequested(false)
, m_passwordGeneratorRequested(false)
, m_prevWindowState(WindowState::Normal)
, m_keepassBrowserUUID(Tools::hexToUuid("de887cc3036343b8974b5911b8816224"))
2017-12-12 10:15:23 +02:00
{
connect(m_browserHost, &BrowserHost::clientMessageReceived, this, &BrowserService::processClientMessage);
connect(getMainWindow(), &MainWindow::databaseUnlocked, this, &BrowserService::databaseUnlocked);
connect(getMainWindow(), &MainWindow::databaseLocked, this, &BrowserService::databaseLocked);
connect(getMainWindow(), &MainWindow::activeDatabaseChanged, this, &BrowserService::activeDatabaseChanged);
setEnabled(browserSettings()->isEnabled());
}
BrowserService* BrowserService::instance()
{
return s_browserService;
}
void BrowserService::setEnabled(bool enabled)
{
if (enabled) {
// Update KeePassXC/keepassxc-proxy binary paths to Native Messaging scripts
if (browserSettings()->updateBinaryPath()) {
browserSettings()->updateBinaryPaths();
}
m_browserHost->start();
} else {
m_browserHost->stop();
}
2017-12-12 10:15:23 +02:00
}
bool BrowserService::isDatabaseOpened() const
{
if (m_currentDatabaseWidget) {
return !m_currentDatabaseWidget->isLocked();
2017-12-12 10:15:23 +02:00
}
return false;
2017-12-12 10:15:23 +02:00
}
2018-01-17 14:55:13 +02:00
bool BrowserService::openDatabase(bool triggerUnlock)
2017-12-12 10:15:23 +02:00
{
if (!browserSettings()->unlockDatabase()) {
2017-12-12 10:15:23 +02:00
return false;
}
if (m_currentDatabaseWidget && !m_currentDatabaseWidget->isLocked()) {
2017-12-12 10:15:23 +02:00
return true;
}
2018-01-17 14:55:13 +02:00
if (triggerUnlock) {
m_bringToFrontRequested = true;
updateWindowState();
emit requestUnlock();
2018-01-17 14:55:13 +02:00
}
2017-12-12 10:15:23 +02:00
return false;
}
void BrowserService::lockDatabase()
{
if (m_currentDatabaseWidget) {
m_currentDatabaseWidget->lock();
2017-12-12 10:15:23 +02:00
}
}
2017-12-12 10:15:23 +02:00
QString BrowserService::getDatabaseHash(bool legacy)
{
if (legacy) {
return QCryptographicHash::hash(
(browserService()->getDatabaseRootUuid() + browserService()->getDatabaseRecycleBinUuid()).toUtf8(),
QCryptographicHash::Sha256)
.toHex();
2017-12-12 10:15:23 +02:00
}
return QCryptographicHash::hash(getDatabaseRootUuid().toUtf8(), QCryptographicHash::Sha256).toHex();
2017-12-12 10:15:23 +02:00
}
QString BrowserService::getDatabaseRootUuid()
{
auto db = getDatabase();
2017-12-12 10:15:23 +02:00
if (!db) {
return {};
2017-12-12 10:15:23 +02:00
}
Group* rootGroup = db->rootGroup();
if (!rootGroup) {
return {};
2017-12-12 10:15:23 +02:00
}
return rootGroup->uuidToHex();
2017-12-12 10:15:23 +02:00
}
QString BrowserService::getDatabaseRecycleBinUuid()
{
auto db = getDatabase();
2017-12-12 10:15:23 +02:00
if (!db) {
return {};
2017-12-12 10:15:23 +02:00
}
Group* recycleBin = db->metadata()->recycleBin();
if (!recycleBin) {
return {};
2017-12-12 10:15:23 +02:00
}
return recycleBin->uuidToHex();
2017-12-12 10:15:23 +02:00
}
QJsonArray BrowserService::getChildrenFromGroup(Group* group)
{
QJsonArray groupList;
if (!group) {
return groupList;
}
for (const auto& c : group->children()) {
if (c == group->database()->metadata()->recycleBin()) {
continue;
}
QJsonObject jsonGroup;
jsonGroup["name"] = c->name();
jsonGroup["uuid"] = Tools::uuidToHex(c->uuid());
jsonGroup["children"] = getChildrenFromGroup(c);
groupList.push_back(jsonGroup);
}
return groupList;
}
QJsonObject BrowserService::getDatabaseGroups()
{
auto db = getDatabase();
if (!db) {
return {};
}
Group* rootGroup = db->rootGroup();
if (!rootGroup) {
return {};
}
QJsonObject root;
root["name"] = rootGroup->name();
root["uuid"] = Tools::uuidToHex(rootGroup->uuid());
root["children"] = getChildrenFromGroup(rootGroup);
QJsonArray groups;
groups.push_back(root);
QJsonObject result;
result["groups"] = groups;
return result;
}
QJsonArray BrowserService::getDatabaseEntries()
{
auto db = getDatabase();
if (!db) {
return {};
}
Group* rootGroup = db->rootGroup();
if (!rootGroup) {
return {};
}
QJsonArray entries;
for (const auto& group : rootGroup->groupsRecursive(true)) {
if (group == db->metadata()->recycleBin()) {
continue;
}
for (const auto& entry : group->entries()) {
QJsonObject jentry;
jentry["title"] = entry->resolveMultiplePlaceholders(entry->title());
jentry["uuid"] = entry->resolveMultiplePlaceholders(entry->uuidToHex());
jentry["url"] = entry->resolveMultiplePlaceholders(entry->url());
entries.push_back(jentry);
}
}
return entries;
}
QJsonObject BrowserService::createNewGroup(const QString& groupName)
{
auto db = getDatabase();
if (!db) {
return {};
}
Group* rootGroup = db->rootGroup();
if (!rootGroup) {
return {};
}
auto group = rootGroup->findGroupByPath(groupName);
// Group already exists
if (group) {
QJsonObject result;
result["name"] = group->name();
result["uuid"] = Tools::uuidToHex(group->uuid());
return result;
}
2023-07-20 09:52:20 +03:00
auto dialogResult = MessageBox::warning(m_currentDatabaseWidget,
tr("KeePassXC: Create a new group"),
tr("A request for creating a new group \"%1\" has been received.\n"
2019-03-19 14:48:33 -04:00
"Do you want to create this group?\n")
.arg(groupName),
MessageBox::Yes | MessageBox::No);
if (dialogResult != MessageBox::Yes) {
return {};
}
QString name, uuid;
Group* previousGroup = rootGroup;
auto groups = groupName.split("/");
// Returns the group name based on depth
auto getGroupName = [&](int depth) {
QString gName;
2019-03-19 14:48:33 -04:00
for (int i = 0; i < depth + 1; ++i) {
gName.append((i == 0 ? "" : "/") + groups[i]);
}
return gName;
};
2019-03-19 14:48:33 -04:00
// Create new group(s) always when the path is not found
for (int i = 0; i < groups.length(); ++i) {
QString gName = getGroupName(i);
auto tempGroup = rootGroup->findGroupByPath(gName);
if (!tempGroup) {
2019-03-19 14:48:33 -04:00
Group* newGroup = new Group();
newGroup->setName(groups[i]);
newGroup->setUuid(QUuid::createUuid());
newGroup->setParent(previousGroup);
name = newGroup->name();
uuid = Tools::uuidToHex(newGroup->uuid());
previousGroup = newGroup;
continue;
}
previousGroup = tempGroup;
}
2019-03-19 14:48:33 -04:00
QJsonObject result;
result["name"] = name;
result["uuid"] = uuid;
return result;
}
QString BrowserService::getCurrentTotp(const QString& uuid)
{
QList<QSharedPointer<Database>> databases;
if (browserSettings()->searchInAllDatabases()) {
for (auto dbWidget : getMainWindow()->getOpenDatabases()) {
auto db = dbWidget->database();
if (db) {
databases << db;
}
}
} else {
databases << getDatabase();
}
auto entryUuid = Tools::hexToUuid(uuid);
for (const auto& db : databases) {
auto entry = db->rootGroup()->findEntryByUuid(entryUuid, true);
if (entry) {
return entry->totp();
}
}
return {};
}
QJsonArray
BrowserService::findEntries(const EntryParameters& entryParameters, const StringPairList& keyList, bool* entriesFound)
{
if (entriesFound) {
*entriesFound = false;
}
const bool alwaysAllowAccess = browserSettings()->alwaysAllowAccess();
const bool ignoreHttpAuth = browserSettings()->httpAuthPermission();
const QString siteHost = QUrl(entryParameters.siteUrl).host();
const QString formHost = QUrl(entryParameters.formUrl).host();
// Check entries for authorization
QList<Entry*> entriesToConfirm;
QList<Entry*> allowedEntries;
for (auto* entry : searchEntries(entryParameters.siteUrl, entryParameters.formUrl, keyList)) {
auto entryCustomData = entry->customData();
if (!entryParameters.httpAuth
&& ((entryCustomData->contains(BrowserService::OPTION_ONLY_HTTP_AUTH)
&& entryCustomData->value(BrowserService::OPTION_ONLY_HTTP_AUTH) == TRUE_STR)
|| entry->group()->resolveCustomDataTriState(BrowserService::OPTION_ONLY_HTTP_AUTH) == Group::Enable)) {
continue;
}
if (entryParameters.httpAuth
&& ((entryCustomData->contains(BrowserService::OPTION_NOT_HTTP_AUTH)
&& entryCustomData->value(BrowserService::OPTION_NOT_HTTP_AUTH) == TRUE_STR)
|| entry->group()->resolveCustomDataTriState(BrowserService::OPTION_NOT_HTTP_AUTH) == Group::Enable)) {
continue;
}
// HTTP Basic Auth always needs a confirmation
if (!ignoreHttpAuth && entryParameters.httpAuth) {
entriesToConfirm.append(entry);
continue;
}
switch (checkAccess(entry, siteHost, formHost, entryParameters.realm)) {
case Denied:
continue;
case Unknown:
if (alwaysAllowAccess) {
allowedEntries.append(entry);
} else {
entriesToConfirm.append(entry);
}
break;
case Allowed:
allowedEntries.append(entry);
break;
}
}
if (entriesToConfirm.isEmpty() && allowedEntries.isEmpty()) {
return {};
}
// Confirm entries
auto selectedEntriesToConfirm =
confirmEntries(entriesToConfirm, entryParameters, siteHost, formHost, entryParameters.httpAuth);
if (!selectedEntriesToConfirm.isEmpty()) {
allowedEntries.append(selectedEntriesToConfirm);
}
2022-10-26 10:24:49 +03:00
// Ensure that database is not locked when the popup was visible
if (!isDatabaseOpened()) {
return {};
}
2022-10-26 10:24:49 +03:00
// Sort results
allowedEntries = sortEntries(allowedEntries, entryParameters.siteUrl, entryParameters.formUrl);
2022-10-26 10:24:49 +03:00
// Fill the list
QJsonArray entries;
for (auto* entry : allowedEntries) {
entries.append(prepareEntry(entry));
2022-10-26 10:24:49 +03:00
}
if (entriesFound != nullptr) {
*entriesFound = true;
}
return entries;
2022-10-26 10:24:49 +03:00
}
QList<Entry*> BrowserService::confirmEntries(QList<Entry*>& entriesToConfirm,
const EntryParameters& entryParameters,
2022-10-26 10:24:49 +03:00
const QString& siteHost,
const QString& formUrl,
const bool httpAuth)
{
if (entriesToConfirm.isEmpty() || m_dialogActive) {
2022-10-26 10:24:49 +03:00
return {};
}
2022-10-26 10:24:49 +03:00
m_dialogActive = true;
updateWindowState();
2023-07-20 09:52:20 +03:00
BrowserAccessControlDialog accessControlDialog(m_currentDatabaseWidget);
2022-10-26 10:24:49 +03:00
connect(m_currentDatabaseWidget, SIGNAL(databaseLockRequested()), &accessControlDialog, SLOT(reject()));
2022-10-26 10:24:49 +03:00
connect(&accessControlDialog, &BrowserAccessControlDialog::disableAccess, [&](QTableWidgetItem* item) {
auto entry = entriesToConfirm[item->row()];
denyEntry(entry, siteHost, formUrl, entryParameters.realm);
2022-10-26 10:24:49 +03:00
});
accessControlDialog.setEntries(entriesToConfirm, entryParameters.siteUrl, httpAuth);
2022-10-26 10:24:49 +03:00
QList<Entry*> allowedEntries;
auto ret = accessControlDialog.exec();
auto remember = accessControlDialog.remember();
// All are denied
if (ret == QDialog::Rejected && remember) {
for (auto& entry : entriesToConfirm) {
denyEntry(entry, siteHost, formUrl, entryParameters.realm);
}
}
// Some/all are accepted
if (ret == QDialog::Accepted) {
auto selectedEntries = accessControlDialog.getEntries(SelectionType::Selected);
for (auto& item : selectedEntries) {
auto entry = entriesToConfirm[item->row()];
allowedEntries.append(entry);
if (remember) {
allowEntry(entry, siteHost, formUrl, entryParameters.realm);
2022-10-26 10:24:49 +03:00
}
}
// Remembered non-selected entries must be denied
if (remember) {
auto nonSelectedEntries = accessControlDialog.getEntries(SelectionType::NonSelected);
for (auto& item : nonSelectedEntries) {
auto entry = entriesToConfirm[item->row()];
denyEntry(entry, siteHost, formUrl, entryParameters.realm);
}
2022-10-26 10:24:49 +03:00
}
}
// Handle disabled entries (returned Accept/Reject status does not matter)
auto disabledEntries = accessControlDialog.getEntries(SelectionType::Disabled);
for (auto& item : disabledEntries) {
auto entry = entriesToConfirm[item->row()];
denyEntry(entry, siteHost, formUrl, entryParameters.realm);
}
2022-10-26 10:24:49 +03:00
// Re-hide the application if it wasn't visible before
hideWindow();
2022-10-26 10:24:49 +03:00
m_dialogActive = false;
return allowedEntries;
}
void BrowserService::showPasswordGenerator(const KeyPairMessage& keyPairMessage)
{
if (!m_passwordGenerator) {
2023-07-20 09:52:20 +03:00
m_passwordGenerator.reset(PasswordGeneratorWidget::popupGenerator(m_currentDatabaseWidget));
connect(m_passwordGenerator.data(), &PasswordGeneratorWidget::closed, m_passwordGenerator.data(), [=] {
if (!m_passwordGenerator->isPasswordGenerated()) {
auto errorMessage = browserMessageBuilder()->getErrorReply("generate-password",
ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED);
m_browserHost->sendClientMessage(keyPairMessage.socket, errorMessage);
}
m_passwordGenerator.reset();
hideWindow();
m_passwordGeneratorRequested = false;
});
connect(m_passwordGenerator.data(),
&PasswordGeneratorWidget::appliedPassword,
m_passwordGenerator.data(),
[=](const QString& password) {
const Parameters params{{"password", password}};
m_browserHost->sendClientMessage(keyPairMessage.socket,
browserMessageBuilder()->buildResponse("generate-password",
keyPairMessage.nonce,
params,
keyPairMessage.publicKey,
keyPairMessage.secretKey));
hideWindow();
});
}
m_passwordGeneratorRequested = true;
raiseWindow();
m_passwordGenerator->raise();
m_passwordGenerator->activateWindow();
}
bool BrowserService::isPasswordGeneratorRequested() const
{
return m_passwordGeneratorRequested;
}
2017-12-12 10:15:23 +02:00
QString BrowserService::storeKey(const QString& key)
{
auto db = getDatabase();
if (!db) {
return {};
2017-12-12 10:15:23 +02:00
}
bool contains;
auto dialogResult = MessageBox::Cancel;
QString id;
2017-12-12 10:15:23 +02:00
do {
2023-07-20 09:52:20 +03:00
QInputDialog keyDialog(m_currentDatabaseWidget);
connect(m_currentDatabaseWidget, SIGNAL(databaseLockRequested()), &keyDialog, SLOT(reject()));
keyDialog.setWindowTitle(tr("KeePassXC: New key association request"));
keyDialog.setLabelText(tr("You have received an association request for the following database:\n%1\n\n"
"Give the connection a unique name or ID, for example:\nchrome-laptop.")
.arg(db->metadata()->name().toHtmlEscaped()));
keyDialog.setOkButtonText(tr("Save and allow access"));
keyDialog.setWindowFlags(keyDialog.windowFlags() | Qt::WindowStaysOnTopHint);
raiseWindow();
keyDialog.show();
keyDialog.activateWindow();
keyDialog.raise();
auto ok = keyDialog.exec();
id = keyDialog.textValue();
2019-04-27 13:37:42 +03:00
if (ok != QDialog::Accepted || id.isEmpty() || !isDatabaseOpened()) {
hideWindow();
return {};
2017-12-12 10:15:23 +02:00
}
contains = db->metadata()->customData()->contains(CustomData::BrowserKeyPrefix + id);
if (contains) {
2023-07-20 09:52:20 +03:00
dialogResult = MessageBox::warning(m_currentDatabaseWidget,
Customize buttons on MessageBox and confirm before recycling (#2376) * Add confirmation prompt before moving groups to the recycling bin Spawn a yes/no QMessage box when "Delete Group" is selected on a group that is not already in the recycle bin (note: the prompt for deletion from the recycle bin was already implemented). This follows the same pattern and language as entry deletion. Fixes #2125 * Make prompts for destructive operations use action words on buttons Replace yes/no, yes/cancel (and other such buttons on prompts that cause data to be destroyed) use language that indicates the action that it is going to take. This makes destructive/unsafe and/or irreversible operations more clear to the user. Address feedback on PR #2376 * Refactor MessageBox class to allow for custom buttons Replaces arguments and return values of type QMessageBox::StandardButton(s) with MessageBox::Button(s), which reimplements the entire set of QMessageBox::StandardButton and allows for custom KeePassXC buttons, such as "Skip". Modifies all calls to MessageBox functions to use MessageBox::Button(s). Addresses feedback on #2376 * Remove MessageBox::addButton in favor of map lookup Replaced the switch statement mechanism in MessageBox::addButton with a map lookup to address CodeFactor Complex Method issue. This has a side-effect of a small performance/cleanliness increase, as an extra QPushButton is no longer created/destroyed (to obtain it's label text) everytime a MessageBox button based on QMessageBox::StandardButton is created; now the text is obtained once, at application start up.
2018-12-19 20:14:11 -08:00
tr("KeePassXC: Overwrite existing key?"),
tr("A shared encryption key with the name \"%1\" "
"already exists.\nDo you want to overwrite it?")
.arg(id),
MessageBox::Overwrite | MessageBox::Cancel,
MessageBox::Cancel);
}
Customize buttons on MessageBox and confirm before recycling (#2376) * Add confirmation prompt before moving groups to the recycling bin Spawn a yes/no QMessage box when "Delete Group" is selected on a group that is not already in the recycle bin (note: the prompt for deletion from the recycle bin was already implemented). This follows the same pattern and language as entry deletion. Fixes #2125 * Make prompts for destructive operations use action words on buttons Replace yes/no, yes/cancel (and other such buttons on prompts that cause data to be destroyed) use language that indicates the action that it is going to take. This makes destructive/unsafe and/or irreversible operations more clear to the user. Address feedback on PR #2376 * Refactor MessageBox class to allow for custom buttons Replaces arguments and return values of type QMessageBox::StandardButton(s) with MessageBox::Button(s), which reimplements the entire set of QMessageBox::StandardButton and allows for custom KeePassXC buttons, such as "Skip". Modifies all calls to MessageBox functions to use MessageBox::Button(s). Addresses feedback on #2376 * Remove MessageBox::addButton in favor of map lookup Replaced the switch statement mechanism in MessageBox::addButton with a map lookup to address CodeFactor Complex Method issue. This has a side-effect of a small performance/cleanliness increase, as an extra QPushButton is no longer created/destroyed (to obtain it's label text) everytime a MessageBox button based on QMessageBox::StandardButton is created; now the text is obtained once, at application start up.
2018-12-19 20:14:11 -08:00
} while (contains && dialogResult == MessageBox::Cancel);
2017-12-12 10:15:23 +02:00
hideWindow();
db->metadata()->customData()->set(CustomData::BrowserKeyPrefix + id, key);
db->metadata()->customData()->set(QString("%1_%2").arg(CustomData::Created, id),
Clock::currentDateTime().toString(Qt::SystemLocaleShortDate));
2017-12-12 10:15:23 +02:00
return id;
}
QString BrowserService::getKey(const QString& id)
{
auto db = getDatabase();
if (!db) {
return {};
2017-12-12 10:15:23 +02:00
}
return db->metadata()->customData()->value(CustomData::BrowserKeyPrefix + id);
2017-12-12 10:15:23 +02:00
}
void BrowserService::addEntry(const EntryParameters& entryParameters,
const QString& group,
const QString& groupUuid,
const bool downloadFavicon,
const QSharedPointer<Database>& selectedDb)
2017-12-12 10:15:23 +02:00
{
// TODO: select database based on this key id
auto db = selectedDb ? selectedDb : selectedDatabase();
if (!db) {
2019-06-18 18:23:12 -04:00
return;
}
auto* entry = new Entry();
2018-03-23 11:18:06 +01:00
entry->setUuid(QUuid::createUuid());
entry->setTitle(QUrl(entryParameters.siteUrl).host());
entry->setUrl(entryParameters.siteUrl);
2017-12-12 10:15:23 +02:00
entry->setIcon(KEEPASSXCBROWSER_DEFAULT_ICON);
entry->setUsername(entryParameters.login);
entry->setPassword(entryParameters.password);
// Select a group for the entry
if (!group.isEmpty()) {
if (db->rootGroup()) {
auto selectedGroup = db->rootGroup()->findGroupByUuid(Tools::hexToUuid(groupUuid));
2019-05-07 10:51:24 +03:00
if (selectedGroup) {
entry->setGroup(selectedGroup);
2019-05-07 10:51:24 +03:00
} else {
entry->setGroup(getDefaultEntryGroup(db));
}
}
2019-05-07 10:51:24 +03:00
} else {
entry->setGroup(getDefaultEntryGroup(db));
}
2017-12-12 10:15:23 +02:00
const QString host = QUrl(entryParameters.siteUrl).host();
const QString submitHost = QUrl(entryParameters.formUrl).host();
2017-12-12 10:15:23 +02:00
BrowserEntryConfig config;
config.allow(host);
if (!submitHost.isEmpty()) {
config.allow(submitHost);
}
if (!entryParameters.realm.isEmpty()) {
config.setRealm(entryParameters.realm);
2017-12-12 10:15:23 +02:00
}
config.save(entry);
if (downloadFavicon && m_currentDatabaseWidget) {
m_currentDatabaseWidget->downloadFaviconInBackground(entry);
}
2017-12-12 10:15:23 +02:00
}
bool BrowserService::updateEntry(const EntryParameters& entryParameters, const QString& uuid)
2017-12-12 10:15:23 +02:00
{
// TODO: select database based on this key id
auto db = selectedDatabase();
2017-12-12 10:15:23 +02:00
if (!db) {
return false;
2017-12-12 10:15:23 +02:00
}
Entry* entry = db->rootGroup()->findEntryByUuid(Tools::hexToUuid(uuid));
2017-12-12 10:15:23 +02:00
if (!entry) {
// If entry is not found for update, add a new one to the selected database
addEntry(entryParameters, "", "", false, db);
return true;
2017-12-12 10:15:23 +02:00
}
// Check if the entry password is a reference. If so, update the original entry instead
while (entry->attributes()->isReference(EntryAttributes::PasswordKey)) {
const QUuid referenceUuid = entry->attributes()->referenceUuid(EntryAttributes::PasswordKey);
if (!referenceUuid.isNull()) {
entry = db->rootGroup()->findEntryByUuid(referenceUuid);
if (!entry) {
return false;
}
}
}
auto username = entry->username();
2017-12-12 10:15:23 +02:00
if (username.isEmpty()) {
return false;
2017-12-12 10:15:23 +02:00
}
bool result = false;
if (username.compare(entryParameters.login, Qt::CaseSensitive) != 0
|| entry->password().compare(entryParameters.password, Qt::CaseSensitive) != 0) {
Customize buttons on MessageBox and confirm before recycling (#2376) * Add confirmation prompt before moving groups to the recycling bin Spawn a yes/no QMessage box when "Delete Group" is selected on a group that is not already in the recycle bin (note: the prompt for deletion from the recycle bin was already implemented). This follows the same pattern and language as entry deletion. Fixes #2125 * Make prompts for destructive operations use action words on buttons Replace yes/no, yes/cancel (and other such buttons on prompts that cause data to be destroyed) use language that indicates the action that it is going to take. This makes destructive/unsafe and/or irreversible operations more clear to the user. Address feedback on PR #2376 * Refactor MessageBox class to allow for custom buttons Replaces arguments and return values of type QMessageBox::StandardButton(s) with MessageBox::Button(s), which reimplements the entire set of QMessageBox::StandardButton and allows for custom KeePassXC buttons, such as "Skip". Modifies all calls to MessageBox functions to use MessageBox::Button(s). Addresses feedback on #2376 * Remove MessageBox::addButton in favor of map lookup Replaced the switch statement mechanism in MessageBox::addButton with a map lookup to address CodeFactor Complex Method issue. This has a side-effect of a small performance/cleanliness increase, as an extra QPushButton is no longer created/destroyed (to obtain it's label text) everytime a MessageBox button based on QMessageBox::StandardButton is created; now the text is obtained once, at application start up.
2018-12-19 20:14:11 -08:00
MessageBox::Button dialogResult = MessageBox::No;
if (!browserSettings()->alwaysAllowUpdate()) {
raiseWindow();
2023-07-20 09:52:20 +03:00
dialogResult = MessageBox::question(m_currentDatabaseWidget,
tr("KeePassXC: Update Entry"),
tr("Do you want to update the information in %1 - %2?")
.arg(QUrl(entryParameters.siteUrl).host(), username),
MessageBox::Save | MessageBox::Cancel,
MessageBox::Cancel,
MessageBox::Raise);
2017-12-12 10:15:23 +02:00
}
Customize buttons on MessageBox and confirm before recycling (#2376) * Add confirmation prompt before moving groups to the recycling bin Spawn a yes/no QMessage box when "Delete Group" is selected on a group that is not already in the recycle bin (note: the prompt for deletion from the recycle bin was already implemented). This follows the same pattern and language as entry deletion. Fixes #2125 * Make prompts for destructive operations use action words on buttons Replace yes/no, yes/cancel (and other such buttons on prompts that cause data to be destroyed) use language that indicates the action that it is going to take. This makes destructive/unsafe and/or irreversible operations more clear to the user. Address feedback on PR #2376 * Refactor MessageBox class to allow for custom buttons Replaces arguments and return values of type QMessageBox::StandardButton(s) with MessageBox::Button(s), which reimplements the entire set of QMessageBox::StandardButton and allows for custom KeePassXC buttons, such as "Skip". Modifies all calls to MessageBox functions to use MessageBox::Button(s). Addresses feedback on #2376 * Remove MessageBox::addButton in favor of map lookup Replaced the switch statement mechanism in MessageBox::addButton with a map lookup to address CodeFactor Complex Method issue. This has a side-effect of a small performance/cleanliness increase, as an extra QPushButton is no longer created/destroyed (to obtain it's label text) everytime a MessageBox button based on QMessageBox::StandardButton is created; now the text is obtained once, at application start up.
2018-12-19 20:14:11 -08:00
if (browserSettings()->alwaysAllowUpdate() || dialogResult == MessageBox::Save) {
2017-12-12 10:15:23 +02:00
entry->beginUpdate();
if (!entry->attributes()->isReference(EntryAttributes::UserNameKey)) {
entry->setUsername(entryParameters.login);
}
entry->setPassword(entryParameters.password);
2017-12-12 10:15:23 +02:00
entry->endUpdate();
result = true;
2017-12-12 10:15:23 +02:00
}
hideWindow();
2017-12-12 10:15:23 +02:00
}
2019-06-13 10:05:29 +03:00
return result;
2017-12-12 10:15:23 +02:00
}
bool BrowserService::deleteEntry(const QString& uuid)
{
auto db = selectedDatabase();
if (!db) {
return false;
}
auto* entry = db->rootGroup()->findEntryByUuid(Tools::hexToUuid(uuid));
if (!entry) {
return false;
}
2023-07-20 09:52:20 +03:00
auto dialogResult = MessageBox::warning(m_currentDatabaseWidget,
tr("KeePassXC: Delete entry"),
tr("A request for deleting entry \"%1\" has been received.\n"
"Do you want to delete the entry?\n")
.arg(entry->title()),
MessageBox::Yes | MessageBox::No);
if (dialogResult != MessageBox::Yes) {
return false;
}
db->recycleEntry(entry);
return true;
}
2019-01-29 05:39:43 +01:00
QList<Entry*>
BrowserService::searchEntries(const QSharedPointer<Database>& db, const QString& siteUrl, const QString& formUrl)
2017-12-12 10:15:23 +02:00
{
QList<Entry*> entries;
auto* rootGroup = db->rootGroup();
2017-12-12 10:15:23 +02:00
if (!rootGroup) {
return entries;
}
for (const auto& group : rootGroup->groupsRecursive(true)) {
if (group->isRecycled()
|| group->resolveCustomDataTriState(BrowserService::OPTION_HIDE_ENTRY) == Group::Enable) {
continue;
}
2017-12-12 10:15:23 +02:00
const auto omitWwwSubdomain =
group->resolveCustomDataTriState(BrowserService::OPTION_OMIT_WWW) == Group::Enable;
for (auto* entry : group->entries()) {
if (entry->isRecycled()
|| (entry->customData()->contains(BrowserService::OPTION_HIDE_ENTRY)
&& entry->customData()->value(BrowserService::OPTION_HIDE_ENTRY) == TRUE_STR)) {
continue;
}
if (!shouldIncludeEntry(entry, siteUrl, formUrl, omitWwwSubdomain)) {
continue;
}
// Additional URL check may have already inserted the entry to the list
if (!entries.contains(entry)) {
entries.append(entry);
}
2017-12-12 10:15:23 +02:00
}
}
return entries;
}
QList<Entry*>
BrowserService::searchEntries(const QString& siteUrl, const QString& formUrl, const StringPairList& keyList)
2017-12-12 10:15:23 +02:00
{
// Check if database is connected with KeePassXC-Browser
auto databaseConnected = [&](const QSharedPointer<Database>& db) {
for (const StringPair& keyPair : keyList) {
QString key = db->metadata()->customData()->value(CustomData::BrowserKeyPrefix + keyPair.first);
if (!key.isEmpty() && keyPair.second == key) {
return true;
}
}
return false;
};
2017-12-12 10:15:23 +02:00
// Get the list of databases to search
QList<QSharedPointer<Database>> databases;
if (browserSettings()->searchInAllDatabases()) {
for (auto dbWidget : getMainWindow()->getOpenDatabases()) {
auto db = dbWidget->database();
if (db && databaseConnected(dbWidget->database())) {
databases << db;
2017-12-12 10:15:23 +02:00
}
}
} else {
const auto& db = getDatabase();
if (databaseConnected(db)) {
databases << db;
}
2017-12-12 10:15:23 +02:00
}
// Search entries matching the hostname
QString hostname = QUrl(siteUrl).host();
2017-12-12 10:15:23 +02:00
QList<Entry*> entries;
do {
for (const auto& db : databases) {
entries << searchEntries(db, siteUrl, formUrl);
2017-12-12 10:15:23 +02:00
}
} while (entries.isEmpty() && removeFirstDomain(hostname));
return entries;
}
void BrowserService::requestGlobalAutoType(const QString& search)
{
emit osUtils->globalShortcutTriggered("autotype", search);
}
QList<Entry*> BrowserService::sortEntries(QList<Entry*>& entries, const QString& siteUrl, const QString& formUrl)
2017-12-12 10:15:23 +02:00
{
// Build map of prioritized entries
QMultiMap<int, Entry*> priorities;
for (auto* entry : entries) {
2022-11-12 11:27:28 +02:00
priorities.insert(sortPriority(entry->getAllUrls(), siteUrl, formUrl), entry);
2017-12-12 10:15:23 +02:00
}
auto keys = priorities.uniqueKeys();
std::sort(keys.begin(), keys.end(), [](int l, int r) { return l > r; });
QList<Entry*> results;
for (auto key : keys) {
results << priorities.values(key);
if (browserSettings()->bestMatchOnly() && !results.isEmpty()) {
// Early out once we find the highest batch of matches
break;
2017-12-12 10:15:23 +02:00
}
}
2017-12-12 10:15:23 +02:00
return results;
2017-12-12 10:15:23 +02:00
}
void BrowserService::allowEntry(Entry* entry, const QString& siteHost, const QString& formUrl, const QString& realm)
2017-12-12 10:15:23 +02:00
{
BrowserEntryConfig config;
config.load(entry);
config.allow(siteHost);
2017-12-12 10:15:23 +02:00
if (!formUrl.isEmpty() && siteHost != formUrl) {
config.allow(formUrl);
}
if (!realm.isEmpty()) {
config.setRealm(realm);
}
config.save(entry);
}
void BrowserService::denyEntry(Entry* entry, const QString& siteHost, const QString& formUrl, const QString& realm)
{
BrowserEntryConfig config;
config.load(entry);
config.deny(siteHost);
2017-12-12 10:15:23 +02:00
if (!formUrl.isEmpty() && siteHost != formUrl) {
config.deny(formUrl);
2017-12-12 10:15:23 +02:00
}
if (!realm.isEmpty()) {
config.setRealm(realm);
}
config.save(entry);
2017-12-12 10:15:23 +02:00
}
QJsonObject BrowserService::prepareEntry(const Entry* entry)
{
QJsonObject res;
res["login"] = entry->resolveMultiplePlaceholders(entry->username());
res["password"] = entry->resolveMultiplePlaceholders(entry->password());
res["name"] = entry->resolveMultiplePlaceholders(entry->title());
res["uuid"] = entry->resolveMultiplePlaceholders(entry->uuidToHex());
res["group"] = entry->resolveMultiplePlaceholders(entry->group()->name());
2017-12-12 10:15:23 +02:00
if (entry->hasTotp()) {
res["totp"] = entry->totp();
}
if (entry->isExpired()) {
res["expired"] = TRUE_STR;
}
auto skipAutoSubmitGroup = entry->group()->resolveCustomDataTriState(BrowserService::OPTION_SKIP_AUTO_SUBMIT);
if (skipAutoSubmitGroup == Group::Inherit) {
if (entry->customData()->contains(BrowserService::OPTION_SKIP_AUTO_SUBMIT)) {
res["skipAutoSubmit"] = entry->customData()->value(BrowserService::OPTION_SKIP_AUTO_SUBMIT);
}
} else {
res["skipAutoSubmit"] = skipAutoSubmitGroup == Group::Enable ? TRUE_STR : FALSE_STR;
}
if (browserSettings()->supportKphFields()) {
2017-12-12 10:15:23 +02:00
const EntryAttributes* attr = entry->attributes();
QJsonArray stringFields;
for (const auto& key : attr->keys()) {
if (key.startsWith("KPH: ")) {
2017-12-12 10:15:23 +02:00
QJsonObject sField;
sField[key] = entry->resolveMultiplePlaceholders(attr->value(key));
2019-05-19 15:58:52 -04:00
stringFields.append(sField);
2017-12-12 10:15:23 +02:00
}
}
res["stringFields"] = stringFields;
}
return res;
}
2018-03-31 16:01:30 -04:00
BrowserService::Access
BrowserService::checkAccess(const Entry* entry, const QString& siteHost, const QString& formHost, const QString& realm)
2017-12-12 10:15:23 +02:00
{
2023-06-29 18:13:34 +03:00
if (entry->isExpired() && !browserSettings()->allowExpiredCredentials()) {
return Denied;
}
2017-12-12 10:15:23 +02:00
BrowserEntryConfig config;
if (!config.load(entry)) {
return Unknown;
}
if ((config.isAllowed(siteHost)) && (formHost.isEmpty() || config.isAllowed(formHost))) {
2017-12-12 10:15:23 +02:00
return Allowed;
}
if ((config.isDenied(siteHost)) || (!formHost.isEmpty() && config.isDenied(formHost))) {
2017-12-12 10:15:23 +02:00
return Denied;
}
if (!realm.isEmpty() && config.realm() != realm) {
return Denied;
}
return Unknown;
}
2019-05-07 10:51:24 +03:00
Group* BrowserService::getDefaultEntryGroup(const QSharedPointer<Database>& selectedDb)
2017-12-12 10:15:23 +02:00
{
auto db = selectedDb ? selectedDb : getDatabase();
2017-12-12 10:15:23 +02:00
if (!db) {
return nullptr;
}
auto* rootGroup = db->rootGroup();
2017-12-12 10:15:23 +02:00
if (!rootGroup) {
return nullptr;
}
for (auto* g : rootGroup->groupsRecursive(true)) {
if (g->name() == KEEPASSXCBROWSER_GROUP_NAME && !g->isRecycled()) {
return db->rootGroup()->findGroupByUuid(g->uuid());
2017-12-12 10:15:23 +02:00
}
}
auto* group = new Group();
2018-03-23 11:18:06 +01:00
group->setUuid(QUuid::createUuid());
group->setName(KEEPASSXCBROWSER_GROUP_NAME);
2017-12-12 10:15:23 +02:00
group->setIcon(KEEPASSXCBROWSER_DEFAULT_ICON);
group->setParent(rootGroup);
return group;
}
// Returns the maximum sort priority given a set of match urls and the
// extension provided site and form url.
int BrowserService::sortPriority(const QStringList& urls, const QString& siteUrl, const QString& formUrl)
2017-12-12 10:15:23 +02:00
{
QList<int> priorityList;
// NOTE: QUrl::matches is utterly broken in Qt < 5.11, so we work around that
// by removing parts of the url that we don't match and direct matching others
const auto stdOpts = QUrl::RemoveFragment | QUrl::RemoveUserInfo;
const auto adjustedSiteUrl = QUrl(siteUrl).adjusted(stdOpts);
const auto adjustedFormUrl = QUrl(formUrl).adjusted(stdOpts);
auto getPriority = [&](const QString& givenUrl) {
auto url = QUrl::fromUserInput(givenUrl).adjusted(stdOpts);
// Default to https scheme if undefined
if (url.scheme().isEmpty() || !givenUrl.contains("://")) {
url.setScheme("https");
}
2020-01-11 12:50:21 +02:00
// Add the empty path to the URL if it's missing.
// URL's from the extension always have a path set, entry URL's can be without.
if (url.path().isEmpty() && !url.hasFragment() && !url.hasQuery()) {
url.setPath("/");
}
2020-01-11 12:50:21 +02:00
// Reject invalid urls and hosts, except 'localhost', and scheme mismatch
if (!url.isValid() || (!url.host().contains(".") && url.host() != "localhost")
|| url.scheme() != adjustedSiteUrl.scheme()) {
return 0;
}
2017-12-12 10:15:23 +02:00
// Exact match with site url or form url
if (url.matches(adjustedSiteUrl, QUrl::None) || url.matches(adjustedFormUrl, QUrl::None)) {
return 100;
}
// Exact match without the query string
if (url.matches(adjustedSiteUrl, QUrl::RemoveQuery) || url.matches(adjustedFormUrl, QUrl::RemoveQuery)) {
return 90;
}
// Parent directory match
if (url.isParentOf(adjustedSiteUrl) || url.isParentOf(adjustedFormUrl)) {
return 85;
}
// Match without path (ie, FQDN match), form url prioritizes lower than site url
if (url.host() == adjustedSiteUrl.host()) {
return 80;
}
if (url.host() == adjustedFormUrl.host()) {
return 70;
}
// Site/form url ends with given url (subdomain mismatch)
if (adjustedSiteUrl.host().endsWith(url.host())) {
return 60;
}
if (adjustedFormUrl.host().endsWith(url.host())) {
return 50;
}
// No valid match found
2019-11-01 20:13:12 +02:00
return 0;
};
for (const auto& entryUrl : urls) {
priorityList << getPriority(entryUrl);
2019-11-01 20:13:12 +02:00
}
return *std::max_element(priorityList.begin(), priorityList.end());
2017-12-12 10:15:23 +02:00
}
bool BrowserService::removeFirstDomain(QString& hostname)
{
int pos = hostname.indexOf(".");
if (pos < 0) {
return false;
}
// Don't remove the second-level domain if it's the only one
if (hostname.count(".") > 1) {
hostname = hostname.mid(pos + 1);
return !hostname.isEmpty();
}
// Nothing removed
return false;
}
/* Test if a search URL matches a custom entry. If the URL has the schema "keepassxc", some special checks will be made.
* Otherwise, this simply delegates to handleURL(). */
bool BrowserService::shouldIncludeEntry(Entry* entry,
const QString& url,
const QString& submitUrl,
const bool omitWwwSubdomain)
{
// Use this special scheme to find entries by UUID
2020-10-17 10:05:02 -04:00
if (url.startsWith("keepassxc://by-uuid/")) {
return url.endsWith("by-uuid/" + entry->uuidToHex());
} else if (url.startsWith("keepassxc://by-path/")) {
return url.endsWith("by-path/" + entry->path());
}
const auto allEntryUrls = entry->getAllUrls();
for (const auto& entryUrl : allEntryUrls) {
if (handleURL(entryUrl, url, submitUrl, omitWwwSubdomain)) {
return true;
}
}
return false;
}
bool BrowserService::handleURL(const QString& entryUrl,
const QString& siteUrl,
const QString& formUrl,
const bool omitWwwSubdomain)
{
2019-11-01 20:13:12 +02:00
if (entryUrl.isEmpty()) {
return false;
}
QUrl entryQUrl;
if (entryUrl.contains("://")) {
entryQUrl = entryUrl;
} else {
entryQUrl = QUrl::fromUserInput(entryUrl);
if (browserSettings()->matchUrlScheme()) {
entryQUrl.setScheme("https");
}
}
// Remove WWW subdomain from matching if group setting is enabled
if (omitWwwSubdomain && entryQUrl.host().startsWith("www.")) {
entryQUrl.setHost(entryQUrl.host().remove("www."));
}
2019-11-12 22:38:20 +02:00
// Make a direct compare if a local file is used
if (siteUrl.startsWith("file://")) {
return entryUrl == formUrl;
2019-11-12 22:38:20 +02:00
}
2019-11-01 20:13:12 +02:00
// URL host validation fails
2019-11-12 22:38:20 +02:00
if (entryQUrl.host().isEmpty()) {
2019-11-01 20:13:12 +02:00
return false;
}
// Match port, if used
QUrl siteQUrl(siteUrl);
2019-11-12 22:38:20 +02:00
if (entryQUrl.port() > 0 && entryQUrl.port() != siteQUrl.port()) {
2019-11-01 20:13:12 +02:00
return false;
}
2019-11-01 20:13:12 +02:00
// Match scheme
2019-11-18 06:57:04 +00:00
if (browserSettings()->matchUrlScheme() && !entryQUrl.scheme().isEmpty()
&& entryQUrl.scheme().compare(siteQUrl.scheme()) != 0) {
2019-11-01 20:13:12 +02:00
return false;
}
// Check for illegal characters
QRegularExpression re("[<>\\^`{|}]");
2019-11-12 22:38:20 +02:00
if (re.match(entryUrl).hasMatch()) {
return false;
}
2020-01-14 10:05:24 +02:00
// Match the base domain
2023-10-14 16:18:27 +03:00
if (urlTools()->getBaseDomainFromUrl(siteQUrl.host()) != urlTools()->getBaseDomainFromUrl(entryQUrl.host())) {
2020-01-14 10:05:24 +02:00
return false;
}
// Match the subdomains with the limited wildcard
if (siteQUrl.host().endsWith(entryQUrl.host())) {
return true;
}
2019-11-01 20:13:12 +02:00
return false;
2018-08-30 13:40:41 +03:00
}
QSharedPointer<Database> BrowserService::getDatabase()
2017-12-12 10:15:23 +02:00
{
if (m_currentDatabaseWidget) {
return m_currentDatabaseWidget->database();
2017-12-12 10:15:23 +02:00
}
return {};
2017-12-12 10:15:23 +02:00
}
QSharedPointer<Database> BrowserService::selectedDatabase()
{
QList<DatabaseWidget*> databaseWidgets;
for (auto dbWidget : getMainWindow()->getOpenDatabases()) {
// Add only open databases
if (!dbWidget->isLocked()) {
databaseWidgets << dbWidget;
}
}
2023-07-20 09:52:20 +03:00
BrowserEntrySaveDialog browserEntrySaveDialog(m_currentDatabaseWidget);
int openDatabaseCount = browserEntrySaveDialog.setItems(databaseWidgets, m_currentDatabaseWidget);
if (openDatabaseCount > 1) {
int res = browserEntrySaveDialog.exec();
if (res == QDialog::Accepted) {
const auto selectedDatabase = browserEntrySaveDialog.getSelected();
if (selectedDatabase.length() > 0) {
2019-11-01 20:13:12 +02:00
int index = selectedDatabase[0]->data(Qt::UserRole).toInt();
return databaseWidgets[index]->database();
}
} else {
return {};
}
}
// Return current database
return getDatabase();
}
void BrowserService::hideWindow() const
{
if (m_prevWindowState == WindowState::Minimized) {
getMainWindow()->showMinimized();
} else {
#ifdef Q_OS_MACOS
if (m_prevWindowState == WindowState::Hidden) {
macUtils()->hideOwnWindow();
} else {
macUtils()->raiseLastActiveWindow();
}
#else
if (m_prevWindowState == WindowState::Hidden) {
getMainWindow()->hideWindow();
} else {
getMainWindow()->lower();
}
#endif
}
}
void BrowserService::raiseWindow(const bool force)
{
m_prevWindowState = WindowState::Normal;
if (getMainWindow()->isMinimized()) {
m_prevWindowState = WindowState::Minimized;
}
#ifdef Q_OS_MACOS
2019-11-01 20:13:12 +02:00
Q_UNUSED(force)
if (macUtils()->isHidden()) {
m_prevWindowState = WindowState::Hidden;
}
macUtils()->raiseOwnWindow();
Tools::wait(500);
#else
if (getMainWindow()->isHidden()) {
m_prevWindowState = WindowState::Hidden;
}
if (force) {
getMainWindow()->bringToFront();
}
#endif
}
void BrowserService::updateWindowState()
{
m_prevWindowState = WindowState::Normal;
if (getMainWindow()->isMinimized()) {
m_prevWindowState = WindowState::Minimized;
}
#ifdef Q_OS_MACOS
if (macUtils()->isHidden()) {
m_prevWindowState = WindowState::Hidden;
}
#else
if (getMainWindow()->isHidden()) {
m_prevWindowState = WindowState::Hidden;
}
#endif
}
2017-12-12 10:15:23 +02:00
void BrowserService::databaseLocked(DatabaseWidget* dbWidget)
{
if (dbWidget) {
QJsonObject msg;
msg["action"] = QString("database-locked");
m_browserHost->broadcastClientMessage(msg);
2017-12-12 10:15:23 +02:00
}
}
void BrowserService::databaseUnlocked(DatabaseWidget* dbWidget)
{
if (dbWidget) {
if (m_bringToFrontRequested) {
m_bringToFrontRequested = false;
hideWindow();
}
QJsonObject msg;
msg["action"] = QString("database-unlocked");
m_browserHost->broadcastClientMessage(msg);
2017-12-12 10:15:23 +02:00
}
}
void BrowserService::activeDatabaseChanged(DatabaseWidget* dbWidget)
2017-12-12 10:15:23 +02:00
{
if (dbWidget) {
if (dbWidget->isLocked()) {
databaseLocked(dbWidget);
2017-12-12 10:15:23 +02:00
} else {
databaseUnlocked(dbWidget);
2017-12-12 10:15:23 +02:00
}
}
m_currentDatabaseWidget = dbWidget;
2017-12-12 10:15:23 +02:00
}
void BrowserService::processClientMessage(QLocalSocket* socket, const QJsonObject& message)
{
auto clientID = message["clientID"].toString();
if (clientID.isEmpty()) {
return;
}
// Create a new client action if we haven't seen this id yet
if (!m_browserClients.contains(clientID)) {
m_browserClients.insert(clientID, QSharedPointer<BrowserAction>::create());
}
auto& action = m_browserClients.value(clientID);
auto response = action->processClientMessage(socket, message);
m_browserHost->sendClientMessage(socket, response);
}