1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
23 #include <QCoreApplication>
26 #include "coreauthhandler.h"
27 #include "coresession.h"
28 #include "coresettings.h"
30 #include "internalpeer.h"
32 #include "postgresqlstorage.h"
34 #include "sqlauthenticator.h"
35 #include "sqlitestorage.h"
38 // Currently building with LDAP bindings is optional.
40 #include "ldapauthenticator.h"
52 // ==============================
54 // ==============================
55 const int Core::AddClientEventId = QEvent::registerEventType();
57 class AddClientEvent : public QEvent
60 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
66 // ==============================
68 // ==============================
69 Core *Core::_instance{nullptr};
71 Core *Core::instance()
80 qWarning() << "Recreating core instance!";
90 qDeleteAll(_connectingClients);
91 qDeleteAll(_sessions);
99 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
101 Quassel::loadTranslation(QLocale::system());
103 // check settings version
104 // so far, we only have 1
106 if (s.version() != 1) {
107 qCritical() << "Invalid core settings version, terminating!";
111 // Set up storage and authentication backends
112 registerStorageBackends();
113 registerAuthenticators();
115 QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
116 bool config_from_environment = Quassel::isOptionSet("config-from-environment");
119 QVariantMap db_connectionProperties;
121 QString auth_authenticator;
122 QVariantMap auth_properties;
124 bool writeError = false;
126 if (config_from_environment) {
127 db_backend = environment.value("DB_BACKEND");
128 auth_authenticator = environment.value("AUTH_AUTHENTICATOR");
132 QVariantMap dbsettings = cs.storageSettings().toMap();
133 db_backend = dbsettings.value("Backend").toString();
134 db_connectionProperties = dbsettings.value("ConnectionProperties").toMap();
136 QVariantMap authSettings = cs.authSettings().toMap();
137 auth_authenticator = authSettings.value("Authenticator", "Database").toString();
138 auth_properties = authSettings.value("AuthProperties").toMap();
140 writeError = !cs.isWritable();
144 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment);
146 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
148 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment);
151 if (Quassel::isOptionSet("select-backend") || Quassel::isOptionSet("select-authenticator")) {
152 if (Quassel::isOptionSet("select-backend")) {
153 selectBackend(Quassel::optionValue("select-backend"));
155 if (Quassel::isOptionSet("select-authenticator")) {
156 selectAuthenticator(Quassel::optionValue("select-authenticator"));
162 if (config_from_environment) {
163 _configured = initStorage(db_backend, db_connectionProperties, environment, config_from_environment, true);
164 initAuthenticator(auth_authenticator, auth_properties, environment, config_from_environment, true);
167 qWarning() << "Cannot configure from environment";
172 if (_registeredStorageBackends.empty()) {
173 quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
175 << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
176 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
178 exit(EXIT_FAILURE); // TODO make this less brutal (especially for mono client -> popup)
182 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
186 quInfo() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
190 if (Quassel::isOptionSet("add-user")) {
191 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
194 if (Quassel::isOptionSet("change-userpass")) {
195 exit(changeUserPass(Quassel::optionValue("change-userpass")) ? EXIT_SUCCESS : EXIT_FAILURE);
198 _strictIdentEnabled = Quassel::isOptionSet("strict-ident");
199 if (_strictIdentEnabled) {
203 if (Quassel::isOptionSet("oidentd")) {
204 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
207 Quassel::registerReloadHandler([]() {
208 // Currently, only reloading SSL certificates and the sysident cache is supported
209 if (Core::instance()) {
210 Core::instance()->cacheSysIdent();
211 Core::instance()->reloadCerts();
217 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
218 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
221 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
222 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
224 if (!startListening()) {
225 exit(EXIT_FAILURE); // TODO make this less brutal
228 if (_configured && !Quassel::isOptionSet("norestore")) {
229 Core::restoreState();
235 /*** Session Restore ***/
237 void Core::saveState()
240 QVariantList activeSessions;
241 for (auto &&user : instance()->_sessions.keys())
242 activeSessions << QVariant::fromValue<UserId>(user);
243 _storage->setCoreState(activeSessions);
248 void Core::restoreState()
251 quWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
254 if (_sessions.count()) {
255 quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
260 /* We don't check, since we are at the first version since switching to Git
261 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
263 quWarning() << qPrintable(tr("Core state too old, ignoring..."));
268 const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
269 QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
271 if (activeSessions.count() > 0) {
272 quInfo() << "Restoring previous core state...";
273 for(auto &&v : activeSessions) {
274 UserId user = v.value<UserId>();
275 sessionForUser(user, true);
283 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
285 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
289 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
292 return tr("Core is already configured! Not configuring again...");
294 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
295 return tr("Admin user or password not set.");
297 if (!(_configured = initStorage(backend, setupData, {}, false, true))) {
298 return tr("Could not setup storage!");
301 quInfo() << "Selected authenticator:" << authenticator;
302 if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
304 return tr("Could not setup authenticator!");
307 if (!saveBackendSettings(backend, setupData)) {
308 return tr("Could not save backend settings, probably a permission problem.");
310 saveAuthenticatorSettings(authenticator, authSetupData);
312 quInfo() << qPrintable(tr("Creating admin user..."));
313 _storage->addUser(adminUser, adminPassword);
315 startListening(); // TODO check when we need this
320 QString Core::setupCoreForInternalUsage()
322 Q_ASSERT(!_registeredStorageBackends.empty());
324 qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());
326 for (int i = 0; i < 10; i++) {
328 pass += qrand() % 10;
331 // mono client currently needs sqlite
332 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
336 /*** Storage Handling ***/
338 template<typename Storage>
339 void Core::registerStorageBackend()
341 auto backend = makeDeferredShared<Storage>(this);
342 if (backend->isAvailable())
343 _registeredStorageBackends.emplace_back(std::move(backend));
345 backend->deleteLater();
349 void Core::registerStorageBackends()
351 if (_registeredStorageBackends.empty()) {
352 registerStorageBackend<SqliteStorage>();
353 registerStorageBackend<PostgreSqlStorage>();
358 DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
360 auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
361 [backendId](const DeferredSharedPtr<Storage> &backend) {
362 return backend->displayName() == backendId;
364 return it != _registeredStorageBackends.end() ? *it : nullptr;
368 // "Type" => "sqlite"
369 bool Core::initStorage(const QString &backend, const QVariantMap &settings,
370 const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
372 if (backend.isEmpty()) {
373 quWarning() << "No storage backend selected!";
377 auto storage = storageBackend(backend);
379 qCritical() << "Selected storage backend is not available:" << backend;
383 Storage::State storageState = storage->init(settings, environment, loadFromEnvironment);
384 switch (storageState) {
385 case Storage::NeedsSetup:
387 return false; // trigger setup process
388 if (storage->setup(settings, environment, loadFromEnvironment))
389 return initStorage(backend, settings, environment, loadFromEnvironment, false);
392 // if initialization wasn't successful, we quit to keep from coming up unconfigured
393 case Storage::NotAvailable:
394 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
399 case Storage::IsReady:
400 // delete all other backends
401 _registeredStorageBackends.clear();
402 connect(storage.get(), SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)),
403 this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
406 _storage = std::move(storage);
411 void Core::syncStorage()
418 /*** Storage Access ***/
419 bool Core::createNetwork(UserId user, NetworkInfo &info)
421 NetworkId networkId = instance()->_storage->createNetwork(user, info);
422 if (!networkId.isValid())
425 info.networkId = networkId;
430 /*** Authenticators ***/
432 // Authentication handling, now independent from storage.
433 template<typename Authenticator>
434 void Core::registerAuthenticator()
436 auto authenticator = makeDeferredShared<Authenticator>(this);
437 if (authenticator->isAvailable())
438 _registeredAuthenticators.emplace_back(std::move(authenticator));
440 authenticator->deleteLater();
444 void Core::registerAuthenticators()
446 if (_registeredAuthenticators.empty()) {
447 registerAuthenticator<SqlAuthenticator>();
449 registerAuthenticator<LdapAuthenticator>();
455 DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
457 auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
458 [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
459 return authenticator->backendId() == backendId;
461 return it != _registeredAuthenticators.end() ? *it : nullptr;
465 // FIXME: Apparently, this is the legacy way of initting storage backends?
466 // If there's a not-legacy way, it should be used here
467 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
468 const QProcessEnvironment &environment, bool loadFromEnvironment,
471 if (backend.isEmpty()) {
472 quWarning() << "No authenticator selected!";
476 auto auth = authenticator(backend);
478 qCritical() << "Selected auth backend is not available:" << backend;
482 Authenticator::State authState = auth->init(settings, environment, loadFromEnvironment);
484 case Authenticator::NeedsSetup:
486 return false; // trigger setup process
487 if (auth->setup(settings, environment, loadFromEnvironment))
488 return initAuthenticator(backend, settings, environment, loadFromEnvironment, false);
491 // if initialization wasn't successful, we quit to keep from coming up unconfigured
492 case Authenticator::NotAvailable:
493 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
498 case Authenticator::IsReady:
499 // delete all other backends
500 _registeredAuthenticators.clear();
503 _authenticator = std::move(auth);
508 /*** Network Management ***/
510 bool Core::sslSupported()
513 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
514 return sslServer && sslServer->isCertValid();
521 bool Core::reloadCerts()
524 SslServer *sslServerv4 = qobject_cast<SslServer *>(&_server);
525 bool retv4 = sslServerv4->reloadCerts();
527 SslServer *sslServerv6 = qobject_cast<SslServer *>(&_v6server);
528 bool retv6 = sslServerv6->reloadCerts();
530 return retv4 && retv6;
532 // SSL not supported, don't mark configuration reload as failed
538 void Core::cacheSysIdent()
540 if (isConfigured()) {
541 _authUserNames = _storage->getAllAuthUserNames();
546 QString Core::strictSysIdent(UserId user) const
548 if (_authUserNames.contains(user)) {
549 return _authUserNames[user];
552 // A new user got added since we last pulled our cache from the database.
553 // There's no way to avoid a database hit - we don't even know the authname!
554 instance()->cacheSysIdent();
556 if (_authUserNames.contains(user)) {
557 return _authUserNames[user];
560 // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
561 qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
562 return "unknown"; // Should we just terminate the program instead?
566 bool Core::startListening()
568 // in mono mode we only start a local port if a port is specified in the cli call
569 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
572 bool success = false;
573 uint port = Quassel::optionValue("port").toUInt();
575 const QString listen = Quassel::optionValue("listen");
576 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
577 if (listen_list.size() > 0) {
578 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
580 if (!addr.setAddress(listen_term)) {
581 qCritical() << qPrintable(
582 tr("Invalid listen address %1")
587 switch (addr.protocol()) {
588 case QAbstractSocket::IPv6Protocol:
589 if (_v6server.listen(addr, port)) {
590 quInfo() << qPrintable(
591 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
592 .arg(addr.toString())
593 .arg(_v6server.serverPort())
594 .arg(Quassel::buildInfo().protocolVersion)
599 quWarning() << qPrintable(
600 tr("Could not open IPv6 interface %1:%2: %3")
601 .arg(addr.toString())
603 .arg(_v6server.errorString()));
605 case QAbstractSocket::IPv4Protocol:
606 if (_server.listen(addr, port)) {
607 quInfo() << qPrintable(
608 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
609 .arg(addr.toString())
610 .arg(_server.serverPort())
611 .arg(Quassel::buildInfo().protocolVersion)
616 // if v6 succeeded on Any, the port will be already in use - don't display the error then
617 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
618 quWarning() << qPrintable(
619 tr("Could not open IPv4 interface %1:%2: %3")
620 .arg(addr.toString())
622 .arg(_server.errorString()));
626 qCritical() << qPrintable(
627 tr("Invalid listen address %1, unknown network protocol")
636 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
642 void Core::stopListening(const QString &reason)
644 bool wasListening = false;
645 if (_server.isListening()) {
649 if (_v6server.isListening()) {
654 if (reason.isEmpty())
655 quInfo() << "No longer listening for GUI clients.";
657 quInfo() << qPrintable(reason);
662 void Core::incomingConnection()
664 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
666 while (server->hasPendingConnections()) {
667 QTcpSocket *socket = server->nextPendingConnection();
669 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
670 _connectingClients.insert(handler);
672 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
673 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
674 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
676 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
679 stopListening(tr("Closing server for basic setup."));
685 // Potentially called during the initialization phase (before handing the connection off to the session)
686 void Core::clientDisconnected()
688 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
691 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
692 _connectingClients.remove(handler);
693 handler->deleteLater();
695 // make server listen again if still not configured
700 // TODO remove unneeded sessions - if necessary/possible...
701 // Suggestion: kill sessions if they are not connected to any network and client.
705 void Core::setupClientSession(RemotePeer *peer, UserId uid)
707 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
710 // From now on everything is handled by the client session
711 disconnect(handler, 0, this, 0);
712 _connectingClients.remove(handler);
713 handler->deleteLater();
715 // Find or create session for validated user
718 // as we are currently handling an event triggered by incoming data on this socket
719 // it is unsafe to directly move the socket to the client thread.
720 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
724 void Core::customEvent(QEvent *event)
726 if (event->type() == AddClientEventId) {
727 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
728 addClientHelper(addClientEvent->peer, addClientEvent->userId);
734 void Core::addClientHelper(RemotePeer *peer, UserId uid)
736 // Find or create session for validated user
737 SessionThread *session = sessionForUser(uid);
738 session->addClient(peer);
742 void Core::setupInternalClientSession(InternalPeer *clientPeer)
746 setupCoreForInternalUsage();
751 uid = _storage->internalUser();
754 quWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
758 InternalPeer *corePeer = new InternalPeer(this);
759 corePeer->setPeer(clientPeer);
760 clientPeer->setPeer(corePeer);
762 // Find or create session for validated user
763 SessionThread *sessionThread = sessionForUser(uid);
764 sessionThread->addClient(corePeer);
768 SessionThread *Core::sessionForUser(UserId uid, bool restore)
770 if (_sessions.contains(uid))
771 return _sessions[uid];
773 SessionThread *session = new SessionThread(uid, restore, strictIdentEnabled(), this);
774 _sessions[uid] = session;
780 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
782 quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
786 QVariantList Core::backendInfo()
788 instance()->registerStorageBackends();
790 QVariantList backendInfos;
791 for (auto &&backend : instance()->_registeredStorageBackends) {
793 v["BackendId"] = backend->backendId();
794 v["DisplayName"] = backend->displayName();
795 v["Description"] = backend->description();
796 v["SetupData"] = backend->setupData(); // ignored by legacy clients
798 // TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
799 const auto &setupData = backend->setupData();
800 QStringList setupKeys;
801 QVariantMap setupDefaults;
802 for (int i = 0; i + 2 < setupData.size(); i += 3) {
803 setupKeys << setupData[i].toString();
804 setupDefaults[setupData[i].toString()] = setupData[i + 2];
806 v["SetupKeys"] = setupKeys;
807 v["SetupDefaults"] = setupDefaults;
808 // TODO Protocol Break: Remove
809 v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
817 QVariantList Core::authenticatorInfo()
819 instance()->registerAuthenticators();
821 QVariantList authInfos;
822 for(auto &&backend : instance()->_registeredAuthenticators) {
824 v["BackendId"] = backend->backendId();
825 v["DisplayName"] = backend->displayName();
826 v["Description"] = backend->description();
827 v["SetupData"] = backend->setupData();
833 // migration / backend selection
834 bool Core::selectBackend(const QString &backend)
836 // reregister all storage backends
837 registerStorageBackends();
838 auto storage = storageBackend(backend);
840 QStringList backends;
841 std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
842 std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
843 return backend->displayName();
845 quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
846 quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
850 QVariantMap settings = promptForSettings(storage.get());
852 Storage::State storageState = storage->init(settings);
853 switch (storageState) {
854 case Storage::IsReady:
855 if (!saveBackendSettings(backend, settings)) {
856 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
858 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
859 quWarning() << qPrintable(tr("Backend already initialized. Skipping Migration..."));
861 case Storage::NotAvailable:
862 qCritical() << qPrintable(tr("Storage backend is not available: %1").arg(backend));
864 case Storage::NeedsSetup:
865 if (!storage->setup(settings)) {
866 quWarning() << qPrintable(tr("Unable to setup storage backend: %1").arg(backend));
870 if (storage->init(settings) != Storage::IsReady) {
871 quWarning() << qPrintable(tr("Unable to initialize storage backend: %1").arg(backend));
875 if (!saveBackendSettings(backend, settings)) {
876 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
878 quWarning() << qPrintable(tr("Switched storage backend to: %1").arg(backend));
882 // let's see if we have a current storage object we can migrate from
883 auto reader = getMigrationReader(_storage.get());
884 auto writer = getMigrationWriter(storage.get());
885 if (reader && writer) {
886 qDebug() << qPrintable(tr("Migrating storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
889 if (reader->migrateTo(writer.get())) {
890 qDebug() << "Migration finished!";
891 qDebug() << qPrintable(tr("Migration finished!"));
892 if (!saveBackendSettings(backend, settings)) {
893 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
898 quWarning() << qPrintable(tr("Unable to migrate storage backend! (No migration writer for %1)").arg(backend));
902 // inform the user why we cannot merge
904 quWarning() << qPrintable(tr("No currently active storage backend. Skipping migration..."));
907 quWarning() << qPrintable(tr("Currently active storage backend does not support migration: %1").arg(_storage->displayName()));
910 quWarning() << qPrintable(tr("New storage backend does not support migration: %1").arg(backend));
913 // so we were unable to merge, but let's create a user \o/
914 _storage = std::move(storage);
919 // TODO: I am not sure if this function is implemented correctly.
920 // There is currently no concept of migraiton between auth backends.
921 bool Core::selectAuthenticator(const QString &backend)
923 // Register all authentication backends.
924 registerAuthenticators();
925 auto auther = authenticator(backend);
927 QStringList authenticators;
928 std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
929 std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
930 return authenticator->displayName();
932 quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
933 quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
937 QVariantMap settings = promptForSettings(auther.get());
939 Authenticator::State state = auther->init(settings);
941 case Authenticator::IsReady:
942 saveAuthenticatorSettings(backend, settings);
943 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
945 case Authenticator::NotAvailable:
946 qCritical() << qPrintable(tr("Authenticator is not available: %1").arg(backend));
948 case Authenticator::NeedsSetup:
949 if (!auther->setup(settings)) {
950 quWarning() << qPrintable(tr("Unable to setup authenticator: %1").arg(backend));
954 if (auther->init(settings) != Authenticator::IsReady) {
955 quWarning() << qPrintable(tr("Unable to initialize authenticator: %1").arg(backend));
959 saveAuthenticatorSettings(backend, settings);
960 quWarning() << qPrintable(tr("Switched authenticator to: %1").arg(backend));
963 _authenticator = std::move(auther);
968 bool Core::createUser()
970 QTextStream out(stdout);
971 QTextStream in(stdin);
972 out << "Add a new user:" << endl;
975 QString username = in.readLine().trimmed();
980 QString password = in.readLine().trimmed();
982 out << "Repeat Password: ";
984 QString password2 = in.readLine().trimmed();
988 if (password != password2) {
989 quWarning() << "Passwords don't match!";
992 if (password.isEmpty()) {
993 quWarning() << "Password is empty!";
997 if (_configured && _storage->addUser(username, password).isValid()) {
998 out << "Added user " << username << " successfully!" << endl;
1002 quWarning() << "Unable to add user:" << qPrintable(username);
1008 bool Core::changeUserPass(const QString &username)
1010 QTextStream out(stdout);
1011 QTextStream in(stdin);
1012 UserId userId = _storage->getUserId(username);
1013 if (!userId.isValid()) {
1014 out << "User " << username << " does not exist." << endl;
1018 if (!canChangeUserPassword(userId)) {
1019 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
1023 out << "Change password for user: " << username << endl;
1026 out << "New Password: ";
1028 QString password = in.readLine().trimmed();
1030 out << "Repeat Password: ";
1032 QString password2 = in.readLine().trimmed();
1036 if (password != password2) {
1037 quWarning() << "Passwords don't match!";
1040 if (password.isEmpty()) {
1041 quWarning() << "Password is empty!";
1045 if (_configured && _storage->updateUser(userId, password)) {
1046 out << "Password changed successfully!" << endl;
1050 quWarning() << "Failed to change password!";
1056 bool Core::changeUserPassword(UserId userId, const QString &password)
1058 if (!isConfigured() || !userId.isValid())
1061 if (!canChangeUserPassword(userId))
1064 return instance()->_storage->updateUser(userId, password);
1067 // TODO: this code isn't currently 100% optimal because the core
1068 // doesn't know it can have multiple auth providers configured (there aren't
1069 // multiple auth providers at the moment anyway) and we have hardcoded the
1070 // Database provider to be always allowed.
1071 bool Core::canChangeUserPassword(UserId userId)
1073 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
1074 if (authProvider != "Database") {
1075 if (authProvider != instance()->_authenticator->backendId()) {
1078 else if (instance()->_authenticator->canChangePassword()) {
1086 std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
1091 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1093 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1097 return sqlStorage->createMigrationReader();
1101 std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
1106 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1108 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1112 return sqlStorage->createMigrationWriter();
1116 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1118 QVariantMap dbsettings;
1119 dbsettings["Backend"] = backend;
1120 dbsettings["ConnectionProperties"] = settings;
1121 CoreSettings s = CoreSettings();
1122 s.setStorageSettings(dbsettings);
1127 void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
1129 QVariantMap dbsettings;
1130 dbsettings["Authenticator"] = backend;
1131 dbsettings["AuthProperties"] = settings;
1132 CoreSettings().setAuthSettings(dbsettings);
1135 // Generic version of promptForSettings that doesn't care what *type* of
1136 // backend it runs over.
1137 template<typename Backend>
1138 QVariantMap Core::promptForSettings(const Backend *backend)
1140 QVariantMap settings;
1141 const QVariantList& setupData = backend->setupData();
1143 if (setupData.isEmpty())
1146 QTextStream out(stdout);
1147 QTextStream in(stdin);
1148 out << "Default values are in brackets" << endl;
1150 for (int i = 0; i + 2 < setupData.size(); i += 3) {
1151 QString key = setupData[i].toString();
1152 out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
1154 bool noEcho = key.toLower().contains("password");
1158 QString input = in.readLine().trimmed();
1164 QVariant value{setupData[i+2]};
1165 if (!input.isEmpty()) {
1166 switch (value.type()) {
1168 value = input.toInt();
1174 settings[key] = value;
1181 void Core::stdInEcho(bool on)
1183 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1185 GetConsoleMode(hStdin, &mode);
1187 mode |= ENABLE_ECHO_INPUT;
1189 mode &= ~ENABLE_ECHO_INPUT;
1190 SetConsoleMode(hStdin, mode);
1194 void Core::stdInEcho(bool on)
1197 tcgetattr(STDIN_FILENO, &t);
1202 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1205 #endif /* Q_OS_WIN */