1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 ***************************************************************************/
21 #include <QCoreApplication>
24 #include "coreauthhandler.h"
25 #include "coresession.h"
26 #include "coresettings.h"
28 #include "internalpeer.h"
30 #include "postgresqlstorage.h"
32 #include "sqlauthenticator.h"
33 #include "sqlitestorage.h"
36 // Currently building with LDAP bindings is optional.
38 #include "ldapauthenticator.h"
51 # include <sys/types.h>
52 # include <sys/stat.h>
53 #endif /* HAVE_UMASK */
55 // ==============================
57 // ==============================
58 const int Core::AddClientEventId = QEvent::registerEventType();
60 class AddClientEvent : public QEvent
63 AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
69 // ==============================
71 // ==============================
72 Core *Core::instanceptr = 0;
74 Core *Core::instance()
76 if (instanceptr) return instanceptr;
77 instanceptr = new Core();
96 umask(S_IRWXG | S_IRWXO);
98 _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
100 Quassel::loadTranslation(QLocale::system());
102 // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
103 // Move settings, note this does not delete the old files
105 QSettings newSettings("quassel-irc.org", "quasselcore");
109 QSettings::Format format = QSettings::IniFormat;
111 QSettings::Format format = QSettings::NativeFormat;
113 QString newFilePath = Quassel::configDirPath() + "quasselcore"
114 + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
115 QSettings newSettings(newFilePath, format);
116 #endif /* Q_OS_MAC */
118 if (newSettings.value("Config/Version").toUInt() == 0) {
120 QString org = "quassel-irc.org";
122 QString org = "Quassel Project";
124 QSettings oldSettings(org, "Quassel Core");
125 if (oldSettings.allKeys().count()) {
126 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
127 foreach(QString key, oldSettings.allKeys())
128 newSettings.setValue(key, oldSettings.value(key));
129 newSettings.setValue("Config/Version", 1);
130 qWarning() << "* Your core settings have been migrated to" << newSettings.fileName();
132 #ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */
134 QString quasselDir = qgetenv("APPDATA") + "/quassel/";
135 #elif defined Q_OS_MAC
136 QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
138 QString quasselDir = QDir::homePath() + "/.quassel/";
141 QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
142 if (!info.exists()) {
143 // move database, if we found it
144 QFile oldDb(quasselDir + "quassel-storage.sqlite");
145 if (oldDb.exists()) {
146 bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
148 qWarning() << "* Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
150 qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
154 QFileInfo certInfo(quasselDir + "quasselCert.pem");
155 if (certInfo.exists()) {
156 QFile cert(quasselDir + "quasselCert.pem");
157 bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
159 qWarning() << "* Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
161 qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
163 #endif /* !Q_OS_MAC */
164 qWarning() << "*** Migration completed.\n\n";
169 // check settings version
170 // so far, we only have 1
172 if (s.version() != 1) {
173 qCritical() << "Invalid core settings version, terminating!";
177 registerStorageBackends();
178 registerAuthenticatorBackends();
180 connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
181 _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
189 QVariantMap dbsettings = cs.storageSettings().toMap();
190 _configured = initStorage(dbsettings.value("Backend").toString(), dbsettings.value("ConnectionProperties").toMap());
192 // Not entirely sure what is 'legacy' about the above, but it seems to be the way things work!
193 QVariantMap authSettings = cs.authSettings().toMap();
194 initAuthenticator(authSettings.value("AuthBackend").toString(), authSettings.value("ConnectionProperties").toMap());
196 if (Quassel::isOptionSet("select-backend")) {
197 selectBackend(Quassel::optionValue("select-backend"));
201 // TODO: add --select-authenticator command line option and code.
204 if (!_storageBackends.count()) {
205 qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
206 qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
207 "Qt library with the sqlite or postgres plugin enabled in order for quasselcore\n"
209 exit(1); // TODO make this less brutal (especially for mono client -> popup)
212 qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
214 if (!cs.isWritable()) {
215 qWarning() << "Cannot write quasselcore configuration; probably a permission problem.";
221 if (Quassel::isOptionSet("add-user")) {
222 exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
226 if (Quassel::isOptionSet("change-userpass")) {
227 exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
228 EXIT_SUCCESS : EXIT_FAILURE);
231 connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
232 connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
233 if (!startListening()) exit(1); // TODO make this less brutal
235 if (Quassel::isOptionSet("oidentd"))
236 _oidentdConfigGenerator = new OidentdConfigGenerator(this);
242 // FIXME do we need more cleanup for handlers?
243 foreach(CoreAuthHandler *handler, _connectingClients) {
244 handler->deleteLater(); // disconnect non authed clients
246 qDeleteAll(_sessions);
247 qDeleteAll(_storageBackends);
248 qDeleteAll(_authenticatorBackends);
252 /*** Session Restore ***/
254 void Core::saveState()
258 QVariantList activeSessions;
259 foreach(UserId user, instance()->_sessions.keys())
260 activeSessions << QVariant::fromValue<UserId>(user);
261 state["CoreStateVersion"] = 1;
262 state["ActiveSessions"] = activeSessions;
263 s.setCoreState(state);
267 void Core::restoreState()
269 if (!instance()->_configured) {
270 // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
273 if (instance()->_sessions.count()) {
274 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
278 /* We don't check, since we are at the first version since switching to Git
279 uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
281 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
286 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
287 if (activeSessions.count() > 0) {
288 quInfo() << "Restoring previous core state...";
289 foreach(QVariant v, activeSessions) {
290 UserId user = v.value<UserId>();
291 instance()->sessionForUser(user, true);
299 QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupData)
301 return instance()->setupCore(adminUser, adminPassword, backend, setupData, authBackend, authSetupData);
305 QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupData)
308 return tr("Core is already configured! Not configuring again...");
310 if (adminUser.isEmpty() || adminPassword.isEmpty()) {
311 return tr("Admin user or password not set.");
313 if (!(_configured = initStorage(backend, setupData, true))) {
314 return tr("Could not setup storage!");
317 quInfo() << "Selected authenticator: " << authBackend;
318 if (!(_configured = initAuthenticator(authBackend, authSetupData, true)))
320 return tr("Could not setup authenticator!");
323 if (!saveBackendSettings(backend, setupData)) {
324 return tr("Could not save backend settings, probably a permission problem.");
326 saveAuthBackendSettings(authBackend, authSetupData);
328 quInfo() << qPrintable(tr("Creating admin user..."));
329 _storage->addUser(adminUser, adminPassword);
330 startListening(); // TODO check when we need this
335 QString Core::setupCoreForInternalUsage()
337 Q_ASSERT(!_storageBackends.isEmpty());
339 qsrand(QDateTime::currentDateTime().toTime_t());
341 for (int i = 0; i < 10; i++) {
343 pass += qrand() % 10;
346 // mono client currently needs sqlite
347 return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "StorageAuth", QVariantMap());
351 /*** Storage Handling ***/
352 void Core::registerStorageBackends()
354 // Register storage backends here!
355 registerStorageBackend(new SqliteStorage(this));
356 registerStorageBackend(new PostgreSqlStorage(this));
360 bool Core::registerStorageBackend(Storage *backend)
362 if (backend->isAvailable()) {
363 _storageBackends[backend->displayName()] = backend;
367 backend->deleteLater();
372 void Core::unregisterStorageBackends()
374 foreach(Storage *s, _storageBackends.values()) {
377 _storageBackends.clear();
381 void Core::unregisterStorageBackend(Storage *backend)
383 _storageBackends.remove(backend->displayName());
384 backend->deleteLater();
387 // Authentication handling, now independent from storage.
388 // Register and unregister authenticators.
390 void Core::registerAuthenticatorBackends()
392 // Register new authentication backends here!
393 registerAuthenticatorBackend(new SqlAuthenticator(this));
395 registerAuthenticatorBackend(new LdapAuthenticator(this));
400 bool Core::registerAuthenticatorBackend(Authenticator *authenticator)
402 if (authenticator->isAvailable())
404 _authenticatorBackends[authenticator->displayName()] = authenticator;
407 authenticator->deleteLater();
412 void Core::unregisterAuthenticatorBackends()
414 foreach(Authenticator* a, _authenticatorBackends.values())
418 _authenticatorBackends.clear();
421 void Core::unregisterAuthenticatorBackend(Authenticator *backend)
423 _authenticatorBackends.remove(backend->displayName());
424 backend->deleteLater();
428 // "Type" => "sqlite"
429 bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool setup)
433 if (backend.isEmpty()) {
437 Storage *storage = 0;
438 if (_storageBackends.contains(backend)) {
439 storage = _storageBackends[backend];
442 qCritical() << "Selected storage backend is not available:" << backend;
446 Storage::State storageState = storage->init(settings);
447 switch (storageState) {
448 case Storage::NeedsSetup:
450 return false; // trigger setup process
451 if (storage->setup(settings))
452 return initStorage(backend, settings, false);
453 // if initialization wasn't successful, we quit to keep from coming up unconfigured
454 case Storage::NotAvailable:
455 qCritical() << "FATAL: Selected storage backend is not available:" << backend;
457 case Storage::IsReady:
458 // delete all other backends
459 _storageBackends.remove(backend);
460 unregisterStorageBackends();
461 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
467 // XXX: TODO: Apparently, this is legacy?
468 bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup)
472 if (backend.isEmpty()) {
476 Authenticator *authenticator = 0;
477 if (_authenticatorBackends.contains(backend)) {
478 authenticator = _authenticatorBackends[backend];
481 qCritical() << "Selected auth backend is not available:" << backend;
485 Authenticator::State authState = authenticator->init(settings);
487 case Authenticator::NeedsSetup:
489 return false; // trigger setup process
490 if (authenticator->setup(settings))
491 return initAuthenticator(backend, settings, false);
492 // if initialization wasn't successful, we quit to keep from coming up unconfigured
493 case Authenticator::NotAvailable:
494 qCritical() << "FATAL: Selected auth backend is not available:" << backend;
496 case Authenticator::IsReady:
497 // delete all other backends
498 _authenticatorBackends.remove(backend);
499 unregisterAuthenticatorBackends();
501 _authenticator = authenticator;
505 void Core::syncStorage()
512 /*** Storage Access ***/
513 bool Core::createNetwork(UserId user, NetworkInfo &info)
515 NetworkId networkId = instance()->_storage->createNetwork(user, info);
516 if (!networkId.isValid())
519 info.networkId = networkId;
524 /*** Network Management ***/
526 bool Core::sslSupported()
529 SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
530 return sslServer && sslServer->isCertValid();
537 bool Core::reloadCerts()
540 SslServer *sslServerv4 = qobject_cast<SslServer *>(&instance()->_server);
541 bool retv4 = sslServerv4->reloadCerts();
543 SslServer *sslServerv6 = qobject_cast<SslServer *>(&instance()->_v6server);
544 bool retv6 = sslServerv6->reloadCerts();
546 return retv4 && retv6;
548 // SSL not supported, don't mark configuration reload as failed
554 bool Core::startListening()
556 // in mono mode we only start a local port if a port is specified in the cli call
557 if (Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
560 bool success = false;
561 uint port = Quassel::optionValue("port").toUInt();
563 const QString listen = Quassel::optionValue("listen");
564 const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
565 if (listen_list.size() > 0) {
566 foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
568 if (!addr.setAddress(listen_term)) {
569 qCritical() << qPrintable(
570 tr("Invalid listen address %1")
575 switch (addr.protocol()) {
576 case QAbstractSocket::IPv6Protocol:
577 if (_v6server.listen(addr, port)) {
578 quInfo() << qPrintable(
579 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
580 .arg(addr.toString())
581 .arg(_v6server.serverPort())
582 .arg(Quassel::buildInfo().protocolVersion)
587 quWarning() << qPrintable(
588 tr("Could not open IPv6 interface %1:%2: %3")
589 .arg(addr.toString())
591 .arg(_v6server.errorString()));
593 case QAbstractSocket::IPv4Protocol:
594 if (_server.listen(addr, port)) {
595 quInfo() << qPrintable(
596 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
597 .arg(addr.toString())
598 .arg(_server.serverPort())
599 .arg(Quassel::buildInfo().protocolVersion)
604 // if v6 succeeded on Any, the port will be already in use - don't display the error then
605 if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
606 quWarning() << qPrintable(
607 tr("Could not open IPv4 interface %1:%2: %3")
608 .arg(addr.toString())
610 .arg(_server.errorString()));
614 qCritical() << qPrintable(
615 tr("Invalid listen address %1, unknown network protocol")
624 quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
630 void Core::stopListening(const QString &reason)
632 bool wasListening = false;
633 if (_server.isListening()) {
637 if (_v6server.isListening()) {
642 if (reason.isEmpty())
643 quInfo() << "No longer listening for GUI clients.";
645 quInfo() << qPrintable(reason);
650 void Core::incomingConnection()
652 QTcpServer *server = qobject_cast<QTcpServer *>(sender());
654 while (server->hasPendingConnections()) {
655 QTcpSocket *socket = server->nextPendingConnection();
657 CoreAuthHandler *handler = new CoreAuthHandler(socket, this);
658 _connectingClients.insert(handler);
660 connect(handler, SIGNAL(disconnected()), SLOT(clientDisconnected()));
661 connect(handler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(socketError(QAbstractSocket::SocketError,QString)));
662 connect(handler, SIGNAL(handshakeComplete(RemotePeer*,UserId)), SLOT(setupClientSession(RemotePeer*,UserId)));
664 quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
667 stopListening(tr("Closing server for basic setup."));
673 // Potentially called during the initialization phase (before handing the connection off to the session)
674 void Core::clientDisconnected()
676 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
679 quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
680 _connectingClients.remove(handler);
681 handler->deleteLater();
683 // make server listen again if still not configured
688 // TODO remove unneeded sessions - if necessary/possible...
689 // Suggestion: kill sessions if they are not connected to any network and client.
693 void Core::setupClientSession(RemotePeer *peer, UserId uid)
695 CoreAuthHandler *handler = qobject_cast<CoreAuthHandler *>(sender());
698 // From now on everything is handled by the client session
699 disconnect(handler, 0, this, 0);
700 _connectingClients.remove(handler);
701 handler->deleteLater();
703 // Find or create session for validated user
706 // as we are currently handling an event triggered by incoming data on this socket
707 // it is unsafe to directly move the socket to the client thread.
708 QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
712 void Core::customEvent(QEvent *event)
714 if (event->type() == AddClientEventId) {
715 AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
716 addClientHelper(addClientEvent->peer, addClientEvent->userId);
722 void Core::addClientHelper(RemotePeer *peer, UserId uid)
724 // Find or create session for validated user
725 SessionThread *session = sessionForUser(uid);
726 session->addClient(peer);
730 void Core::setupInternalClientSession(InternalPeer *clientPeer)
734 setupCoreForInternalUsage();
739 uid = _storage->internalUser();
742 qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
746 InternalPeer *corePeer = new InternalPeer(this);
747 corePeer->setPeer(clientPeer);
748 clientPeer->setPeer(corePeer);
750 // Find or create session for validated user
751 SessionThread *sessionThread = sessionForUser(uid);
752 sessionThread->addClient(corePeer);
756 SessionThread *Core::sessionForUser(UserId uid, bool restore)
758 if (_sessions.contains(uid))
759 return _sessions[uid];
761 SessionThread *session = new SessionThread(uid, restore, this);
762 _sessions[uid] = session;
768 void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
770 qWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
774 QVariantList Core::backendInfo()
776 QVariantList backends;
777 foreach(const Storage *backend, instance()->_storageBackends.values()) {
779 v["DisplayName"] = backend->displayName();
780 v["Description"] = backend->description();
781 v["SetupKeys"] = backend->setupKeys();
782 v["SetupDefaults"] = backend->setupDefaults();
783 v["IsDefault"] = isStorageBackendDefault(backend);
789 QVariantList Core::authenticatorInfo()
791 QVariantList backends;
792 foreach(const Authenticator *backend, instance()->_authenticatorBackends.values()) {
794 v["DisplayName"] = backend->displayName();
795 v["Description"] = backend->description();
796 v["SetupKeys"] = backend->setupKeys();
797 v["SetupDefaults"] = backend->setupDefaults();
803 // migration / backend selection
804 bool Core::selectBackend(const QString &backend)
806 // reregister all storage backends
807 registerStorageBackends();
808 if (!_storageBackends.contains(backend)) {
809 qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
810 qWarning() << " supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
814 Storage *storage = _storageBackends[backend];
815 QVariantMap settings = promptForSettings(storage);
817 Storage::State storageState = storage->init(settings);
818 switch (storageState) {
819 case Storage::IsReady:
820 if (!saveBackendSettings(backend, settings)) {
821 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
823 qWarning() << "Switched backend to:" << qPrintable(backend);
824 qWarning() << "Backend already initialized. Skipping Migration";
826 case Storage::NotAvailable:
827 qCritical() << "Backend is not available:" << qPrintable(backend);
829 case Storage::NeedsSetup:
830 if (!storage->setup(settings)) {
831 qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
835 if (storage->init(settings) != Storage::IsReady) {
836 qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
840 if (!saveBackendSettings(backend, settings)) {
841 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
843 qWarning() << "Switched backend to:" << qPrintable(backend);
847 // let's see if we have a current storage object we can migrate from
848 AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
849 AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
850 if (reader && writer) {
851 qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
856 if (reader->migrateTo(writer)) {
857 qDebug() << "Migration finished!";
858 if (!saveBackendSettings(backend, settings)) {
859 qCritical() << qPrintable(QString("Could not save backend settings, probably a permission problem."));
865 qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
868 // inform the user why we cannot merge
870 qWarning() << "No currently active backend. Skipping migration.";
873 qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
876 qWarning() << "New backend does not support migration:" << qPrintable(backend);
879 // so we were unable to merge, but let's create a user \o/
886 bool Core::createUser()
888 QTextStream out(stdout);
889 QTextStream in(stdin);
890 out << "Add a new user:" << endl;
893 QString username = in.readLine().trimmed();
898 QString password = in.readLine().trimmed();
900 out << "Repeat Password: ";
902 QString password2 = in.readLine().trimmed();
906 if (password != password2) {
907 qWarning() << "Passwords don't match!";
910 if (password.isEmpty()) {
911 qWarning() << "Password is empty!";
915 if (_configured && _storage->addUser(username, password).isValid()) {
916 out << "Added user " << username << " successfully!" << endl;
920 qWarning() << "Unable to add user:" << qPrintable(username);
926 bool Core::changeUserPass(const QString &username)
928 QTextStream out(stdout);
929 QTextStream in(stdin);
930 UserId userId = _storage->getUserId(username);
931 if (!userId.isValid()) {
932 out << "User " << username << " does not exist." << endl;
936 if (!canChangeUserPassword(userId))
938 out << "User " << username << " is configured through an auth provider that has forbidden manual password changing." << endl;
942 out << "Change password for user: " << username << endl;
945 out << "New Password: ";
947 QString password = in.readLine().trimmed();
949 out << "Repeat Password: ";
951 QString password2 = in.readLine().trimmed();
955 if (password != password2) {
956 qWarning() << "Passwords don't match!";
959 if (password.isEmpty()) {
960 qWarning() << "Password is empty!";
964 if (_configured && _storage->updateUser(userId, password)) {
965 out << "Password changed successfully!" << endl;
969 qWarning() << "Failed to change password!";
975 bool Core::changeUserPassword(UserId userId, const QString &password)
977 if (!isConfigured() || !userId.isValid())
980 if (!canChangeUserPassword(userId))
983 return instance()->_storage->updateUser(userId, password);
986 // XXX: this code isn't currently 100% optimal because the core
987 // doesn't know it can have multiple auth providers configured (there aren't
988 // multiple auth providers at the moment anyway) and we have hardcoded the
989 // Database provider to be always allowed.
990 bool Core::canChangeUserPassword(UserId userId)
992 QString authProvider = instance()->_storage->getUserAuthenticator(userId);
993 if (authProvider != "Database")
995 if (authProvider != instance()->_authenticator->displayName()) {
997 } else if (instance()->_authenticator->canChangePassword()) {
1004 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
1009 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1011 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1015 return sqlStorage->createMigrationReader();
1019 AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage)
1024 AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
1026 qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
1030 return sqlStorage->createMigrationWriter();
1034 bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
1036 QVariantMap dbsettings;
1037 dbsettings["Backend"] = backend;
1038 dbsettings["ConnectionProperties"] = settings;
1039 CoreSettings s = CoreSettings();
1040 s.setStorageSettings(dbsettings);
1044 void Core::saveAuthBackendSettings(const QString &backend, const QVariantMap &settings)
1046 QVariantMap dbsettings;
1047 dbsettings["AuthBackend"] = backend;
1048 dbsettings["ConnectionProperties"] = settings;
1049 CoreSettings().setAuthSettings(dbsettings);
1053 QVariantMap Core::promptForSettings(const Storage *storage)
1055 QVariantMap settings;
1057 QStringList keys = storage->setupKeys();
1061 QTextStream out(stdout);
1062 QTextStream in(stdin);
1063 out << "Default values are in brackets" << endl;
1065 QVariantMap defaults = storage->setupDefaults();
1067 foreach(QString key, keys) {
1069 if (defaults.contains(key)) {
1070 val = defaults[key];
1073 if (!val.toString().isEmpty()) {
1074 out << " (" << val.toString() << ")";
1079 bool noEcho = QString("password").toLower().startsWith(key.toLower());
1083 value = in.readLine().trimmed();
1089 if (!value.isEmpty()) {
1090 switch (defaults[key].type()) {
1092 val = QVariant(value.toInt());
1095 val = QVariant(value);
1098 settings[key] = val;
1105 void Core::stdInEcho(bool on)
1107 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
1109 GetConsoleMode(hStdin, &mode);
1111 mode |= ENABLE_ECHO_INPUT;
1113 mode &= ~ENABLE_ECHO_INPUT;
1114 SetConsoleMode(hStdin, mode);
1119 void Core::stdInEcho(bool on)
1122 tcgetattr(STDIN_FILENO, &t);
1127 tcsetattr(STDIN_FILENO, TCSANOW, &t);
1131 #endif /* Q_OS_WIN */