17#include <QCoreApplication>
19#include <QDomDocument>
24#include <QMutexLocker>
26#include <QRandomGenerator>
27#include <QRegularExpression>
29#include <QSqlDatabase>
39using namespace Qt::StringLiterals;
46#include <QSslConfiguration>
61#include "moc_qgsauthmanager.cpp"
72const QString QgsAuthManager::AUTH_CONFIG_TABLE = u
"auth_configs"_s;
73const QString QgsAuthManager::AUTH_SERVERS_TABLE = u
"auth_servers"_s;
75const QString QgsAuthManager::AUTH_CFG_REGEX = u
"authcfg=([a-z]|[A-Z]|[0-9]){7}"_s;
78const QLatin1String QgsAuthManager::AUTH_PASSWORD_HELPER_KEY_NAME_BASE(
"QGIS-Master-Password" );
79const QLatin1String QgsAuthManager::AUTH_PASSWORD_HELPER_FOLDER_NAME(
"QGIS" );
87#elif defined(Q_OS_WIN)
89#elif defined(Q_OS_LINUX)
100 QMutexLocker locker( &sMutex );
115 mMutex = std::make_unique<QRecursiveMutex>();
116 mMasterPasswordMutex = std::make_unique<QRecursiveMutex>();
118 this, &QgsAuthManager::writeToConsole );
134 QMutexLocker locker( mMutex.get() );
139 return storage->authDatabaseConnection();
144 return QSqlDatabase();
157 const QList<QgsAuthConfigurationStorage *> storages { storageRegistry->
readyStorages() };
160 if (
auto dbStorage = qobject_cast<QgsAuthConfigurationStorageDb *>( storage ) )
164 return dbStorage->quotedQualifiedIdentifier( dbStorage->methodConfigTableName() );
181 const auto drivers { QSqlDatabase::drivers() };
182 for (
const QString &driver : std::as_const( drivers ) )
184 if ( driver != ( u
"QSQLITE"_s ) && driver != ( u
"QSPATIALITE"_s ) && uri.startsWith( driver ) )
199 return mAuthDatabaseConnectionUri;
208 QRegularExpression re( u
"password=(.*)"_s );
209 QString uri = mAuthDatabaseConnectionUri;
210 return uri.replace( re, u
"password=*****"_s );
220 mAuthDatabaseConnectionUri = authDatabasePath.startsWith(
"QSQLITE://"_L1 ) ? authDatabasePath : u
"QSQLITE://"_s + authDatabasePath;
221 return initPrivate( pluginPath );
223 Q_UNUSED( pluginPath )
224 Q_UNUSED( authDatabasePath )
232 static QRecursiveMutex sInitializationMutex;
233 static bool sInitialized =
false;
235 sInitializationMutex.lock();
238 sInitializationMutex.unlock();
239 return mLazyInitResult;
242 mLazyInitResult =
const_cast< QgsAuthManager *
>( this )->initPrivate( mPluginPath );
244 sInitializationMutex.unlock();
246 return mLazyInitResult;
252static char *sPassFileEnv =
nullptr;
254bool QgsAuthManager::initPrivate(
const QString &pluginPath )
264 mQcaInitializer = std::make_unique<QCA::Initializer>( QCA::Practical, 256 );
267 QCA::scanForPlugins();
269 QgsDebugMsgLevel( u
"QCA Plugin Diagnostics Context: %1"_s.arg( QCA::pluginDiagnosticText() ), 2 );
270 QStringList capabilities;
272 capabilities = QCA::supportedFeatures();
273 QgsDebugMsgLevel( u
"QCA supports: %1"_s.arg( capabilities.join(
"," ) ), 2 );
276 if ( !QCA::isSupported(
"cert", u
"qca-ossl"_s ) )
278 mAuthDisabled =
true;
279 mAuthDisabledMessage = tr(
"QCA's OpenSSL plugin (qca-ossl) is missing" );
283 QgsDebugMsgLevel( u
"Prioritizing qca-ossl over all other QCA providers..."_s, 2 );
284 const QCA::ProviderList provds = QCA::providers();
286 for ( QCA::Provider *p : provds )
288 QString pn = p->name();
290 if ( pn !=
"qca-ossl"_L1 )
292 pr = QCA::providerPriority( pn ) + 1;
294 QCA::setProviderPriority( pn, pr );
295 prlist << u
"%1:%2"_s.arg( pn ).arg( QCA::providerPriority( pn ) );
297 QgsDebugMsgLevel( u
"QCA provider priorities: %1"_s.arg( prlist.join(
", " ) ), 2 );
304 QgsDebugMsgLevel( u
"Authentication methods found: %1"_s.arg( methods.join(
", " ) ), 2 );
306 if ( methods.isEmpty() )
308 mAuthDisabled =
true;
309 mAuthDisabledMessage = tr(
"No authentication method plugins found" );
315 mAuthDisabled =
true;
316 mAuthDisabledMessage = tr(
"No authentication method plugins could be loaded" );
320 QgsDebugMsgLevel( u
"Auth database URI: %1"_s.arg( mAuthDatabaseConnectionUri ), 2 );
324 if ( ! sqliteDbPath.isEmpty() )
328 else if ( ! mAuthDatabaseConnectionUri.isEmpty() )
332 QgsAuthConfigurationStorageDb *storage =
new QgsAuthConfigurationStorageDb( mAuthDatabaseConnectionUri );
342 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
351 const QString err = tr(
"Failed to initialize storage %1: %2" ).arg( storage->
name(), storage->
lastError() );
371 QString passpath( sPassFileEnv );
372 free( sPassFileEnv );
373 sPassFileEnv =
nullptr;
376 QFile passfile( passpath );
377 if ( passfile.exists() && passfile.open( QIODevice::ReadOnly | QIODevice::Text ) )
379 QTextStream passin( &passfile );
380 while ( !passin.atEnd() )
382 masterpass = passin.readLine();
387 if ( !masterpass.isEmpty() )
391 QgsDebugMsgLevel( u
"Authentication master password set from QGIS_AUTH_PASSWORD_FILE"_s, 2 );
395 QgsDebugError(
"QGIS_AUTH_PASSWORD_FILE set, but FAILED to set password using: " + passpath );
401 QgsDebugError(
"QGIS_AUTH_PASSWORD_FILE set, but FAILED to read password from: " + passpath );
412 Q_UNUSED( pluginPath )
420 mPluginPath = pluginPath;
421 mAuthDatabaseConnectionUri = authDatabasePath;
423 const char *p = getenv(
"QGIS_AUTH_PASSWORD_FILE" );
426 sPassFileEnv = qstrdup( p );
431 putenv(
"QGIS_AUTH_PASSWORD_FILE" );
433 unsetenv(
"QGIS_AUTH_PASSWORD_FILE" );
437 Q_UNUSED( pluginPath )
438 Q_UNUSED( authDatabasePath )
442QString QgsAuthManager::generatePassword()
445 QRandomGenerator generator = QRandomGenerator::securelySeeded();
448 static const QString sPwChars = u
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-{}[]"_s;
449 for (
int i = 0; i < pw.size(); ++i )
451 pw[i] = sPwChars.at( generator.bounded( 0, sPwChars.length() ) );
466 QgsDebugError( u
"Authentication system DISABLED: QCA's qca-ossl (OpenSSL) plugin is missing"_s );
468 return mAuthDisabled;
479 return tr(
"Authentication system is DISABLED:\n%1" ).arg( mAuthDisabledMessage );
488 QMutexLocker locker( mMasterPasswordMutex.get() );
492 if ( mScheduledDbErase )
498 if ( !mMasterPass.isEmpty() )
504 const QString newPassword = generatePassword();
505 if ( passwordHelperWrite( newPassword ) )
507 mMasterPass = newPassword;
539 QString path = mAuthDatabaseConnectionUri;
540 if ( path.startsWith( u
"QSQLITE://"_s, Qt::CaseSensitivity::CaseInsensitive ) )
542 path = path.mid( 10 );
544 else if ( path.startsWith( u
"QSPATIALITE://"_s, Qt::CaseSensitivity::CaseInsensitive ) )
546 path = path.mid( 14 );
549 return QDir::cleanPath( path );
569 QMutexLocker locker( mMasterPasswordMutex.get() );
573 if ( mScheduledDbErase )
576 if ( mMasterPass.isEmpty() )
579 if ( !masterPasswordInput() )
608 QMutexLocker locker( mMutex.get() );
612 if ( mScheduledDbErase )
616 QString prevpass = QString( mMasterPass );
620 mMasterPass = prevpass;
621 const char *err = QT_TR_NOOP(
"Master password set: FAILED to verify, reset to previous" );
627 QgsDebugMsgLevel( u
"Master password set: SUCCESS%1"_s.arg( verify ?
" and verified" :
"" ), 2 );
645 if ( !masterPasswordRowsInDb( rows ) )
647 const char *err = QT_TR_NOOP(
"Master password: FAILED to access database" );
655 QgsDebugMsgLevel( u
"Master password: %1 rows in database"_s.arg( rows ), 2 );
659 const char *err = QT_TR_NOOP(
"Master password: FAILED to find just one master password record in database" );
666 else if ( rows == 1 )
668 if ( !masterPasswordCheckAgainstDb( compare ) )
670 if ( compare.isNull() )
672 const char *err = QT_TR_NOOP(
"Master password: FAILED to verify against hash in database" );
681 if ( mPassTries >= 5 )
683 mAuthDisabled =
true;
684 const char *err = QT_TR_NOOP(
"Master password: failed 5 times authentication system DISABLED" );
692 QgsDebugMsgLevel( u
"Master password: verified against hash in database"_s, 2 );
693 if ( compare.isNull() )
697 else if ( compare.isNull() )
699 if ( !masterPasswordStoreInDb() )
701 const char *err = QT_TR_NOOP(
"Master password: hash FAILED to be stored in database" );
713 if ( !masterPasswordCheckAgainstDb() )
715 const char *err = QT_TR_NOOP(
"Master password: FAILED to verify against hash in database" );
725 QgsDebugMsgLevel( u
"Master password: verified against hash in database"_s, 2 );
742 return !mMasterPass.isEmpty();
753 return mMasterPass == pass;
761 bool keepbackup, QString *backuppath )
778 QgsDebugMsgLevel( u
"Master password reset: backed up current database"_s, 2 );
781 QString prevpass = QString( mMasterPass );
782 QString prevciv = QString( masterPasswordCiv() );
788 if ( ok && !masterPasswordClearDb() )
791 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not clear current password from database" );
797 QgsDebugMsgLevel( u
"Master password reset: cleared current password from database"_s, 2 );
804 if ( ok && !masterPasswordStoreInDb() )
807 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not store new password in database" );
813 QgsDebugMsgLevel( u
"Master password reset: stored new password in database"_s, 2 );
820 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not verify new password in database" );
826 if ( ok && !reencryptAllAuthenticationConfigs( prevpass, prevciv ) )
829 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not re-encrypt configs in database" );
835 QgsDebugMsgLevel( u
"Master password reset: re-encrypted configs in database"_s, 2 );
839 if ( ok && !verifyPasswordCanDecryptConfigs() )
842 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not verify password can decrypt re-encrypted configs" );
847 if ( ok && !reencryptAllAuthenticationSettings( prevpass, prevciv ) )
850 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not re-encrypt settings in database" );
855 if ( ok && !reencryptAllAuthenticationIdentities( prevpass, prevciv ) )
858 const char *err = QT_TR_NOOP(
"Master password reset FAILED: could not re-encrypt identities in database" );
866 const QString err = tr(
"Master password reset FAILED: could not sync password helper: %1" ).arg(
passwordHelperErrorMessage() );
875 QString errdbbackup( dbbackup );
876 errdbbackup.replace(
".db"_L1,
"_ERROR.db"_L1 );
878 QgsDebugError( u
"Master password reset FAILED: backed up failed db at %1"_s.arg( errdbbackup ) );
881 mMasterPass = prevpass;
882 QgsDebugError( u
"Master password reset FAILED: reinstated previous password and database"_s );
886 *backuppath = errdbbackup;
891 if ( !keepbackup && !QFile::remove( dbbackup ) )
893 const char *err = QT_TR_NOOP(
"Master password reset: could not remove old database backup" );
901 QgsDebugMsgLevel( u
"Master password reset: backed up previous db at %1"_s.arg( dbbackup ), 2 );
903 *backuppath = dbbackup;
914 Q_UNUSED( keepbackup )
915 Q_UNUSED( backuppath )
930 const QString existingPassword = passwordHelperRead( readOk );
939 Q_UNUSED( newPassword )
940 Q_UNUSED( keepBackup )
941 Q_UNUSED( backupPath )
951 mScheduledDbErase = scheduleErase;
953 mScheduledDbEraseRequestEmitted =
false;
954 mScheduledDbEraseRequestCount = 0;
958 if ( !mScheduledDbEraseTimer )
960 mScheduledDbEraseTimer = std::make_unique<QTimer>(
this );
961 connect( mScheduledDbEraseTimer.get(), &QTimer::timeout,
this, &QgsAuthManager::tryToStartDbErase );
962 mScheduledDbEraseTimer->start( mScheduledDbEraseRequestWait * 1000 );
964 else if ( !mScheduledDbEraseTimer->isActive() )
966 mScheduledDbEraseTimer->start();
971 if ( mScheduledDbEraseTimer && mScheduledDbEraseTimer->isActive() )
972 mScheduledDbEraseTimer->stop();
975 Q_UNUSED( scheduleErase )
985 qDeleteAll( mAuthMethods );
986 mAuthMethods.clear();
988 for (
const auto &authMethodKey : methods )
993 return !mAuthMethods.isEmpty();
1009#ifndef __clang_analyzer__
1012 QTimer::singleShot( 3, &loop, &QEventLoop::quit );
1019 for (
int i = 0; i < len; i++ )
1021 switch ( QRandomGenerator::system()->generate() % 2 )
1024 id +=
static_cast<char>(
'0' + QRandomGenerator::system()->generate() % 10 );
1027 id +=
static_cast<char>(
'a' + QRandomGenerator::system()->generate() % 26 );
1031 if ( !configids.contains(
id ) )
1053 const char *err = QT_TR_NOOP(
"Config ID is empty" );
1059 return !configids.contains(
id );
1069 const thread_local QRegularExpression authCfgRegExp( AUTH_CFG_REGEX );
1070 return txt.indexOf( authCfgRegExp ) != -1;
1082 QMutexLocker locker( mMutex.get() );
1083 QStringList providerAuthMethodsKeys;
1084 if ( !dataprovider.isEmpty() )
1101 if ( providerAuthMethodsKeys.isEmpty() || providerAuthMethodsKeys.contains( config.method() ) )
1104 if ( baseConfigs.contains( config.id() ) )
1111 baseConfigs.insert( config.id(), config );
1117 if ( storages.empty() )
1126 Q_UNUSED( dataprovider )
1144 if ( !
configIds.contains( config.id() ) )
1146 mConfigAuthMethods.insert( config.id(), config.method() );
1147 QgsDebugMsgLevel( u
"Stored auth config/methods:\n%1 %2"_s.arg( config.id(), config.method() ), 2 );
1153 QgsDebugMsgLevel( u
"A config with same id %1 was already added, skipping from %2"_s.arg( config.id(), storage->
name() ), 2 );
1168 if ( !mConfigAuthMethods.contains( authcfg ) )
1170 QgsDebugError( u
"No config auth method found in database for authcfg: %1"_s.arg( authcfg ) );
1174 QString authMethodKey = mConfigAuthMethods.value( authcfg );
1191 return mConfigAuthMethods.value( authcfg, QString() );
1206 Q_UNUSED( dataprovider )
1207 return QStringList();
1216 if ( !mAuthMethods.contains( authMethodKey ) )
1218 QgsDebugError( u
"No auth method registered for auth method key: %1"_s.arg( authMethodKey ) );
1222 return mAuthMethods.value( authMethodKey );
1224 Q_UNUSED( authMethodKey )
1234 if ( !mAuthMethods.contains( authMethodKey ) )
1236 QgsDebugError( u
"No auth method registered for auth method key: %1"_s.arg( authMethodKey ) );
1242 Q_UNUSED( authMethodKey )
1253 if ( dataprovider.isEmpty() )
1255 return mAuthMethods;
1259 QgsAuthMethodsMap::const_iterator i = mAuthMethods.constBegin();
1260 while ( i != mAuthMethods.constEnd() )
1263 && ( i.value()->supportedDataProviders().contains( u
"all"_s )
1264 || i.value()->supportedDataProviders().contains( dataprovider ) ) )
1266 filteredmap.insert( i.key(), i.value() );
1272 Q_UNUSED( dataprovider )
1278QWidget *QgsAuthManager::authMethodEditWidget(
const QString &authMethodKey, QWidget *parent )
1284 return method->editWidget( parent );
1316 QMutexLocker locker( mMutex.get() );
1323 const char *err = QT_TR_NOOP(
"Store config: FAILED because config is invalid" );
1329 QString uid = config.
id();
1330 bool passedinID = !uid.isEmpty();
1331 if ( uid.isEmpty() )
1339 const char *err = QT_TR_NOOP(
"Store config: FAILED because pre-defined config ID %1 is not unique" );
1347 const char *err = QT_TR_NOOP(
"Store config: FAILED because pre-defined config ID %1 could not be removed" );
1356 if ( configstring.isEmpty() )
1358 const char *err = QT_TR_NOOP(
"Store config: FAILED because config string is empty" );
1366 if ( defaultStorage->isEncrypted() )
1373 configCopy.
setId( uid );
1374 if ( !defaultStorage->storeMethodConfig( configCopy, configstring ) )
1388 config.
setId( uid );
1392 QgsDebugMsgLevel( u
"Store config SUCCESS for authcfg: %1"_s.arg( uid ), 2 );
1396 Q_UNUSED( overwrite )
1406 QMutexLocker locker( mMutex.get() );
1411 if ( !config.
isValid(
true ) )
1413 const char *err = QT_TR_NOOP(
"Update config: FAILED because config is invalid" );
1420 if ( configstring.isEmpty() )
1422 const char *err = QT_TR_NOOP(
"Update config: FAILED because config is empty" );
1453 if ( storages.empty() )
1464 QgsDebugMsgLevel( u
"Update config SUCCESS for authcfg: %1"_s.arg( config.
id() ), 2 );
1484 QMutexLocker locker( mMutex.get() );
1496 if ( ! config.
isValid(
true ) || ( full && payload.isEmpty() ) )
1519 QgsDebugError( u
"Update of authcfg %1 FAILED for auth method %2"_s.arg( authcfg, authMethodKey ) );
1522 QgsDebugMsgLevel( u
"Load %1 config SUCCESS for authcfg: %2"_s.arg( full ?
"full" :
"base", authcfg ), 2 );
1527 if ( storages.empty() )
1550 QMutexLocker locker( mMutex.get() );
1554 if ( authcfg.isEmpty() )
1580 if ( storages.empty() )
1602 if ( filename.isEmpty() )
1605 QDomDocument document( u
"qgis_authentication"_s );
1606 QDomElement root = document.createElement( u
"qgis_authentication"_s );
1607 document.appendChild( root );
1610 if ( !password.isEmpty() )
1615 root.setAttribute( u
"salt"_s, salt );
1616 root.setAttribute( u
"hash"_s, hash );
1617 root.setAttribute( u
"civ"_s, civ );
1620 QDomElement configurations = document.createElement( u
"configurations"_s );
1621 for (
const QString &authcfg : authcfgs )
1628 authMethodConfig.
writeXml( configurations, document );
1631 if ( !password.isEmpty() )
1633 QString configurationsString;
1634 QTextStream ts( &configurationsString );
1635 configurations.save( ts, 2 );
1636 root.appendChild( document.createTextNode(
QgsAuthCrypto::encrypt( password, civ, configurationsString ) ) );
1640 root.appendChild( configurations );
1643 QFile file( filename );
1644 if ( !file.open( QFile::WriteOnly | QIODevice::Truncate ) )
1647 QTextStream ts( &file );
1648#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1649 ts.setCodec(
"UTF-8" );
1651 document.save( ts, 2 );
1655 Q_UNUSED( filename )
1656 Q_UNUSED( authcfgs )
1657 Q_UNUSED( password )
1667 QFile file( filename );
1668 if ( !file.open( QFile::ReadOnly ) )
1673 QDomDocument document( u
"qgis_authentication"_s );
1674 if ( !document.setContent( &file ) )
1681 QDomElement root = document.documentElement();
1682 if ( root.tagName() !=
"qgis_authentication"_L1 )
1687 QDomElement configurations;
1688 if ( root.hasAttribute( u
"salt"_s ) )
1690 QString salt = root.attribute( u
"salt"_s );
1691 QString hash = root.attribute( u
"hash"_s );
1692 QString civ = root.attribute( u
"civ"_s );
1697 configurations = document.firstChild().toElement();
1701 configurations = root.firstChildElement( u
"configurations"_s );
1704 QDomElement configuration = configurations.firstChildElement();
1705 while ( !configuration.isNull() )
1708 ( void )authMethodConfig.
readXml( configuration );
1711 configuration = configuration.nextSiblingElement();
1715 Q_UNUSED( filename )
1716 Q_UNUSED( password )
1717 Q_UNUSED( overwrite )
1727 QMutexLocker locker( mMutex.get() );
1733 if ( defaultStorage->clearMethodConfigs() )
1742 QgsDebugMsgLevel( u
"FAILED to remove all configs from the default storage"_s, 2 );
1762 QMutexLocker locker( mMutex.get() );
1766 const char *err = QT_TR_NOOP(
"The authentication storage is not filesystem-based" );
1774 const char *err = QT_TR_NOOP(
"No authentication database file found" );
1784 if ( authConn.isValid() && authConn.isOpen() )
1788 QString datestamp( QDateTime::currentDateTime().toString( u
"yyyy-MM-dd-hhmmss"_s ) );
1790 dbbackup.replace(
".db"_L1, u
"_%1.db"_s.arg( datestamp ) );
1794 const char *err = QT_TR_NOOP(
"Could not back up authentication database" );
1801 *backuppath = dbbackup;
1806 Q_UNUSED( backuppath )
1816 QMutexLocker locker( mMutex.get() );
1827 if ( backuppath && !dbbackup.isEmpty() )
1828 *backuppath = dbbackup;
1832 if ( defaultStorage->erase() )
1834 mMasterPass = QString();
1861 Q_UNUSED( backuppath )
1867 const QString &dataprovider )
1880 QgsDebugError( u
"Network request updating not supported by authcfg: %1"_s.arg( authcfg ) );
1895 Q_UNUSED( dataprovider )
1901 const QString &dataprovider )
1914 QgsDebugMsgLevel( u
"Network reply updating not supported by authcfg: %1"_s.arg( authcfg ), 3 );
1930 Q_UNUSED( dataprovider )
1936 const QString &dataprovider )
1949 QgsDebugError( u
"Data source URI updating not supported by authcfg: %1"_s.arg( authcfg ) );
1963 Q_UNUSED( connectionItems )
1965 Q_UNUSED( dataprovider )
1983 QgsDebugError( u
"Proxy updating not supported by authcfg: %1"_s.arg( authcfg ) );
1992 QgsDebugMsgLevel( u
"Proxy updated successfully from authcfg: %1"_s.arg( authcfg ), 2 );
2000 Q_UNUSED( dataprovider )
2010 QMutexLocker locker( mMutex.get() );
2011 if ( key.isEmpty() )
2014 QString storeval( value.toString() );
2037 if ( !defaultStorage->storeAuthSetting( key, storeval ) )
2062 QMutexLocker locker( mMutex.get() );
2063 if ( key.isEmpty() )
2069 QVariant value = defaultValue;
2077 if ( !storeval.isEmpty() )
2088 if ( storages.empty() )
2096 Q_UNUSED( defaultValue )
2107 QMutexLocker locker( mMutex.get() );
2108 if ( key.isEmpty() )
2122 if ( storages.empty() )
2139 QMutexLocker locker( mMutex.get() );
2140 if ( key.isEmpty() )
2167 if ( storages.empty() )
2187 QMutexLocker locker( mMutex.get() );
2193 mCustomConfigByHostCache.clear();
2194 mHasCheckedIfCustomConfigByHostExists =
false;
2209 QMutexLocker locker( mMutex.get() );
2210 if ( cert.isNull() )
2224 QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
2229 QgsDebugError( u
"Store certificate identity: FAILED to remove pre-existing certificate identity %1"_s.arg(
id ) );
2237 if ( !defaultStorage->storeCertIdentity( cert, keypem ) )
2261 QMutexLocker locker( mMutex.get() );
2263 QSslCertificate cert;
2274 if ( !cert.isNull() )
2280 if ( storages.empty() )
2288 return QSslCertificate();
2296 QMutexLocker locker( mMutex.get() );
2297 QPair<QSslCertificate, QSslKey> bundle;
2312 if ( encryptedBundle.first.isNull() )
2314 QgsDebugError( u
"Certificate identity bundle is null for id: %1"_s.arg(
id ) );
2317 QSslKey key(
QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), encryptedBundle.second ).toLatin1(),
2318 QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey );
2321 QgsDebugError( u
"Certificate identity bundle: FAILED to create private key"_s );
2324 bundle = qMakePair( encryptedBundle.first, key );
2329 if ( storages.empty() )
2343 QMutexLocker locker( mMutex.get() );
2345 if ( QgsAuthCertUtils::certIsViable( bundle.first ) && !bundle.second.isNull() )
2347 return QStringList() << QString( bundle.first.toPem() ) << QString( bundle.second.toPem() );
2349 return QStringList();
2352 return QStringList();
2361 QMutexLocker locker( mMutex.get() );
2362 QList<QSslCertificate> certs;
2369 const QList<QSslCertificate> storageCerts = storage->
certIdentities();
2371 for (
const QSslCertificate &cert : std::as_const( storageCerts ) )
2373 if ( !certs.contains( cert ) )
2375 certs.append( cert );
2384 if ( storages.empty() )
2391 return QList<QSslCertificate>();
2400 QMutexLocker locker( mMutex.get() );
2414 for (
const QString &
id : std::as_const( storageIds ) )
2416 if ( !ids.contains(
id ) )
2429 return QStringList();
2438 QMutexLocker locker( mMutex.get() );
2453 if ( storages.empty() )
2470 QMutexLocker locker( mMutex.get() );
2493 if ( storages.empty() )
2511 QMutexLocker locker( mMutex.get() );
2519 const QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
2523 QgsDebugError( u
"Store SSL certificate custom config: FAILED to remove pre-existing config %1"_s.arg(
id ) );
2529 if ( !defaultStorage->storeSslCertCustomConfig( config ) )
2542 mCustomConfigByHostCache.clear();
2556 QMutexLocker locker( mMutex.get() );
2559 if (
id.isEmpty() || hostport.isEmpty() )
2561 QgsDebugError( u
"Passed config ID or host:port is empty"_s );
2585 if ( storages.empty() )
2594 Q_UNUSED( hostport )
2605 if ( hostport.isEmpty() )
2610 QMutexLocker locker( mMutex.get() );
2612 if ( mCustomConfigByHostCache.contains( hostport ) )
2613 return mCustomConfigByHostCache.value( hostport );
2623 mCustomConfigByHostCache.insert( hostport, config );
2628 if ( storages.empty() )
2635 Q_UNUSED( hostport )
2645 QMutexLocker locker( mMutex.get() );
2646 QList<QgsAuthConfigSslServer> configs;
2657 for (
const auto &config : std::as_const( storageConfigs ) )
2659 const QString id( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ) );
2660 const QString hostPort = config.sslHostPort();
2661 const QString shaHostPort( u
"%1:%2"_s.arg(
id, hostPort ) );
2662 if ( ! ids.contains( shaHostPort ) )
2664 ids.append( shaHostPort );
2665 configs.append( config );
2674 if ( storages.empty() )
2681 return QList<QgsAuthConfigSslServer>();
2690 QMutexLocker locker( mMutex.get() );
2691 if (
id.isEmpty() || hostPort.isEmpty() )
2693 QgsDebugError( u
"Passed config ID or host:port is empty"_s );
2708 if ( storages.empty() )
2716 Q_UNUSED( hostPort )
2726 QMutexLocker locker( mMutex.get() );
2727 if (
id.isEmpty() || hostport.isEmpty() )
2729 QgsDebugError( u
"Passed config ID or host:port is empty"_s );
2733 mCustomConfigByHostCache.clear();
2747 const QString shaHostPort( u
"%1:%2"_s.arg(
id, hostport ) );
2748 if ( mIgnoredSslErrorsCache.contains( shaHostPort ) )
2750 mIgnoredSslErrorsCache.remove( shaHostPort );
2756 if ( storages.empty() )
2764 Q_UNUSED( hostport )
2775 QMutexLocker locker( mMutex.get() );
2776 if ( !mIgnoredSslErrorsCache.isEmpty() )
2779 QHash<QString, QSet<QSslError::SslError> >::const_iterator i = mIgnoredSslErrorsCache.constBegin();
2780 while ( i != mIgnoredSslErrorsCache.constEnd() )
2783 for (
auto err : i.value() )
2785 errs << QgsAuthCertUtils::sslErrorEnumString( err );
2803 QMutexLocker locker( mMutex.get() );
2810 QString shahostport( u
"%1:%2"_s
2811 .arg( QgsAuthCertUtils::shaHexForCert( config.
sslCertificate() ).trimmed(),
2813 if ( mIgnoredSslErrorsCache.contains( shahostport ) )
2815 mIgnoredSslErrorsCache.remove( shahostport );
2818 if ( !errenums.isEmpty() )
2820 mIgnoredSslErrorsCache.insert( shahostport, QSet<QSslError::SslError>( errenums.begin(), errenums.end() ) );
2821 QgsDebugMsgLevel( u
"Update of ignored SSL errors cache SUCCEEDED for sha:host:port = %1"_s.arg( shahostport ), 2 );
2826 QgsDebugMsgLevel( u
"No ignored SSL errors to cache for sha:host:port = %1"_s.arg( shahostport ), 2 );
2839 QMutexLocker locker( mMutex.get() );
2840 const thread_local QRegularExpression rx( QRegularExpression::anchoredPattern(
"\\S+:\\S+:\\d+" ) );
2841 if ( !rx.match( shahostport ).hasMatch() )
2843 QgsDebugError(
"Passed shahostport does not match \\S+:\\S+:\\d+, "
2844 "e.g. 74a4ef5ea94512a43769b744cda0ca5049a72491:www.example.com:443" );
2848 if ( mIgnoredSslErrorsCache.contains( shahostport ) )
2850 mIgnoredSslErrorsCache.remove( shahostport );
2853 if ( errors.isEmpty() )
2859 QSet<QSslError::SslError> errs;
2860 for (
const auto &error : errors )
2862 if ( error.error() == QSslError::NoError )
2865 errs.insert( error.error() );
2868 if ( errs.isEmpty() )
2870 QgsDebugError( u
"Passed errors list does not contain errors"_s );
2874 mIgnoredSslErrorsCache.insert( shahostport, errs );
2876 QgsDebugMsgLevel( u
"Update of ignored SSL errors cache SUCCEEDED for sha:host:port = %1"_s.arg( shahostport ), 2 );
2880 Q_UNUSED( shahostport )
2891 QMutexLocker locker( mMutex.get() );
2892 QHash<QString, QSet<QSslError::SslError> > prevcache( mIgnoredSslErrorsCache );
2893 QHash<QString, QSet<QSslError::SslError> > nextcache;
2903 for (
const auto &config : std::as_const( customConfigs ) )
2905 const QString shaHostPort( u
"%1:%2"_s.arg( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ), config.sslHostPort() ) );
2906 if ( ! ids.contains( shaHostPort ) )
2908 ids.append( shaHostPort );
2909 if ( !config.sslIgnoredErrorEnums().isEmpty() )
2911 nextcache.insert( shaHostPort, QSet<QSslError::SslError>( config.sslIgnoredErrorEnums().cbegin(), config.sslIgnoredErrorEnums().cend() ) );
2913 if ( prevcache.contains( shaHostPort ) )
2915 prevcache.remove( shaHostPort );
2925 if ( !prevcache.isEmpty() )
2928 QHash<QString, QSet<QSslError::SslError> >::const_iterator i = prevcache.constBegin();
2929 while ( i != prevcache.constEnd() )
2931 nextcache.insert( i.key(), i.value() );
2936 if ( nextcache != mIgnoredSslErrorsCache )
2938 mIgnoredSslErrorsCache.clear();
2939 mIgnoredSslErrorsCache = nextcache;
2945 QgsDebugMsgLevel( u
"Rebuild of ignored SSL errors cache SAME AS BEFORE"_s, 2 );
2958 QMutexLocker locker( mMutex.get() );
2959 if ( certs.isEmpty() )
2965 for (
const auto &cert : certs )
2982 QMutexLocker locker( mMutex.get() );
2985 if ( cert.isNull() )
2993 QgsDebugError( u
"Store certificate authority: FAILED to remove pre-existing certificate authority"_s );
2999 return defaultStorage->storeCertAuthority( cert );
3019 QMutexLocker locker( mMutex.get() );
3020 QSslCertificate emptycert;
3021 QSslCertificate cert;
3031 if ( !cert.isNull() )
3037 if ( storages.empty() )
3046 return QSslCertificate();
3055 QMutexLocker locker( mMutex.get() );
3056 if ( cert.isNull() )
3073 if ( storages.empty() )
3089 QMutexLocker locker( mMutex.get() );
3090 if ( cert.isNull() )
3119 if ( storages.empty() )
3134 return QSslConfiguration::systemCaCertificates();
3136 return QList<QSslCertificate>();
3145 QMutexLocker locker( mMutex.get() );
3146 QList<QSslCertificate> certs;
3147 QList<QSslCertificate> filecerts;
3156 QString cafile( cafileval.toString() );
3157 if ( !cafile.isEmpty() && QFile::exists( cafile ) )
3159 filecerts = QgsAuthCertUtils::certsFromFile( cafile );
3162 for (
const auto &cert : std::as_const( filecerts ) )
3164 if ( !allowinvalid.toBool() && ( cert.isBlacklisted()
3166 || cert.expiryDate() <= QDateTime::currentDateTime()
3167 || cert.effectiveDate() > QDateTime::currentDateTime() ) )
3172 if ( QgsAuthCertUtils::certificateIsAuthorityOrIssuer( cert ) )
3179 return QList<QSslCertificate>();
3188 QMutexLocker locker( mMutex.get() );
3193 QList<QSslCertificate> certs;
3197 const QList<QSslCertificate> storageCerts = storage->
caCerts();
3199 for (
const QSslCertificate &cert : std::as_const( storageCerts ) )
3201 if ( !certs.contains( cert ) )
3203 certs.append( cert );
3212 if ( storages.empty() )
3219 return QList<QSslCertificate>();
3227 QMutexLocker locker( mMutex.get() );
3228 return QgsAuthCertUtils::mapDigestToCerts(
databaseCAs() );
3236 QMutexLocker locker( mMutex.get() );
3237 mCaCertsCache.clear();
3243 bool res = !mCaCertsCache.isEmpty();
3257 QMutexLocker locker( mMutex.get() );
3258 if ( cert.isNull() )
3277 return defaultStorage->storeCertTrustPolicy( cert, policy );
3296 QMutexLocker locker( mMutex.get() );
3297 if ( cert.isNull() )
3315 if ( storages.empty() )
3332 QMutexLocker locker( mMutex.get() );
3333 if ( certs.empty() )
3339 for (
const auto &cert : certs )
3356 QMutexLocker locker( mMutex.get() );
3357 if ( cert.isNull() )
3385 if ( storages.empty() )
3402 QMutexLocker locker( mMutex.get() );
3403 if ( cert.isNull() )
3408 QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
3413 if ( trustedids.contains(
id ) )
3417 else if ( untrustedids.contains(
id ) )
3438 return storeAuthSetting( u
"certdefaulttrust"_s,
static_cast< int >( policy ) );
3450 QMutexLocker locker( mMutex.get() );
3451 QVariant policy(
authSetting( u
"certdefaulttrust"_s ) );
3467 QMutexLocker locker( mMutex.get() );
3468 mCertTrustCache.clear();
3479 for (
auto it = trustedCerts.cbegin(); it != trustedCerts.cend(); ++it )
3481 const QString
id { it.key( )};
3482 if ( ! ids.contains(
id ) )
3503 if ( ! storages.empty() )
3523 QMutexLocker locker( mMutex.get() );
3527 const QList<QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > &certpairs( mCaCertsCache.values() );
3529 QList<QSslCertificate> trustedcerts;
3530 for (
int i = 0; i < certpairs.size(); ++i )
3532 QSslCertificate cert( certpairs.at( i ).second );
3533 QString certid( QgsAuthCertUtils::shaHexForCert( cert ) );
3534 if ( trustedids.contains( certid ) )
3537 trustedcerts.append( cert );
3541 if ( !includeinvalid && !QgsAuthCertUtils::certIsViable( cert ) )
3543 trustedcerts.append( cert );
3548 QSslConfiguration sslconfig( QSslConfiguration::defaultConfiguration() );
3549 sslconfig.setCaCertificates( trustedcerts );
3550 QSslConfiguration::setDefaultConfiguration( sslconfig );
3552 return trustedcerts;
3554 Q_UNUSED( includeinvalid )
3555 return QList<QSslCertificate>();
3564 QMutexLocker locker( mMutex.get() );
3565 if ( trustedCAs.isEmpty() )
3567 if ( mTrustedCaCertsCache.isEmpty() )
3574 const QList<QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > &certpairs( mCaCertsCache.values() );
3576 QList<QSslCertificate> untrustedCAs;
3577 for (
int i = 0; i < certpairs.size(); ++i )
3579 QSslCertificate cert( certpairs.at( i ).second );
3580 if ( !trustedCAs.contains( cert ) )
3582 untrustedCAs.append( cert );
3585 return untrustedCAs;
3587 Q_UNUSED( trustedCAs )
3588 return QList<QSslCertificate>();
3597 QMutexLocker locker( mMutex.get() );
3612 QMutexLocker locker( mMutex.get() );
3615 return QByteArray();
3624 QMutexLocker locker( mMutex.get() );
3627 return passwordHelperWrite( mMasterPass );
3641 bool readOk =
false;
3642 const QString currentPass = passwordHelperRead( readOk );
3646 if ( !currentPass.isEmpty() && ( mPasswordHelperErrorCode == QKeychain::NoError ) )
3659#if defined(Q_OS_MAC)
3660 return titleCase ? QObject::tr(
"Keychain" ) : QObject::tr(
"keychain" );
3661#elif defined(Q_OS_WIN)
3662 return titleCase ? QObject::tr(
"Password Manager" ) : QObject::tr(
"password manager" );
3663#elif defined(Q_OS_LINUX)
3665 const QString desktopSession = qgetenv(
"DESKTOP_SESSION" );
3666 const QString currentDesktop = qgetenv(
"XDG_CURRENT_DESKTOP" );
3667 const QString gdmSession = qgetenv(
"GDMSESSION" );
3669 if ( desktopSession.contains(
"kde"_L1, Qt::CaseInsensitive ) || currentDesktop.contains(
"kde"_L1, Qt::CaseInsensitive ) || gdmSession.contains(
"kde"_L1, Qt::CaseInsensitive ) )
3671 return titleCase ? QObject::tr(
"Wallet" ) : QObject::tr(
"wallet" );
3674 return titleCase ? QObject::tr(
"Wallet/Key Ring" ) : QObject::tr(
"wallet/key ring" );
3676 return titleCase ? QObject::tr(
"Password Manager" ) : QObject::tr(
"password manager" );
3679 Q_UNUSED( titleCase )
3698 for (
const auto &authcfg : ids )
3723void QgsAuthManager::writeToConsole(
const QString &message,
3740 msg +=
"WARNING: "_L1;
3743 msg +=
"ERROR: "_L1;
3750 QTextStream out( stdout, QIODevice::WriteOnly );
3751 out << msg << Qt::endl;
3759void QgsAuthManager::tryToStartDbErase()
3764 ++mScheduledDbEraseRequestCount;
3766 int trycutoff = 90 / ( mScheduledDbEraseRequestWait ? mScheduledDbEraseRequestWait : 3 );
3767 if ( mScheduledDbEraseRequestCount >= trycutoff )
3770 QgsDebugMsgLevel( u
"authDatabaseEraseRequest emitting/scheduling canceled"_s, 2 );
3776 .arg( mScheduledDbEraseRequestCount ).arg( trycutoff ), 2 );
3782 mScheduledDbEraseRequestEmitted =
true;
3798 QMutexLocker locker( mMutex.get() );
3800 QMapIterator<QThread *, QMetaObject::Connection> iterator( mConnectedThreads );
3801 while ( iterator.hasNext() )
3804 QThread::disconnect( iterator.value() );
3815 qDeleteAll( mAuthMethods );
3820 if ( authConn.isValid() && authConn.isOpen() )
3824 QSqlDatabase::removeDatabase( u
"authentication.configs"_s );
3830 QMutexLocker locker( mMutex.get() );
3831 if ( ! mAuthConfigurationStorageRegistry )
3833 mAuthConfigurationStorageRegistry = std::make_unique<QgsAuthConfigurationStorageRegistry>();
3835 return mAuthConfigurationStorageRegistry.get();
3839QString QgsAuthManager::passwordHelperName()
const
3842 return tr(
"Password Helper" );
3849void QgsAuthManager::passwordHelperLog(
const QString &msg )
const
3870 QKeychain::DeletePasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3873 job.setAutoDelete(
false );
3874 job.setKey( authPasswordHelperKeyName() );
3876 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3881 mPasswordHelperErrorCode = job.error();
3882 mPasswordHelperErrorMessage = tr(
"Delete password failed: %1." ).arg( job.errorString() );
3893 passwordHelperProcessError();
3900QString QgsAuthManager::passwordHelperRead(
bool &ok )
3909 QKeychain::ReadPasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3912 job.setAutoDelete(
false );
3913 job.setKey( authPasswordHelperKeyName() );
3915 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3920 mPasswordHelperErrorCode = job.error();
3921 mPasswordHelperErrorMessage = tr(
"Retrieving password from the %1 failed: %2." ).arg(
passwordHelperDisplayName(), job.errorString() );
3927 password = job.textData();
3929 if ( password.isEmpty() )
3931 mPasswordHelperErrorCode = QKeychain::EntryNotFound;
3943 passwordHelperProcessError();
3951bool QgsAuthManager::passwordHelperWrite(
const QString &password )
3956 Q_ASSERT( !password.isEmpty() );
3959 QKeychain::WritePasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3960 QgsSettings settings;
3962 job.setAutoDelete(
false );
3963 job.setKey( authPasswordHelperKeyName() );
3964 job.setTextData( password );
3966 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3971 mPasswordHelperErrorCode = job.error();
3972 mPasswordHelperErrorMessage = tr(
"Storing password in the %1 failed: %2." ).arg(
passwordHelperDisplayName(), job.errorString() );
3979 passwordHelperClearErrors();
3984 passwordHelperProcessError();
3987 Q_UNUSED( password )
4008 emit
messageLog( enabled ? tr(
"Your %1 will be <b>used from now</b> on to store and retrieve the master password." )
4010 tr(
"Your %1 will <b>not be used anymore</b> to store and retrieve the master password." )
4038void QgsAuthManager::passwordHelperClearErrors()
4041 mPasswordHelperErrorCode = QKeychain::NoError;
4042 mPasswordHelperErrorMessage.clear();
4046void QgsAuthManager::passwordHelperProcessError()
4051 if ( mPasswordHelperErrorCode == QKeychain::AccessDenied ||
4052 mPasswordHelperErrorCode == QKeychain::AccessDeniedByUser ||
4053 mPasswordHelperErrorCode == QKeychain::NoBackendAvailable ||
4054 mPasswordHelperErrorCode == QKeychain::NotImplemented )
4060 mPasswordHelperErrorMessage = tr(
"There was an error and integration with your %1 has been disabled. "
4061 "You can re-enable it at any time through the \"Utilities\" menu "
4062 "in the Authentication pane of the options dialog. %2" )
4065 if ( mPasswordHelperErrorCode != QKeychain::NoError )
4071 passwordHelperClearErrors();
4076bool QgsAuthManager::masterPasswordInput()
4085 bool storedPasswordIsValid =
false;
4091 bool readOk =
false;
4092 pass = passwordHelperRead( readOk );
4093 if ( readOk && ! pass.isEmpty() && ( mPasswordHelperErrorCode == QKeychain::NoError ) )
4099 storedPasswordIsValid =
true;
4114 if ( ok && !pass.isEmpty() && mMasterPass != pass )
4119 if ( !passwordHelperWrite( pass ) )
4132bool QgsAuthManager::masterPasswordRowsInDb(
int &rows )
const
4143 QMutexLocker locker( mMutex.get() );
4148 if ( storages.empty() )
4154 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4162 catch (
const QgsNotSupportedException &e )
4186 if ( !masterPasswordRowsInDb( rows ) )
4188 const char *err = QT_TR_NOOP(
"Master password: FAILED to access database" );
4194 return ( rows == 1 );
4200bool QgsAuthManager::masterPasswordCheckAgainstDb(
const QString &compare )
const
4213 const QList<QgsAuthConfigurationStorage::MasterPasswordConfig> passwords { defaultStorage->masterPasswords( ) };
4214 if ( passwords.size() == 0 )
4219 const QgsAuthConfigurationStorage::MasterPasswordConfig storedPassword { passwords.first() };
4222 catch (
const QgsNotSupportedException &e )
4241bool QgsAuthManager::masterPasswordStoreInDb()
const
4249 QString salt, hash, civ;
4257 return defaultStorage->storeMasterPassword( { salt, civ, hash } );
4259 catch (
const QgsNotSupportedException &e )
4276bool QgsAuthManager::masterPasswordClearDb()
4289 return defaultStorage->clearMasterPasswords();
4291 catch (
const QgsNotSupportedException &e )
4309const QString QgsAuthManager::masterPasswordCiv()
const
4321 const QList<QgsAuthConfigurationStorage::MasterPasswordConfig> passwords { defaultStorage->masterPasswords( ) };
4322 if ( passwords.size() == 0 )
4327 return passwords.first().civ;
4329 catch (
const QgsNotSupportedException &e )
4351 QStringList configKeys = QStringList();
4365 for (
auto it = configs.cbegin(); it != configs.cend(); ++it )
4367 if ( !configKeys.contains( it.key() ) )
4369 configKeys.append( it.key() );
4386 return QStringList();
4390bool QgsAuthManager::verifyPasswordCanDecryptConfigs()
const
4403 for (
const QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4414 for (
auto it = configs.cbegin(); it != configs.cend(); ++it )
4416 QString configstring(
QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), it.value().config( u
"encrypted_payload"_s ) ) );
4417 if ( configstring.isEmpty() )
4419 QgsDebugError( u
"Verify password can decrypt configs FAILED, could not decrypt a config (id: %1) from storage %2"_s
4420 .arg( it.key(), storage->
name() ) );
4425 catch (
const QgsNotSupportedException &e )
4434 if ( storages.empty() )
4446bool QgsAuthManager::reencryptAllAuthenticationConfigs(
const QString &prevpass,
const QString &prevciv )
4456 for (
const auto &configid : ids )
4458 res = res && reencryptAuthenticationConfig( configid, prevpass, prevciv );
4462 Q_UNUSED( prevpass )
4468bool QgsAuthManager::reencryptAuthenticationConfig(
const QString &authcfg,
const QString &prevpass,
const QString &prevciv )
4481 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4493 const QgsAuthMethodConfig config = storage->
loadMethodConfig( authcfg, payload,
true );
4494 if ( payload.isEmpty() || ! config.
isValid(
true ) )
4496 QgsDebugError( u
"Reencrypt FAILED, could not find config (id: %1)"_s.arg( authcfg ) );
4501 if ( configstring.isEmpty() )
4503 QgsDebugError( u
"Reencrypt FAILED, could not decrypt config (id: %1)"_s.arg( authcfg ) );
4517 catch (
const QgsNotSupportedException &e )
4525 if ( storages.empty() )
4537 Q_UNUSED( prevpass )
4543bool QgsAuthManager::reencryptAllAuthenticationSettings(
const QString &prevpass,
const QString &prevciv )
4548 Q_UNUSED( prevpass )
4561 QStringList encryptedsettings;
4562 encryptedsettings <<
"";
4564 for (
const auto & sett, std::as_const( encryptedsettings ) )
4571 QSqlQuery query( authDbConnection() );
4573 query.prepare( QStringLiteral(
"SELECT value FROM %1 "
4574 "WHERE setting = :setting" ).arg( authDbSettingsTable() ) );
4576 query.bindValue(
":setting", sett );
4578 if ( !authDbQuery( &query ) )
4581 if ( !query.isActive() || !query.isSelect() )
4583 QgsDebugError( u
"Reencrypt FAILED, query not active or a select operation for setting: %2"_s.arg( sett ) );
4587 if ( query.first() )
4593 query.prepare( QStringLiteral(
"UPDATE %1 "
4594 "SET value = :value "
4595 "WHERE setting = :setting" ).arg( authDbSettingsTable() ) );
4597 query.bindValue(
":setting", sett );
4600 if ( !authDbStartTransaction() )
4603 if ( !authDbQuery( &query ) )
4606 if ( !authDbCommit() )
4614 QgsDebugError( u
"Reencrypt FAILED, could not find in db setting: %2"_s.arg( sett ) );
4620 QgsDebugError( u
"Select contains more than one for setting: %1"_s.arg( sett ) );
4631bool QgsAuthManager::reencryptAllAuthenticationIdentities(
const QString &prevpass,
const QString &prevciv )
4641 for (
const auto &identid : ids )
4643 res = res && reencryptAuthenticationIdentity( identid, prevpass, prevciv );
4647 Q_UNUSED( prevpass )
4653bool QgsAuthManager::reencryptAuthenticationIdentity(
4654 const QString &identid,
4655 const QString &prevpass,
4656 const QString &prevciv )
4670 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4685 if ( keystring.isEmpty() )
4687 QgsDebugError( u
"Reencrypt FAILED, could not decrypt identity id: %1"_s.arg( identid ) );
4695 catch (
const QgsNotSupportedException &e )
4703 if ( storages.empty() )
4715 Q_UNUSED( prevpass )
4727 for (
const auto &cert : certs )
4729 mCaCertsCache.insert( QgsAuthCertUtils::shaHexForCert( cert ),
4730 QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate>( source, cert ) );
4739QString QgsAuthManager::authPasswordHelperKeyName()
const
4744 QString dbProfilePath;
4750 const QFileInfo info( mAuthDatabaseConnectionUri );
4751 dbProfilePath = info.dir().dirName();
4755 dbProfilePath = QCryptographicHash::hash( ( mAuthDatabaseConnectionUri.toUtf8() ), QCryptographicHash::Md5 ).toHex();
4759 return AUTH_PASSWORD_HELPER_KEY_NAME_BASE + ( dbProfilePath.compare(
"default"_L1, Qt::CaseInsensitive ) == 0 ? QString() : dbProfilePath );
4772 if ( qobject_cast<QgsAuthConfigurationStorageDb *>( storage ) )
4787 Q_UNUSED( capability )
MessageLevel
Level for messages This will be used both for message log and message bar in application.
@ Warning
Warning message.
@ Critical
Critical/error message.
@ Info
Information message.
AuthConfigurationStorageCapability
Authentication configuration storage capabilities.
@ CreateSetting
Can create a new authentication setting.
@ CreateConfiguration
Can create a new authentication configuration.
@ ClearStorage
Can clear all configurations from storage.
@ DeleteCertificateAuthority
Can delete a certificate authority.
@ DeleteSslCertificateCustomConfig
Can delete a SSL certificate custom config.
@ DeleteSetting
Can delete the authentication setting.
@ ReadSslCertificateCustomConfig
Can read a SSL certificate custom config.
@ DeleteMasterPassword
Can delete the master password.
@ CreateSslCertificateCustomConfig
Can create a new SSL certificate custom config.
@ ReadCertificateTrustPolicy
Can read a certificate trust policy.
@ ReadConfiguration
Can read an authentication configuration.
@ UpdateConfiguration
Can update an authentication configuration.
@ ReadCertificateAuthority
Can read a certificate authority.
@ CreateCertificateAuthority
Can create a new certificate authority.
@ DeleteConfiguration
Can deleet an authentication configuration.
@ ReadSetting
Can read the authentication settings.
@ CreateCertificateIdentity
Can create a new certificate identity.
@ ReadCertificateIdentity
Can read a certificate identity.
@ CreateCertificateTrustPolicy
Can create a new certificate trust policy.
@ ReadMasterPassword
Can read the master password.
@ CreateMasterPassword
Can create a new master password.
@ DeleteCertificateTrustPolicy
Can delete a certificate trust policy.
CertTrustPolicy
Type of certificate trust policy.
CaCertSource
Type of CA certificate source.
Configuration container for SSL server connection exceptions or overrides.
bool isNull() const
Whether configuration is null (missing components).
const QList< QSslError::SslError > sslIgnoredErrorEnums() const
SSL server errors (as enum list) to ignore in connections.
const QSslCertificate sslCertificate() const
Server certificate object.
const QString sslHostPort() const
Server host:port string.
QSqlDatabase based implementation of QgsAuthConfigurationStorage.
bool removeCertTrustPolicy(const QSslCertificate &cert) override
Remove certificate trust policy.
const QgsAuthConfigSslServer loadSslCertCustomConfigByHost(const QString &hostport) const override
Loads an SSL certificate custom config by hostport (host:port).
QString loadAuthSetting(const QString &key) const override
Load an authentication setting from the storage.
bool removeAuthSetting(const QString &key) override
Remove an authentication setting from the storage.
const QMap< QString, QgsAuthCertUtils::CertTrustPolicy > caCertsPolicy() const override
Returns the map of CA certificates hashes in the storages and their trust policy.
QgsAuthCertUtils::CertTrustPolicy loadCertTrustPolicy(const QSslCertificate &cert) const override
Load certificate trust policy.
bool sslCertCustomConfigExists(const QString &id, const QString &hostport) override
Check if SSL certificate custom config exists.
bool removeCertIdentity(const QSslCertificate &cert) override
Remove a certificate identity from the storage.
const QPair< QSslCertificate, QString > loadCertIdentityBundle(const QString &id) const override
Returns a certificate identity bundle by id (sha hash).
const QList< QgsAuthConfigurationStorage::MasterPasswordConfig > masterPasswords() const override
Returns the list of (encrypted) master passwords stored in the database.
bool methodConfigExists(const QString &id) const override
Check if an authentication configuration exists in the storage.
QStringList certIdentityIds() const override
certIdentityIds get list of certificate identity ids from database
bool initialize() override
Initializes the storage.
bool storeMethodConfig(const QgsAuthMethodConfig &mconfig, const QString &payload) override
Store an authentication config in the database.
bool removeCertAuthority(const QSslCertificate &cert) override
Remove a certificate authority.
const QSslCertificate loadCertIdentity(const QString &id) const override
certIdentity get a certificate identity by id (sha hash)
const QList< QgsAuthConfigSslServer > sslCertCustomConfigs() const override
sslCertCustomConfigs get SSL certificate custom configs
QgsAuthMethodConfigsMap authMethodConfigs(const QStringList &allowedMethods=QStringList()) const override
Returns a mapping of authentication configurations available from this storage.
const QList< QSslCertificate > caCerts() const override
Returns the list of CA certificates in the storage.
bool certTrustPolicyExists(const QSslCertificate &cert) const override
Check if certificate trust policy exists.
const QSslCertificate loadCertAuthority(const QString &id) const override
certAuthority get a certificate authority by id (sha hash)
bool removeMethodConfig(const QString &id) override
Removes the authentication configuration with the specified id.
QgsAuthMethodConfigsMap authMethodConfigsWithPayload() const override
Returns a mapping of authentication configurations available from this storage.
bool certIdentityExists(const QString &id) const override
Check if the certificate identity exists.
bool certAuthorityExists(const QSslCertificate &cert) const override
Check if a certificate authority exists.
QgsAuthMethodConfig loadMethodConfig(const QString &id, QString &payload, bool full=false) const override
Load an authentication configuration from the database.
bool storeCertIdentity(const QSslCertificate &cert, const QString &keyPem) override
Store a certificate identity in the storage.
bool removeSslCertCustomConfig(const QString &id, const QString &hostport) override
Remove an SSL certificate custom config.
const QList< QSslCertificate > certIdentities() const override
certIdentities get certificate identities
QString name() const override
Returns a human readable localized short name of the storage implementation (e.g "SQLite").
bool authSettingExists(const QString &key) const override
Check if an authentication setting exists in the storage.
const QgsAuthConfigSslServer loadSslCertCustomConfig(const QString &id, const QString &hostport) const override
Loads an SSL certificate custom config by id (sha hash) and hostport (host:port).
Registry for authentication configuration storages.
QgsAuthConfigurationStorage * firstReadyStorageWithCapability(Qgis::AuthConfigurationStorageCapability capability) const
Returns the first ready (and enabled) authentication configuration storage which has the required cap...
QList< QgsAuthConfigurationStorage * > storages() const
Returns the list of all registered authentication configuration storages.
QList< QgsAuthConfigurationStorage * > readyStoragesWithCapability(Qgis::AuthConfigurationStorageCapability capability) const
Returns the list of all ready (and enabled) authentication configuration storage with the required ca...
QList< QgsAuthConfigurationStorage * > readyStorages() const
Returns the list of all ready (and enabled) authentication configuration storage.
bool addStorage(QgsAuthConfigurationStorage *storage)
Add an authentication configuration storage to the registry.
Abstract class that defines the interface for all authentication configuration storage implementation...
void messageLog(const QString &message, const QString &tag=u"Authentication"_s, Qgis::MessageLevel level=Qgis::MessageLevel::Info)
Custom logging signal to relay to console output and QgsMessageLog.
virtual void setReadOnly(bool readOnly)
Utility method to unset all editing capabilities.
void methodConfigChanged()
Emitted when the storage method config table was changed.
Qgis::AuthConfigurationStorageCapabilities capabilities() const
Returns the capabilities of the storage.
bool isEnabled() const
Returns true if the storage is enabled.
bool isEncrypted() const
Returns true if the storage is encrypted.
virtual QString lastError() const
Returns the last error message.
static void passwordKeyHash(const QString &pass, QString *salt, QString *hash, QString *cipheriv=nullptr)
Generate SHA256 hash for master password, with iterations and salt.
static const QString encrypt(const QString &pass, const QString &cipheriv, const QString &text)
Encrypt data using master password.
static bool verifyPasswordKeyHash(const QString &pass, const QString &salt, const QString &hash, QString *hashderived=nullptr)
Verify existing master password hash to a re-generated one.
static const QString decrypt(const QString &pass, const QString &cipheriv, const QString &text)
Decrypt data using master password.
Singleton which offers an interface to manage the authentication configuration database and to utiliz...
bool storeAuthSetting(const QString &key, const QVariant &value, bool encrypt=false)
Stores an authentication setting.
bool setDefaultCertTrustPolicy(QgsAuthCertUtils::CertTrustPolicy policy)
Sets the default certificate trust policy preferred by user.
void clearAllCachedConfigs()
Clear all authentication configs from authentication method caches.
const QSslCertificate certIdentity(const QString &id)
certIdentity get a certificate identity by id (sha hash)
const QStringList certIdentityBundleToPem(const QString &id)
certIdentityBundleToPem get a certificate identity bundle by id (sha hash) returned as PEM text
bool updateIgnoredSslErrorsCache(const QString &shahostport, const QList< QSslError > &errors)
Update ignored SSL error cache with possible ignored SSL errors, using sha:host:port key.
bool verifyMasterPassword(const QString &compare=QString())
Verify the supplied master password against any existing hash in authentication database.
bool updateIgnoredSslErrorsCacheFromConfig(const QgsAuthConfigSslServer &config)
Update ignored SSL error cache with possible ignored SSL errors, using server config.
const QString disabledMessage() const
Standard message for when QCA's qca-ossl plugin is missing and system is disabled.
const QList< QSslCertificate > trustedCaCertsCache()
trustedCaCertsCache cache of trusted certificate authorities, ready for network connections
QgsAuthMethod * configAuthMethod(const QString &authcfg)
Gets authentication method from the config/provider cache.
static bool isFilesystemBasedDatabase(const QString &uri)
Returns the true if the uri is a filesystem-based database (SQLite).
bool storeCertIdentity(const QSslCertificate &cert, const QSslKey &key)
Store a certificate identity.
QgsAuthMethodsMap authMethodsMap(const QString &dataprovider=QString())
Gets available authentication methods mapped to their key.
bool rebuildIgnoredSslErrorCache()
Rebuild ignoredSSL error cache.
bool initSslCaches()
Initialize various SSL authentication caches.
const QList< QSslCertificate > extraFileCAs()
extraFileCAs extra file-based certificate authorities
bool removeAuthSetting(const QString &key)
Remove an authentication setting.
bool storeCertTrustPolicy(const QSslCertificate &cert, QgsAuthCertUtils::CertTrustPolicy policy)
Store user trust value for a certificate.
bool rebuildCaCertsCache()
Rebuild certificate authority cache.
bool scheduledAuthDatabaseErase()
Whether there is a scheduled opitonal erase of authentication database.
bool eraseAuthenticationDatabase(bool backup, QString *backuppath=nullptr)
Erase all rows from all tables in authentication database.
static bool passwordHelperEnabled()
Password helper enabled getter.
void passwordHelperMessageLog(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level=Qgis::MessageLevel::Info)
Custom logging signal to inform the user about master password <-> password manager interactions.
bool exportAuthenticationConfigsToXml(const QString &filename, const QStringList &authcfgs, const QString &password=QString())
Export authentication configurations to an XML file.
QString sqliteDatabasePath() const
Returns the path to the authentication database file or an empty string if the database is not SQLite...
Q_DECL_DEPRECATED bool init(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
init initialize QCA, prioritize qca-ossl plugin and optionally set up the authentication database
void authDatabaseChanged()
Emitted when the authentication db is significantly changed, e.g. large record removal,...
void setPasswordHelperEnabled(bool enabled)
Password helper enabled setter.
void setScheduledAuthDatabaseErase(bool scheduleErase)
Schedule an optional erase of authentication database, starting when mutex is lockable.
const QList< QgsAuthConfigSslServer > sslCertCustomConfigs()
sslCertCustomConfigs get SSL certificate custom configs
const QList< QSslCertificate > untrustedCaCerts(QList< QSslCertificate > trustedCAs=QList< QSslCertificate >())
untrustedCaCerts get list of untrusted certificate authorities
const QString uniqueConfigId() const
Gets a unique generated 7-character string to assign to as config id.
const QPair< QSslCertificate, QSslKey > certIdentityBundle(const QString &id)
Gets a certificate identity bundle by id (sha hash).
bool isDisabled() const
Whether QCA has the qca-ossl plugin, which a base run-time requirement.
QVariant authSetting(const QString &key, const QVariant &defaultValue=QVariant(), bool decrypt=false)
Returns a previously set authentication setting.
static const QString AUTH_MAN_TAG
The display name of the Authentication Manager.
QgsAuthCertUtils::CertTrustPolicy defaultCertTrustPolicy()
Gets the default certificate trust policy preferred by user.
const QByteArray trustedCaCertsPemText()
trustedCaCertsPemText get concatenated string of all trusted CA certificates
static bool hasConfigId(const QString &txt)
Returns whether a string includes an authcfg ID token.
bool removeAllAuthenticationConfigs()
Clear all authentication configs from table in database and from provider caches.
QgsAuthCertUtils::CertTrustPolicy certificateTrustPolicy(const QSslCertificate &cert)
certificateTrustPolicy get trust policy for a particular certificate cert
static bool passwordHelperLoggingEnabled()
Password helper logging enabled getter.
QgsAuthConfigurationStorageRegistry * authConfigurationStorageRegistry() const
Returns the authentication configuration storage registry.
bool rebuildCertTrustCache()
Rebuild certificate authority cache.
Q_DECL_DEPRECATED const QString authenticationDatabasePath() const
The standard authentication database file in ~/.qgis3/ or defined location.
static const QList< QSslCertificate > systemRootCAs()
systemRootCAs get root system certificate authorities
bool removeCertAuthority(const QSslCertificate &cert)
Remove a certificate authority.
const QList< QSslCertificate > trustedCaCerts(bool includeinvalid=false)
trustedCaCerts get list of all trusted CA certificates
bool existsCertAuthority(const QSslCertificate &cert)
Check if a certificate authority exists.
const QMap< QString, QSslCertificate > mappedDatabaseCAs()
mappedDatabaseCAs get sha1-mapped database-stored certificate authorities
bool importAuthenticationConfigsFromXml(const QString &filename, const QString &password=QString(), bool overwrite=false)
Import authentication configurations from an XML file.
bool configIdUnique(const QString &id) const
Verify if provided authentication id is unique.
static const QgsSettingsEntryBool * settingsGenerateRandomPasswordForPasswordHelper
QStringList configIds() const
Gets list of authentication ids from database.
QString authManTag() const
Simple text tag describing authentication system for message logs.
bool loadAuthenticationConfig(const QString &authcfg, QgsAuthMethodConfig &mconfig, bool full=false)
Load an authentication config from the database into subclass.
QgsAuthCertUtils::CertTrustPolicy certTrustPolicy(const QSslCertificate &cert)
certTrustPolicy get whether certificate cert is trusted by user
bool masterPasswordHashInDatabase() const
Verify a password hash existing in authentication database.
Q_DECL_DEPRECATED void messageOut(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level=QgsAuthManager::INFO) const
Custom logging signal to relay to console output and QgsMessageLog.
QgsAuthConfigurationStorageDb * defaultDbStorage() const
Transitional proxy to the first ready storage of database type.
bool updateNetworkProxy(QNetworkProxy &proxy, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkProxy with an authentication config.
const QSslCertificate certAuthority(const QString &id)
Gets a certificate authority by id (sha hash).
void passwordHelperSuccess()
Signals emitted on password helper success, mainly used in the tests to exit main application loop.
bool registerCoreAuthMethods()
Instantiate and register existing C++ core authentication methods from plugins.
bool passwordHelperDelete()
Delete master password from wallet.
~QgsAuthManager() override
void dumpIgnoredSslErrorsCache_()
Utility function to dump the cache for debug purposes.
const QList< QSslCertificate > databaseCAs()
databaseCAs get database-stored certificate authorities
void messageLog(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level=Qgis::MessageLevel::Info) const
Custom logging signal to relay to console output and QgsMessageLog.
bool backupAuthenticationDatabase(QString *backuppath=nullptr)
Close connection to current authentication database and back it up.
void authDatabaseEraseRequested()
Emitted when a user has indicated they may want to erase the authentication db.
void passwordHelperFailure()
Signals emitted on password helper failure, mainly used in the tests to exit main application loop.
bool existsSslCertCustomConfig(const QString &id, const QString &hostport)
Check if SSL certificate custom config exists.
bool existsAuthSetting(const QString &key)
Check if an authentication setting exists.
void clearCachedConfig(const QString &authcfg)
Clear an authentication config from its associated authentication method cache.
void clearMasterPassword()
Clear supplied master password.
bool updateNetworkRequest(QNetworkRequest &request, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkRequest with an authentication config.
bool createAndStoreRandomMasterPasswordInKeyChain()
Creates a new securely seeded random password and stores it in the system keychain as the new master ...
const QList< QSslCertificate > certIdentities()
certIdentities get certificate identities
bool storeCertAuthority(const QSslCertificate &cert)
Store a certificate authority.
QStringList certIdentityIds() const
certIdentityIds get list of certificate identity ids from database
bool removeCertTrustPolicies(const QList< QSslCertificate > &certs)
Remove a group certificate authorities.
QgsAuthMethod * authMethod(const QString &authMethodKey)
Gets authentication method from the config/provider cache via its key.
bool updateDataSourceUriItems(QStringList &connectionItems, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QgsDataSourceUri with an authentication config.
void setup(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
Sets up the authentication manager configuration.
const QString passwordHelperErrorMessage()
Error message getter.
Q_DECL_DEPRECATED QSqlDatabase authDatabaseConnection() const
Sets up the application instance of the authentication database connection.
void updateConfigAuthMethods()
Sync the confg/authentication method cache with what is in database.
bool storeSslCertCustomConfig(const QgsAuthConfigSslServer &config)
Store an SSL certificate custom config.
static void setPasswordHelperLoggingEnabled(bool enabled)
Password helper logging enabled setter.
bool ensureInitialized() const
Performs lazy initialization of the authentication framework, if it has not already been done.
const QgsAuthConfigSslServer sslCertCustomConfigByHost(const QString &hostport)
sslCertCustomConfigByHost get an SSL certificate custom config by hostport (host:port)
bool updateAuthenticationConfig(const QgsAuthMethodConfig &config)
Update an authentication config in the database.
bool existsCertIdentity(const QString &id)
Check if a certificate identity exists.
const QString authenticationDatabaseUri() const
Returns the authentication database connection URI.
static const QgsSettingsEntryBool * settingsUsingGeneratedRandomPassword
bool resetMasterPassword(const QString &newpass, const QString &oldpass, bool keepbackup, QString *backuppath=nullptr)
Reset the master password to a new one, then re-encrypts all previous configs with the new password.
QStringList authMethodsKeys(const QString &dataprovider=QString())
Gets keys of supported authentication methods.
bool passwordHelperSync()
Store the password manager into the wallet.
bool masterPasswordIsSet() const
Whether master password has be input and verified, i.e. authentication database is accessible.
const QString methodConfigTableName() const
Returns the database table from the first ready storage that stores authentication configs,...
static QgsAuthManager * instance()
Enforce singleton pattern.
void masterPasswordVerified(bool verified)
Emitted when a password has been verify (or not).
bool setMasterPassword(bool verify=false)
Main call to initially set or continually check master password is set.
bool storeCertAuthorities(const QList< QSslCertificate > &certs)
Store multiple certificate authorities.
bool removeSslCertCustomConfig(const QString &id, const QString &hostport)
Remove an SSL certificate custom config.
bool updateNetworkReply(QNetworkReply *reply, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkReply with an authentication config (used to skip known SSL errors,...
bool rebuildTrustedCaCertsCache()
Rebuild trusted certificate authorities cache.
const QgsAuthMethodMetadata * authMethodMetadata(const QString &authMethodKey)
Gets authentication method metadata via its key.
bool removeAuthenticationConfig(const QString &authcfg)
Remove an authentication config in the database.
bool removeCertTrustPolicy(const QSslCertificate &cert)
Remove a certificate authority.
const QString authenticationDatabaseUriStripped() const
Returns the authentication database connection URI with the password stripped.
QgsAuthMethod::Expansions supportedAuthMethodExpansions(const QString &authcfg)
Gets supported authentication method expansion(s), e.g.
const QgsAuthConfigSslServer sslCertCustomConfig(const QString &id, const QString &hostport)
sslCertCustomConfig get an SSL certificate custom config by id (sha hash) and hostport (host:port)
QgsAuthMethodConfigsMap availableAuthMethodConfigs(const QString &dataprovider=QString())
Gets mapping of authentication config ids and their base configs (not decrypted data).
bool masterPasswordSame(const QString &password) const
Check whether supplied password is the same as the one already set.
static const QString AUTH_PASSWORD_HELPER_DISPLAY_NAME
The display name of the password helper (platform dependent).
bool storeAuthenticationConfig(QgsAuthMethodConfig &mconfig, bool overwrite=false)
Store an authentication config in the database.
bool verifyStoredPasswordHelperPassword()
Verify the password stored in the password helper.
bool removeCertIdentity(const QString &id)
Remove a certificate identity.
static QString passwordHelperDisplayName(bool titleCase=false)
Returns a translated display name of the password helper (platform dependent).
bool resetMasterPasswordUsingStoredPasswordHelper(const QString &newPassword, bool keepBackup, QString *backupPath=nullptr)
Reset the master password to a new one, hen re-encrypts all previous configs with the new password.
QString configAuthMethodKey(const QString &authcfg) const
Gets key of authentication method associated with config ID.
Configuration storage class for authentication method configurations.
bool isValid(bool validateid=false) const
Whether the configuration is valid.
bool readXml(const QDomElement &element)
from a DOM element.
const QString configString() const
The extended configuration, as stored and retrieved from the authentication database.
const QString id() const
Gets 'authcfg' 7-character alphanumeric ID of the config.
void loadConfigString(const QString &configstr)
Load existing extended configuration.
bool writeXml(QDomElement &parentElement, QDomDocument &document)
Stores the configuration in a DOM.
void setId(const QString &id)
Sets auth config ID.
const QgsAuthMethodMetadata * authMethodMetadata(const QString &authMethodKey) const
Returns metadata of the auth method or nullptr if not found.
static QgsAuthMethodRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QStringList authMethodList() const
Returns list of available auth methods by their keys.
Abstract base class for authentication method plugins.
virtual bool updateNetworkProxy(QNetworkProxy &proxy, const QString &authcfg, const QString &dataprovider=QString())
Update proxy settings with authentication components.
virtual bool updateNetworkRequest(QNetworkRequest &request, const QString &authcfg, const QString &dataprovider=QString())
Update a network request with authentication components.
QgsAuthMethod::Expansions supportedExpansions() const
Flags that represent the update points (where authentication configurations are expanded) supported b...
virtual void clearCachedConfig(const QString &authcfg)=0
Clear any cached configuration.
virtual void updateMethodConfig(QgsAuthMethodConfig &mconfig)=0
Update an authentication configuration in place.
virtual bool updateNetworkReply(QNetworkReply *reply, const QString &authcfg, const QString &dataprovider=QString())
Update a network reply with authentication components.
virtual bool updateDataSourceUriItems(QStringList &connectionItems, const QString &authcfg, const QString &dataprovider=QString())
Update data source connection items with authentication components.
QFlags< Expansion > Expansions
static QgsCredentials * instance()
retrieves instance
bool getMasterPassword(QString &password, bool stored=false)
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
Custom exception class which is raised when an operation is not supported.
Scoped object for logging of the runtime for a single operation or group of operations.
A boolean settings entry.
static QgsSettingsTreeNode * sTreeAuthentication
Stores settings for use within QGIS.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
QHash< QString, QgsAuthMethodConfig > QgsAuthMethodConfigsMap
QHash< QString, QgsAuthMethod * > QgsAuthMethodsMap
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)