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#if defined( Q_OS_MAC )
89#elif defined( Q_OS_WIN )
91#elif defined( Q_OS_LINUX )
101 static QMutex sMutex;
102 QMutexLocker locker( &sMutex );
117 mMutex = std::make_unique<QRecursiveMutex>();
118 mMasterPasswordMutex = std::make_unique<QRecursiveMutex>();
135 QMutexLocker locker( mMutex.get() );
140 return storage->authDatabaseConnection();
145 return QSqlDatabase();
158 const QList<QgsAuthConfigurationStorage *> storages { storageRegistry->
readyStorages() };
161 if (
auto dbStorage = qobject_cast<QgsAuthConfigurationStorageDb *>( storage ) )
165 return dbStorage->quotedQualifiedIdentifier( dbStorage->methodConfigTableName() );
182 const auto drivers { QSqlDatabase::drivers() };
183 for (
const QString &driver : std::as_const( drivers ) )
185 if ( driver != ( u
"QSQLITE"_s ) && driver != ( u
"QSPATIALITE"_s ) && uri.startsWith( driver ) )
200 return mAuthDatabaseConnectionUri;
209 QRegularExpression re( u
"password=(.*)"_s );
210 QString uri = mAuthDatabaseConnectionUri;
211 return uri.replace( re, u
"password=*****"_s );
221 mAuthDatabaseConnectionUri = authDatabasePath.startsWith(
"QSQLITE://"_L1 ) ? authDatabasePath : u
"QSQLITE://"_s + authDatabasePath;
222 return initPrivate( pluginPath );
224 Q_UNUSED( pluginPath )
225 Q_UNUSED( authDatabasePath )
233 static QRecursiveMutex sInitializationMutex;
234 static bool sInitialized =
false;
236 sInitializationMutex.lock();
239 sInitializationMutex.unlock();
240 return mLazyInitResult;
243 mLazyInitResult =
const_cast< QgsAuthManager *
>( this )->initPrivate( mPluginPath );
245 sInitializationMutex.unlock();
247 return mLazyInitResult;
253static char *sPassFileEnv =
nullptr;
255bool QgsAuthManager::initPrivate(
const QString &pluginPath )
265 mQcaInitializer = std::make_unique<QCA::Initializer>( QCA::Practical, 256 );
268 QCA::scanForPlugins();
270 QgsDebugMsgLevel( u
"QCA Plugin Diagnostics Context: %1"_s.arg( QCA::pluginDiagnosticText() ), 2 );
271 QStringList capabilities;
273 capabilities = QCA::supportedFeatures();
274 QgsDebugMsgLevel( u
"QCA supports: %1"_s.arg( capabilities.join(
"," ) ), 2 );
277 if ( !QCA::isSupported(
"cert", u
"qca-ossl"_s ) )
279 mAuthDisabled =
true;
280 mAuthDisabledMessage = tr(
"QCA's OpenSSL plugin (qca-ossl) is missing" );
284 QgsDebugMsgLevel( u
"Prioritizing qca-ossl over all other QCA providers..."_s, 2 );
285 const QCA::ProviderList provds = QCA::providers();
287 for ( QCA::Provider *p : provds )
289 QString pn = p->name();
291 if ( pn !=
"qca-ossl"_L1 )
293 pr = QCA::providerPriority( pn ) + 1;
295 QCA::setProviderPriority( pn, pr );
296 prlist << u
"%1:%2"_s.arg( pn ).arg( QCA::providerPriority( pn ) );
298 QgsDebugMsgLevel( u
"QCA provider priorities: %1"_s.arg( prlist.join(
", " ) ), 2 );
305 QgsDebugMsgLevel( u
"Authentication methods found: %1"_s.arg( methods.join(
", " ) ), 2 );
307 if ( methods.isEmpty() )
309 mAuthDisabled =
true;
310 mAuthDisabledMessage = tr(
"No authentication method plugins found" );
316 mAuthDisabled =
true;
317 mAuthDisabledMessage = tr(
"No authentication method plugins could be loaded" );
321 QgsDebugMsgLevel( u
"Auth database URI: %1"_s.arg( mAuthDatabaseConnectionUri ), 2 );
325 if ( !sqliteDbPath.isEmpty() )
329 else if ( !mAuthDatabaseConnectionUri.isEmpty() )
333 QgsAuthConfigurationStorageDb *storage =
new QgsAuthConfigurationStorageDb( mAuthDatabaseConnectionUri );
343 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
352 const QString err = tr(
"Failed to initialize storage %1: %2" ).arg( storage->
name(), storage->
lastError() );
372 QString passpath( sPassFileEnv );
373 free( sPassFileEnv );
374 sPassFileEnv =
nullptr;
377 QFile passfile( passpath );
378 if ( passfile.exists() && passfile.open( QIODevice::ReadOnly | QIODevice::Text ) )
380 QTextStream passin( &passfile );
381 while ( !passin.atEnd() )
383 masterpass = passin.readLine();
388 if ( !masterpass.isEmpty() )
392 QgsDebugMsgLevel( u
"Authentication master password set from QGIS_AUTH_PASSWORD_FILE"_s, 2 );
396 QgsDebugError(
"QGIS_AUTH_PASSWORD_FILE set, but FAILED to set password using: " + passpath );
402 QgsDebugError(
"QGIS_AUTH_PASSWORD_FILE set, but FAILED to read password from: " + passpath );
413 Q_UNUSED( pluginPath )
421 mPluginPath = pluginPath;
422 mAuthDatabaseConnectionUri = authDatabasePath;
424 const char *p = getenv(
"QGIS_AUTH_PASSWORD_FILE" );
427 sPassFileEnv = qstrdup( p );
432 putenv(
"QGIS_AUTH_PASSWORD_FILE" );
434 unsetenv(
"QGIS_AUTH_PASSWORD_FILE" );
438 Q_UNUSED( pluginPath )
439 Q_UNUSED( authDatabasePath )
443QString QgsAuthManager::generatePassword()
446 QRandomGenerator generator = QRandomGenerator::securelySeeded();
449 static const QString sPwChars = u
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-{}[]"_s;
450 for (
int i = 0; i < pw.size(); ++i )
452 pw[i] = sPwChars.at( generator.bounded( 0, sPwChars.length() ) );
467 QgsDebugError( u
"Authentication system DISABLED: QCA's qca-ossl (OpenSSL) plugin is missing"_s );
469 return mAuthDisabled;
480 return tr(
"Authentication system is DISABLED:\n%1" ).arg( mAuthDisabledMessage );
489 QMutexLocker locker( mMasterPasswordMutex.get() );
493 if ( mScheduledDbErase )
499 if ( !mMasterPass.isEmpty() )
505 const QString newPassword = generatePassword();
506 if ( passwordHelperWrite( newPassword ) )
508 mMasterPass = newPassword;
540 QString path = mAuthDatabaseConnectionUri;
541 if ( path.startsWith( u
"QSQLITE://"_s, Qt::CaseSensitivity::CaseInsensitive ) )
543 path = path.mid( 10 );
545 else if ( path.startsWith( u
"QSPATIALITE://"_s, Qt::CaseSensitivity::CaseInsensitive ) )
547 path = path.mid( 14 );
550 return QDir::cleanPath( path );
570 QMutexLocker locker( mMasterPasswordMutex.get() );
574 if ( mScheduledDbErase )
577 if ( mMasterPass.isEmpty() )
580 if ( !masterPasswordInput() )
609 QMutexLocker locker( mMutex.get() );
613 if ( mScheduledDbErase )
617 QString prevpass = QString( mMasterPass );
621 mMasterPass = prevpass;
622 const char *err = QT_TR_NOOP(
"Master password set: FAILED to verify, reset to previous" );
628 QgsDebugMsgLevel( u
"Master password set: SUCCESS%1"_s.arg( verify ?
" and verified" :
"" ), 2 );
646 if ( !masterPasswordRowsInDb( rows ) )
648 const char *err = QT_TR_NOOP(
"Master password: FAILED to access database" );
656 QgsDebugMsgLevel( u
"Master password: %1 rows in database"_s.arg( rows ), 2 );
660 const char *err = QT_TR_NOOP(
"Master password: FAILED to find just one master password record in database" );
667 else if ( rows == 1 )
669 if ( !masterPasswordCheckAgainstDb( compare ) )
671 if ( compare.isNull() )
673 const char *err = QT_TR_NOOP(
"Master password: FAILED to verify against hash in database" );
682 if ( mPassTries >= 5 )
684 mAuthDisabled =
true;
685 const char *err = QT_TR_NOOP(
"Master password: failed 5 times authentication system DISABLED" );
693 QgsDebugMsgLevel( u
"Master password: verified against hash in database"_s, 2 );
694 if ( compare.isNull() )
698 else if ( compare.isNull() )
700 if ( !masterPasswordStoreInDb() )
702 const char *err = QT_TR_NOOP(
"Master password: hash FAILED to be stored in database" );
714 if ( !masterPasswordCheckAgainstDb() )
716 const char *err = QT_TR_NOOP(
"Master password: FAILED to verify against hash in database" );
726 QgsDebugMsgLevel( u
"Master password: verified against hash in database"_s, 2 );
743 return !mMasterPass.isEmpty();
754 return mMasterPass == pass;
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() )
1262 if ( i.value() && ( i.value()->supportedDataProviders().contains( u
"all"_s ) || i.value()->supportedDataProviders().contains( dataprovider ) ) )
1264 filteredmap.insert( i.key(), i.value() );
1270 Q_UNUSED( dataprovider )
1276QWidget *QgsAuthManager::authMethodEditWidget(
const QString &authMethodKey, QWidget *parent )
1282 return method->editWidget( parent );
1314 QMutexLocker locker( mMutex.get() );
1321 const char *err = QT_TR_NOOP(
"Store config: FAILED because config is invalid" );
1327 QString uid = config.
id();
1328 bool passedinID = !uid.isEmpty();
1329 if ( uid.isEmpty() )
1337 const char *err = QT_TR_NOOP(
"Store config: FAILED because pre-defined config ID %1 is not unique" );
1345 const char *err = QT_TR_NOOP(
"Store config: FAILED because pre-defined config ID %1 could not be removed" );
1354 if ( configstring.isEmpty() )
1356 const char *err = QT_TR_NOOP(
"Store config: FAILED because config string is empty" );
1364 if ( defaultStorage->isEncrypted() )
1371 configCopy.
setId( uid );
1372 if ( !defaultStorage->storeMethodConfig( configCopy, configstring ) )
1386 config.
setId( uid );
1390 QgsDebugMsgLevel( u
"Store config SUCCESS for authcfg: %1"_s.arg( uid ), 2 );
1394 Q_UNUSED( overwrite )
1404 QMutexLocker locker( mMutex.get() );
1409 if ( !config.
isValid(
true ) )
1411 const char *err = QT_TR_NOOP(
"Update config: FAILED because config is invalid" );
1418 if ( configstring.isEmpty() )
1420 const char *err = QT_TR_NOOP(
"Update config: FAILED because config is empty" );
1451 if ( storages.empty() )
1462 QgsDebugMsgLevel( u
"Update config SUCCESS for authcfg: %1"_s.arg( config.
id() ), 2 );
1482 QMutexLocker locker( mMutex.get() );
1494 if ( !config.
isValid(
true ) || ( full && payload.isEmpty() ) )
1517 QgsDebugError( u
"Update of authcfg %1 FAILED for auth method %2"_s.arg( authcfg, authMethodKey ) );
1520 QgsDebugMsgLevel( u
"Load %1 config SUCCESS for authcfg: %2"_s.arg( full ?
"full" :
"base", authcfg ), 2 );
1525 if ( storages.empty() )
1548 QMutexLocker locker( mMutex.get() );
1552 if ( authcfg.isEmpty() )
1578 if ( storages.empty() )
1600 if ( filename.isEmpty() )
1603 QDomDocument document( u
"qgis_authentication"_s );
1604 QDomElement root = document.createElement( u
"qgis_authentication"_s );
1605 document.appendChild( root );
1608 if ( !password.isEmpty() )
1613 root.setAttribute( u
"salt"_s, salt );
1614 root.setAttribute( u
"hash"_s, hash );
1615 root.setAttribute( u
"civ"_s, civ );
1618 QDomElement configurations = document.createElement( u
"configurations"_s );
1619 for (
const QString &authcfg : authcfgs )
1626 authMethodConfig.
writeXml( configurations, document );
1629 if ( !password.isEmpty() )
1631 QString configurationsString;
1632 QTextStream ts( &configurationsString );
1633 configurations.save( ts, 2 );
1634 root.appendChild( document.createTextNode(
QgsAuthCrypto::encrypt( password, civ, configurationsString ) ) );
1638 root.appendChild( configurations );
1641 QFile file( filename );
1642 if ( !file.open( QFile::WriteOnly | QIODevice::Truncate ) )
1645 QTextStream ts( &file );
1646 document.save( ts, 2 );
1650 Q_UNUSED( filename )
1651 Q_UNUSED( authcfgs )
1652 Q_UNUSED( password )
1662 QFile file( filename );
1663 if ( !file.open( QFile::ReadOnly ) )
1668 QDomDocument document( u
"qgis_authentication"_s );
1669 if ( !document.setContent( &file ) )
1676 QDomElement root = document.documentElement();
1677 if ( root.tagName() !=
"qgis_authentication"_L1 )
1682 QDomElement configurations;
1683 if ( root.hasAttribute( u
"salt"_s ) )
1685 QString salt = root.attribute( u
"salt"_s );
1686 QString hash = root.attribute( u
"hash"_s );
1687 QString civ = root.attribute( u
"civ"_s );
1692 configurations = document.firstChild().toElement();
1696 configurations = root.firstChildElement( u
"configurations"_s );
1699 QDomElement configuration = configurations.firstChildElement();
1700 while ( !configuration.isNull() )
1703 ( void ) authMethodConfig.
readXml( configuration );
1706 configuration = configuration.nextSiblingElement();
1710 Q_UNUSED( filename )
1711 Q_UNUSED( password )
1712 Q_UNUSED( overwrite )
1722 QMutexLocker locker( mMutex.get() );
1728 if ( defaultStorage->clearMethodConfigs() )
1737 QgsDebugMsgLevel( u
"FAILED to remove all configs from the default storage"_s, 2 );
1757 QMutexLocker locker( mMutex.get() );
1761 const char *err = QT_TR_NOOP(
"The authentication storage is not filesystem-based" );
1769 const char *err = QT_TR_NOOP(
"No authentication database file found" );
1779 if ( authConn.isValid() && authConn.isOpen() )
1783 QString datestamp( QDateTime::currentDateTime().toString( u
"yyyy-MM-dd-hhmmss"_s ) );
1785 dbbackup.replace(
".db"_L1, u
"_%1.db"_s.arg( datestamp ) );
1789 const char *err = QT_TR_NOOP(
"Could not back up authentication database" );
1796 *backuppath = dbbackup;
1801 Q_UNUSED( backuppath )
1811 QMutexLocker locker( mMutex.get() );
1822 if ( backuppath && !dbbackup.isEmpty() )
1823 *backuppath = dbbackup;
1827 if ( defaultStorage->erase() )
1829 mMasterPass = QString();
1856 Q_UNUSED( backuppath )
1874 QgsDebugError( u
"Network request updating not supported by authcfg: %1"_s.arg( authcfg ) );
1889 Q_UNUSED( dataprovider )
1907 QgsDebugMsgLevel( u
"Network reply updating not supported by authcfg: %1"_s.arg( authcfg ), 3 );
1923 Q_UNUSED( dataprovider )
1941 QgsDebugError( u
"Data source URI updating not supported by authcfg: %1"_s.arg( authcfg ) );
1955 Q_UNUSED( connectionItems )
1957 Q_UNUSED( dataprovider )
1975 QgsDebugError( u
"Proxy updating not supported by authcfg: %1"_s.arg( authcfg ) );
1984 QgsDebugMsgLevel( u
"Proxy updated successfully from authcfg: %1"_s.arg( authcfg ), 2 );
1992 Q_UNUSED( dataprovider )
2002 QMutexLocker locker( mMutex.get() );
2003 if ( key.isEmpty() )
2006 QString storeval( value.toString() );
2029 if ( !defaultStorage->storeAuthSetting( key, storeval ) )
2054 QMutexLocker locker( mMutex.get() );
2055 if ( key.isEmpty() )
2061 QVariant value = defaultValue;
2069 if ( !storeval.isEmpty() )
2080 if ( storages.empty() )
2088 Q_UNUSED( defaultValue )
2099 QMutexLocker locker( mMutex.get() );
2100 if ( key.isEmpty() )
2114 if ( storages.empty() )
2131 QMutexLocker locker( mMutex.get() );
2132 if ( key.isEmpty() )
2159 if ( storages.empty() )
2179 QMutexLocker locker( mMutex.get() );
2185 mCustomConfigByHostCache.clear();
2186 mHasCheckedIfCustomConfigByHostExists =
false;
2201 QMutexLocker locker( mMutex.get() );
2202 if ( cert.isNull() )
2216 QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
2221 QgsDebugError( u
"Store certificate identity: FAILED to remove pre-existing certificate identity %1"_s.arg(
id ) );
2229 if ( !defaultStorage->storeCertIdentity( cert, keypem ) )
2253 QMutexLocker locker( mMutex.get() );
2255 QSslCertificate cert;
2266 if ( !cert.isNull() )
2272 if ( storages.empty() )
2280 return QSslCertificate();
2288 QMutexLocker locker( mMutex.get() );
2289 QPair<QSslCertificate, QSslKey> bundle;
2304 if ( encryptedBundle.first.isNull() )
2306 QgsDebugError( u
"Certificate identity bundle is null for id: %1"_s.arg(
id ) );
2309 QSslKey key(
QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), encryptedBundle.second ).toLatin1(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey );
2312 QgsDebugError( u
"Certificate identity bundle: FAILED to create private key"_s );
2315 bundle = qMakePair( encryptedBundle.first, key );
2320 if ( storages.empty() )
2334 QMutexLocker locker( mMutex.get() );
2336 if ( QgsAuthCertUtils::certIsViable( bundle.first ) && !bundle.second.isNull() )
2338 return QStringList() << QString( bundle.first.toPem() ) << QString( bundle.second.toPem() );
2340 return QStringList();
2343 return QStringList();
2352 QMutexLocker locker( mMutex.get() );
2353 QList<QSslCertificate> certs;
2360 const QList<QSslCertificate> storageCerts = storage->
certIdentities();
2362 for (
const QSslCertificate &cert : std::as_const( storageCerts ) )
2364 if ( !certs.contains( cert ) )
2366 certs.append( cert );
2375 if ( storages.empty() )
2382 return QList<QSslCertificate>();
2391 QMutexLocker locker( mMutex.get() );
2405 for (
const QString &
id : std::as_const( storageIds ) )
2407 if ( !ids.contains(
id ) )
2420 return QStringList();
2429 QMutexLocker locker( mMutex.get() );
2444 if ( storages.empty() )
2461 QMutexLocker locker( mMutex.get() );
2484 if ( storages.empty() )
2502 QMutexLocker locker( mMutex.get() );
2510 const QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
2514 QgsDebugError( u
"Store SSL certificate custom config: FAILED to remove pre-existing config %1"_s.arg(
id ) );
2520 if ( !defaultStorage->storeSslCertCustomConfig( config ) )
2533 mCustomConfigByHostCache.clear();
2547 QMutexLocker locker( mMutex.get() );
2550 if (
id.isEmpty() || hostport.isEmpty() )
2552 QgsDebugError( u
"Passed config ID or host:port is empty"_s );
2576 if ( storages.empty() )
2585 Q_UNUSED( hostport )
2596 if ( hostport.isEmpty() )
2601 QMutexLocker locker( mMutex.get() );
2603 if ( mCustomConfigByHostCache.contains( hostport ) )
2604 return mCustomConfigByHostCache.value( hostport );
2614 mCustomConfigByHostCache.insert( hostport, config );
2618 if ( storages.empty() )
2625 Q_UNUSED( hostport )
2635 QMutexLocker locker( mMutex.get() );
2636 QList<QgsAuthConfigSslServer> configs;
2647 for (
const auto &config : std::as_const( storageConfigs ) )
2649 const QString id( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ) );
2650 const QString hostPort = config.sslHostPort();
2651 const QString shaHostPort( u
"%1:%2"_s.arg(
id, hostPort ) );
2652 if ( !ids.contains( shaHostPort ) )
2654 ids.append( shaHostPort );
2655 configs.append( config );
2664 if ( storages.empty() )
2671 return QList<QgsAuthConfigSslServer>();
2680 QMutexLocker locker( mMutex.get() );
2681 if (
id.isEmpty() || hostPort.isEmpty() )
2683 QgsDebugError( u
"Passed config ID or host:port is empty"_s );
2698 if ( storages.empty() )
2706 Q_UNUSED( hostPort )
2716 QMutexLocker locker( mMutex.get() );
2717 if (
id.isEmpty() || hostport.isEmpty() )
2719 QgsDebugError( u
"Passed config ID or host:port is empty"_s );
2723 mCustomConfigByHostCache.clear();
2737 const QString shaHostPort( u
"%1:%2"_s.arg(
id, hostport ) );
2738 if ( mIgnoredSslErrorsCache.contains( shaHostPort ) )
2740 mIgnoredSslErrorsCache.remove( shaHostPort );
2746 if ( storages.empty() )
2754 Q_UNUSED( hostport )
2765 QMutexLocker locker( mMutex.get() );
2766 if ( !mIgnoredSslErrorsCache.isEmpty() )
2769 QHash<QString, QSet<QSslError::SslError> >::const_iterator i = mIgnoredSslErrorsCache.constBegin();
2770 while ( i != mIgnoredSslErrorsCache.constEnd() )
2773 for (
auto err : i.value() )
2775 errs << QgsAuthCertUtils::sslErrorEnumString( err );
2793 QMutexLocker locker( mMutex.get() );
2800 QString shahostport( u
"%1:%2"_s.arg( QgsAuthCertUtils::shaHexForCert( config.
sslCertificate() ).trimmed(), config.
sslHostPort().trimmed() ) );
2801 if ( mIgnoredSslErrorsCache.contains( shahostport ) )
2803 mIgnoredSslErrorsCache.remove( shahostport );
2806 if ( !errenums.isEmpty() )
2808 mIgnoredSslErrorsCache.insert( shahostport, QSet<QSslError::SslError>( errenums.begin(), errenums.end() ) );
2809 QgsDebugMsgLevel( u
"Update of ignored SSL errors cache SUCCEEDED for sha:host:port = %1"_s.arg( shahostport ), 2 );
2814 QgsDebugMsgLevel( u
"No ignored SSL errors to cache for sha:host:port = %1"_s.arg( shahostport ), 2 );
2827 QMutexLocker locker( mMutex.get() );
2828 const thread_local QRegularExpression rx( QRegularExpression::anchoredPattern(
"\\S+:\\S+:\\d+" ) );
2829 if ( !rx.match( shahostport ).hasMatch() )
2832 "Passed shahostport does not match \\S+:\\S+:\\d+, "
2833 "e.g. 74a4ef5ea94512a43769b744cda0ca5049a72491:www.example.com:443"
2838 if ( mIgnoredSslErrorsCache.contains( shahostport ) )
2840 mIgnoredSslErrorsCache.remove( shahostport );
2843 if ( errors.isEmpty() )
2849 QSet<QSslError::SslError> errs;
2850 for (
const auto &error : errors )
2852 if ( error.error() == QSslError::NoError )
2855 errs.insert( error.error() );
2858 if ( errs.isEmpty() )
2860 QgsDebugError( u
"Passed errors list does not contain errors"_s );
2864 mIgnoredSslErrorsCache.insert( shahostport, errs );
2866 QgsDebugMsgLevel( u
"Update of ignored SSL errors cache SUCCEEDED for sha:host:port = %1"_s.arg( shahostport ), 2 );
2870 Q_UNUSED( shahostport )
2881 QMutexLocker locker( mMutex.get() );
2882 QHash<QString, QSet<QSslError::SslError> > prevcache( mIgnoredSslErrorsCache );
2883 QHash<QString, QSet<QSslError::SslError> > nextcache;
2893 for (
const auto &config : std::as_const( customConfigs ) )
2895 const QString shaHostPort( u
"%1:%2"_s.arg( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ), config.sslHostPort() ) );
2896 if ( !ids.contains( shaHostPort ) )
2898 ids.append( shaHostPort );
2899 if ( !config.sslIgnoredErrorEnums().isEmpty() )
2901 nextcache.insert( shaHostPort, QSet<QSslError::SslError>( config.sslIgnoredErrorEnums().cbegin(), config.sslIgnoredErrorEnums().cend() ) );
2903 if ( prevcache.contains( shaHostPort ) )
2905 prevcache.remove( shaHostPort );
2915 if ( !prevcache.isEmpty() )
2918 QHash<QString, QSet<QSslError::SslError> >::const_iterator i = prevcache.constBegin();
2919 while ( i != prevcache.constEnd() )
2921 nextcache.insert( i.key(), i.value() );
2926 if ( nextcache != mIgnoredSslErrorsCache )
2928 mIgnoredSslErrorsCache.clear();
2929 mIgnoredSslErrorsCache = nextcache;
2935 QgsDebugMsgLevel( u
"Rebuild of ignored SSL errors cache SAME AS BEFORE"_s, 2 );
2948 QMutexLocker locker( mMutex.get() );
2949 if ( certs.isEmpty() )
2955 for (
const auto &cert : certs )
2972 QMutexLocker locker( mMutex.get() );
2975 if ( cert.isNull() )
2983 QgsDebugError( u
"Store certificate authority: FAILED to remove pre-existing certificate authority"_s );
2989 return defaultStorage->storeCertAuthority( cert );
3009 QMutexLocker locker( mMutex.get() );
3010 QSslCertificate emptycert;
3011 QSslCertificate cert;
3021 if ( !cert.isNull() )
3027 if ( storages.empty() )
3036 return QSslCertificate();
3045 QMutexLocker locker( mMutex.get() );
3046 if ( cert.isNull() )
3063 if ( storages.empty() )
3079 QMutexLocker locker( mMutex.get() );
3080 if ( cert.isNull() )
3108 if ( storages.empty() )
3123 return QSslConfiguration::systemCaCertificates();
3125 return QList<QSslCertificate>();
3134 QMutexLocker locker( mMutex.get() );
3135 QList<QSslCertificate> certs;
3136 QList<QSslCertificate> filecerts;
3145 QString cafile( cafileval.toString() );
3146 if ( !cafile.isEmpty() && QFile::exists( cafile ) )
3148 filecerts = QgsAuthCertUtils::certsFromFile( cafile );
3151 for (
const auto &cert : std::as_const( filecerts ) )
3153 if ( !allowinvalid.toBool() && ( cert.isBlacklisted() || cert.isNull() || cert.expiryDate() <= QDateTime::currentDateTime() || cert.effectiveDate() > QDateTime::currentDateTime() ) )
3158 if ( QgsAuthCertUtils::certificateIsAuthorityOrIssuer( cert ) )
3165 return QList<QSslCertificate>();
3174 QMutexLocker locker( mMutex.get() );
3179 QList<QSslCertificate> certs;
3183 const QList<QSslCertificate> storageCerts = storage->
caCerts();
3185 for (
const QSslCertificate &cert : std::as_const( storageCerts ) )
3187 if ( !certs.contains( cert ) )
3189 certs.append( cert );
3198 if ( storages.empty() )
3205 return QList<QSslCertificate>();
3213 QMutexLocker locker( mMutex.get() );
3214 return QgsAuthCertUtils::mapDigestToCerts(
databaseCAs() );
3222 QMutexLocker locker( mMutex.get() );
3223 mCaCertsCache.clear();
3229 bool res = !mCaCertsCache.isEmpty();
3243 QMutexLocker locker( mMutex.get() );
3244 if ( cert.isNull() )
3263 return defaultStorage->storeCertTrustPolicy( cert, policy );
3282 QMutexLocker locker( mMutex.get() );
3283 if ( cert.isNull() )
3301 if ( storages.empty() )
3318 QMutexLocker locker( mMutex.get() );
3319 if ( certs.empty() )
3325 for (
const auto &cert : certs )
3342 QMutexLocker locker( mMutex.get() );
3343 if ( cert.isNull() )
3371 if ( storages.empty() )
3388 QMutexLocker locker( mMutex.get() );
3389 if ( cert.isNull() )
3394 QString id( QgsAuthCertUtils::shaHexForCert( cert ) );
3399 if ( trustedids.contains(
id ) )
3403 else if ( untrustedids.contains(
id ) )
3424 return storeAuthSetting( u
"certdefaulttrust"_s,
static_cast< int >( policy ) );
3436 QMutexLocker locker( mMutex.get() );
3437 QVariant policy(
authSetting( u
"certdefaulttrust"_s ) );
3453 QMutexLocker locker( mMutex.get() );
3454 mCertTrustCache.clear();
3464 for (
auto it = trustedCerts.cbegin(); it != trustedCerts.cend(); ++it )
3466 const QString
id { it.key() };
3467 if ( !ids.contains(
id ) )
3488 if ( !storages.empty() )
3508 QMutexLocker locker( mMutex.get() );
3512 const QList<QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > &certpairs( mCaCertsCache.values() );
3514 QList<QSslCertificate> trustedcerts;
3515 for (
int i = 0; i < certpairs.size(); ++i )
3517 QSslCertificate cert( certpairs.at( i ).second );
3518 QString certid( QgsAuthCertUtils::shaHexForCert( cert ) );
3519 if ( trustedids.contains( certid ) )
3522 trustedcerts.append( cert );
3526 if ( !includeinvalid && !QgsAuthCertUtils::certIsViable( cert ) )
3528 trustedcerts.append( cert );
3533 QSslConfiguration sslconfig( QSslConfiguration::defaultConfiguration() );
3534 sslconfig.setCaCertificates( trustedcerts );
3535 QSslConfiguration::setDefaultConfiguration( sslconfig );
3537 return trustedcerts;
3539 Q_UNUSED( includeinvalid )
3540 return QList<QSslCertificate>();
3549 QMutexLocker locker( mMutex.get() );
3550 if ( trustedCAs.isEmpty() )
3552 if ( mTrustedCaCertsCache.isEmpty() )
3559 const QList<QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > &certpairs( mCaCertsCache.values() );
3561 QList<QSslCertificate> untrustedCAs;
3562 for (
int i = 0; i < certpairs.size(); ++i )
3564 QSslCertificate cert( certpairs.at( i ).second );
3565 if ( !trustedCAs.contains( cert ) )
3567 untrustedCAs.append( cert );
3570 return untrustedCAs;
3572 Q_UNUSED( trustedCAs )
3573 return QList<QSslCertificate>();
3582 QMutexLocker locker( mMutex.get() );
3597 QMutexLocker locker( mMutex.get() );
3600 return QByteArray();
3609 QMutexLocker locker( mMutex.get() );
3612 return passwordHelperWrite( mMasterPass );
3626 bool readOk =
false;
3627 const QString currentPass = passwordHelperRead( readOk );
3631 if ( !currentPass.isEmpty() && ( mPasswordHelperErrorCode == QKeychain::NoError ) )
3644#if defined( Q_OS_MAC )
3645 return titleCase ? QObject::tr(
"Keychain" ) : QObject::tr(
"keychain" );
3646#elif defined( Q_OS_WIN )
3647 return titleCase ? QObject::tr(
"Password Manager" ) : QObject::tr(
"password manager" );
3648#elif defined( Q_OS_LINUX )
3650 const QString desktopSession = qgetenv(
"DESKTOP_SESSION" );
3651 const QString currentDesktop = qgetenv(
"XDG_CURRENT_DESKTOP" );
3652 const QString gdmSession = qgetenv(
"GDMSESSION" );
3654 if ( desktopSession.contains(
"kde"_L1, Qt::CaseInsensitive ) || currentDesktop.contains(
"kde"_L1, Qt::CaseInsensitive ) || gdmSession.contains(
"kde"_L1, Qt::CaseInsensitive ) )
3656 return titleCase ? QObject::tr(
"Wallet" ) : QObject::tr(
"wallet" );
3659 return titleCase ? QObject::tr(
"Wallet/Key Ring" ) : QObject::tr(
"wallet/key ring" );
3661 return titleCase ? QObject::tr(
"Password Manager" ) : QObject::tr(
"password manager" );
3664 Q_UNUSED( titleCase )
3683 for (
const auto &authcfg : ids )
3708void QgsAuthManager::writeToConsole(
const QString &message,
const QString &tag,
Qgis::MessageLevel level )
3723 msg +=
"WARNING: "_L1;
3726 msg +=
"ERROR: "_L1;
3733 QTextStream out( stdout, QIODevice::WriteOnly );
3734 out << msg << Qt::endl;
3742void QgsAuthManager::tryToStartDbErase()
3747 ++mScheduledDbEraseRequestCount;
3749 int trycutoff = 90 / ( mScheduledDbEraseRequestWait ? mScheduledDbEraseRequestWait : 3 );
3750 if ( mScheduledDbEraseRequestCount >= trycutoff )
3753 QgsDebugMsgLevel( u
"authDatabaseEraseRequest emitting/scheduling canceled"_s, 2 );
3758 QgsDebugMsgLevel( u
"authDatabaseEraseRequest attempt (%1 of %2)"_s.arg( mScheduledDbEraseRequestCount ).arg( trycutoff ), 2 );
3764 mScheduledDbEraseRequestEmitted =
true;
3780 QMutexLocker locker( mMutex.get() );
3782 QMapIterator<QThread *, QMetaObject::Connection> iterator( mConnectedThreads );
3783 while ( iterator.hasNext() )
3786 QThread::disconnect( iterator.value() );
3797 qDeleteAll( mAuthMethods );
3802 if ( authConn.isValid() && authConn.isOpen() )
3806 QSqlDatabase::removeDatabase( u
"authentication.configs"_s );
3812 QMutexLocker locker( mMutex.get() );
3813 if ( !mAuthConfigurationStorageRegistry )
3815 mAuthConfigurationStorageRegistry = std::make_unique<QgsAuthConfigurationStorageRegistry>();
3817 return mAuthConfigurationStorageRegistry.get();
3821QString QgsAuthManager::passwordHelperName()
const
3824 return tr(
"Password Helper" );
3831void QgsAuthManager::passwordHelperLog(
const QString &msg )
const
3852 QKeychain::DeletePasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3855 job.setAutoDelete(
false );
3856 job.setKey( authPasswordHelperKeyName() );
3858 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3863 mPasswordHelperErrorCode = job.error();
3864 mPasswordHelperErrorMessage = tr(
"Delete password failed: %1." ).arg( job.errorString() );
3875 passwordHelperProcessError();
3882QString QgsAuthManager::passwordHelperRead(
bool &ok )
3891 QKeychain::ReadPasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3894 job.setAutoDelete(
false );
3895 job.setKey( authPasswordHelperKeyName() );
3897 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3902 mPasswordHelperErrorCode = job.error();
3903 mPasswordHelperErrorMessage = tr(
"Retrieving password from the %1 failed: %2." ).arg(
passwordHelperDisplayName(), job.errorString() );
3909 password = job.textData();
3911 if ( password.isEmpty() )
3913 mPasswordHelperErrorCode = QKeychain::EntryNotFound;
3925 passwordHelperProcessError();
3933bool QgsAuthManager::passwordHelperWrite(
const QString &password )
3938 Q_ASSERT( !password.isEmpty() );
3941 QKeychain::WritePasswordJob job( AUTH_PASSWORD_HELPER_FOLDER_NAME );
3942 QgsSettings settings;
3944 job.setAutoDelete(
false );
3945 job.setKey( authPasswordHelperKeyName() );
3946 job.setTextData( password );
3948 connect( &job, &QKeychain::Job::finished, &loop, &QEventLoop::quit );
3953 mPasswordHelperErrorCode = job.error();
3954 mPasswordHelperErrorMessage = tr(
"Storing password in the %1 failed: %2." ).arg(
passwordHelperDisplayName(), job.errorString() );
3961 passwordHelperClearErrors();
3966 passwordHelperProcessError();
3969 Q_UNUSED( password )
3991 enabled ? tr(
"Your %1 will be <b>used from now</b> on to store and retrieve the master password." ).arg(
passwordHelperDisplayName() )
3992 : tr(
"Your %1 will <b>not be used anymore</b> to store and retrieve the master password." ).arg(
passwordHelperDisplayName() )
4020void QgsAuthManager::passwordHelperClearErrors()
4023 mPasswordHelperErrorCode = QKeychain::NoError;
4024 mPasswordHelperErrorMessage.clear();
4028void QgsAuthManager::passwordHelperProcessError()
4033 if ( mPasswordHelperErrorCode == QKeychain::AccessDenied
4034 || mPasswordHelperErrorCode == QKeychain::AccessDeniedByUser
4035 || mPasswordHelperErrorCode == QKeychain::NoBackendAvailable
4036 || mPasswordHelperErrorCode == QKeychain::NotImplemented )
4042 mPasswordHelperErrorMessage = tr(
4043 "There was an error and integration with your %1 has been disabled. "
4044 "You can re-enable it at any time through the \"Utilities\" menu "
4045 "in the Authentication pane of the options dialog. %2"
4049 if ( mPasswordHelperErrorCode != QKeychain::NoError )
4055 passwordHelperClearErrors();
4060bool QgsAuthManager::masterPasswordInput()
4069 bool storedPasswordIsValid =
false;
4075 bool readOk =
false;
4076 pass = passwordHelperRead( readOk );
4077 if ( readOk && !pass.isEmpty() && ( mPasswordHelperErrorCode == QKeychain::NoError ) )
4083 storedPasswordIsValid =
true;
4098 if ( ok && !pass.isEmpty() && mMasterPass != pass )
4103 if ( !passwordHelperWrite( pass ) )
4116bool QgsAuthManager::masterPasswordRowsInDb(
int &rows )
const
4127 QMutexLocker locker( mMutex.get() );
4132 if ( storages.empty() )
4138 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4146 catch (
const QgsNotSupportedException &e )
4170 if ( !masterPasswordRowsInDb( rows ) )
4172 const char *err = QT_TR_NOOP(
"Master password: FAILED to access database" );
4178 return ( rows == 1 );
4184bool QgsAuthManager::masterPasswordCheckAgainstDb(
const QString &compare )
const
4197 const QList<QgsAuthConfigurationStorage::MasterPasswordConfig> passwords { defaultStorage->masterPasswords() };
4198 if ( passwords.size() == 0 )
4203 const QgsAuthConfigurationStorage::MasterPasswordConfig storedPassword { passwords.first() };
4206 catch (
const QgsNotSupportedException &e )
4224bool QgsAuthManager::masterPasswordStoreInDb()
const
4232 QString salt, hash, civ;
4240 return defaultStorage->storeMasterPassword( { salt, civ, hash } );
4242 catch (
const QgsNotSupportedException &e )
4259bool QgsAuthManager::masterPasswordClearDb()
4271 return defaultStorage->clearMasterPasswords();
4273 catch (
const QgsNotSupportedException &e )
4290const QString QgsAuthManager::masterPasswordCiv()
const
4302 const QList<QgsAuthConfigurationStorage::MasterPasswordConfig> passwords { defaultStorage->masterPasswords() };
4303 if ( passwords.size() == 0 )
4308 return passwords.first().civ;
4310 catch (
const QgsNotSupportedException &e )
4332 QStringList configKeys = QStringList();
4346 for (
auto it = configs.cbegin(); it != configs.cend(); ++it )
4348 if ( !configKeys.contains( it.key() ) )
4350 configKeys.append( it.key() );
4367 return QStringList();
4371bool QgsAuthManager::verifyPasswordCanDecryptConfigs()
const
4384 for (
const QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4394 for (
auto it = configs.cbegin(); it != configs.cend(); ++it )
4396 QString configstring(
QgsAuthCrypto::decrypt( mMasterPass, masterPasswordCiv(), it.value().config( u
"encrypted_payload"_s ) ) );
4397 if ( configstring.isEmpty() )
4399 QgsDebugError( u
"Verify password can decrypt configs FAILED, could not decrypt a config (id: %1) from storage %2"_s.arg( it.key(), storage->
name() ) );
4404 catch (
const QgsNotSupportedException &e )
4412 if ( storages.empty() )
4424bool QgsAuthManager::reencryptAllAuthenticationConfigs(
const QString &prevpass,
const QString &prevciv )
4434 for (
const auto &configid : ids )
4436 res = res && reencryptAuthenticationConfig( configid, prevpass, prevciv );
4440 Q_UNUSED( prevpass )
4446bool QgsAuthManager::reencryptAuthenticationConfig(
const QString &authcfg,
const QString &prevpass,
const QString &prevciv )
4459 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4471 const QgsAuthMethodConfig config = storage->
loadMethodConfig( authcfg, payload,
true );
4472 if ( payload.isEmpty() || !config.
isValid(
true ) )
4474 QgsDebugError( u
"Reencrypt FAILED, could not find config (id: %1)"_s.arg( authcfg ) );
4479 if ( configstring.isEmpty() )
4481 QgsDebugError( u
"Reencrypt FAILED, could not decrypt config (id: %1)"_s.arg( authcfg ) );
4495 catch (
const QgsNotSupportedException &e )
4503 if ( storages.empty() )
4515 Q_UNUSED( prevpass )
4521bool QgsAuthManager::reencryptAllAuthenticationSettings(
const QString &prevpass,
const QString &prevciv )
4526 Q_UNUSED( prevpass )
4539 QStringList encryptedsettings;
4540 encryptedsettings <<
"";
4542 for (
const auto & sett, std::as_const( encryptedsettings ) )
4549 QSqlQuery query( authDbConnection() );
4551 query.prepare( QStringLiteral(
"SELECT value FROM %1 "
4552 "WHERE setting = :setting" ).arg( authDbSettingsTable() ) );
4554 query.bindValue(
":setting", sett );
4556 if ( !authDbQuery( &query ) )
4559 if ( !query.isActive() || !query.isSelect() )
4561 QgsDebugError( u
"Reencrypt FAILED, query not active or a select operation for setting: %2"_s.arg( sett ) );
4565 if ( query.first() )
4571 query.prepare( QStringLiteral(
"UPDATE %1 "
4572 "SET value = :value "
4573 "WHERE setting = :setting" ).arg( authDbSettingsTable() ) );
4575 query.bindValue(
":setting", sett );
4578 if ( !authDbStartTransaction() )
4581 if ( !authDbQuery( &query ) )
4584 if ( !authDbCommit() )
4592 QgsDebugError( u
"Reencrypt FAILED, could not find in db setting: %2"_s.arg( sett ) );
4598 QgsDebugError( u
"Select contains more than one for setting: %1"_s.arg( sett ) );
4609bool QgsAuthManager::reencryptAllAuthenticationIdentities(
const QString &prevpass,
const QString &prevciv )
4619 for (
const auto &identid : ids )
4621 res = res && reencryptAuthenticationIdentity( identid, prevpass, prevciv );
4625 Q_UNUSED( prevpass )
4631bool QgsAuthManager::reencryptAuthenticationIdentity(
const QString &identid,
const QString &prevpass,
const QString &prevciv )
4645 for ( QgsAuthConfigurationStorage *storage : std::as_const( storages ) )
4658 if ( keystring.isEmpty() )
4660 QgsDebugError( u
"Reencrypt FAILED, could not decrypt identity id: %1"_s.arg( identid ) );
4668 catch (
const QgsNotSupportedException &e )
4676 if ( storages.empty() )
4688 Q_UNUSED( prevpass )
4700 for (
const auto &cert : certs )
4702 mCaCertsCache.insert( QgsAuthCertUtils::shaHexForCert( cert ), QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate>( source, cert ) );
4711QString QgsAuthManager::authPasswordHelperKeyName()
const
4716 QString dbProfilePath;
4722 const QFileInfo info( mAuthDatabaseConnectionUri );
4723 dbProfilePath = info.dir().dirName();
4727 dbProfilePath = QCryptographicHash::hash( ( mAuthDatabaseConnectionUri.toUtf8() ), QCryptographicHash::Md5 ).toHex();
4731 return AUTH_PASSWORD_HELPER_KEY_NAME_BASE + ( dbProfilePath.compare(
"default"_L1, Qt::CaseInsensitive ) == 0 ? QString() : dbProfilePath );
4744 if ( qobject_cast<QgsAuthConfigurationStorageDb *>( storage ) )
4759 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(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
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)