def set_auth_cfg(plan: LandUsePlanEnum, auth_cfg_id: str, username: str, password: str) -> None: """ Set auth config id to be used as Qaava connection :param plan: :param auth_cfg_id: :param username: :param password: """ # noinspection PyArgumentList auth_mgr: QgsAuthManager = QgsApplication.authManager() if auth_cfg_id in auth_mgr.availableAuthMethodConfigs().keys(): config = QgsAuthMethodConfig() auth_mgr.loadAuthenticationConfig(auth_cfg_id, config, True) config.setConfig('username', username) config.setConfig('password', password) if not config.isValid(): raise QaavaAuthConfigException('Invalid username or password') auth_mgr.updateAuthenticationConfig(config) else: config = QgsAuthMethodConfig() config.setId(auth_cfg_id) config.setName(auth_cfg_id) config.setMethod('Basic') config.setConfig('username', username) config.setConfig('password', password) if not config.isValid(): raise QaavaAuthConfigException('Invalid username or password') auth_mgr.storeAuthenticationConfig(config) set_setting(plan.value.auth_cfg_key, auth_cfg_id, internal=False)
def setUpClass(cls): super().setUpClass() # Prepare DB for path in (AUTH_DB_PATH, MASTER_PASSWORD_PATH): assert os.path.isfile(path) cls.am = QgsApplication.instance().authManager() assert cls.am.configIds() == [] assert cls.am.setMasterPassword(True) assert cls.am.masterPasswordIsSet() config = QgsAuthMethodConfig() config.setName("alice") config.setMethod('Basic') config.setConfig("username", "my user") config.setConfig("password", "my password") assert config.isValid() res, cfg = cls.am.storeAuthenticationConfig(config) assert res assert config.id() != '' assert cfg.id() != '' assert cfg.id() == config.id() # Store fakelayer datasource cls.fakelayer = Layer.objects.get(name='fakelayer') cls.fakelayer_datasource = cls.fakelayer.datasource
def auth_text(user, password): authMgr = QgsApplication.authManager() cfg = QgsAuthMethodConfig() cfg.setName(user) cfg.setMethod('Basic') cfg.setConfig('username', user) cfg.setConfig('password', password) authMgr.storeAuthenticationConfig(cfg) return(cfg)
def handleLogin(self): key = self.textKey.text() if doEnterpriseLogin(key): authMgr = QgsApplication.authManager() config = QgsAuthMethodConfig() config.setId(KEY_NAME) config.setName("GeoCat Bridge Enterprise key") config.setMethod("Basic") config.setConfig("username", "") config.setConfig("password", "") config.setConfig("licensekey", key) authMgr.storeAuthenticationConfig(config) self.accept() else: QMessageBox.warning(self, 'Error', 'Bad username or password')
def sync_auth_save(sender, instance, **kwargs): """Sync the QGIS auth DB after save""" c = QgsAuthMethodConfig() c.setId(instance.id) c.setMethod(instance.method) c.setName(instance.name) c.setUri(instance.uri) c.setVersion(instance.version) c.setConfigMap(ast.literal_eval(instance.config)) am = QgsApplication.instance().authManager() if c.id() in am.configIds(): am.updateAuthenticationConfig(c) else: am.storeAuthenticationConfig(c)
def initAuthConfigId(): am = QgsApplication.authManager() if AUTHCFGID not in am.configIds(): conf = dict( URL=serverLocationBasicAuth()+'/rest', USER=GSUSER, PASSWORD=GSPASSWORD, AUTHCFG=AUTHCFGID) conf.update([(k, os.getenv('GS%s' % k)) for k in conf if 'GS%s' % k in os.environ]) cfg = QgsAuthMethodConfig() cfg.setId(AUTHCFGID) cfg.setName('Geoserver test') cfg.setMethod('Basic') cfg.setConfig('username', conf['USER']) cfg.setConfig('password', conf['PASSWORD']) self.am.storeAuthenticationConfig(cfg)
def populatePKITestCerts(): """ Populate AuthManager with test certificates. heavily based on testqgsauthmanager.cpp. """ global AUTHM global AUTHCFGID global AUTHTYPE assert (AUTHM is not None) if AUTHCFGID: removePKITestCerts() assert (AUTHCFGID is None) # set alice PKI data p_config = QgsAuthMethodConfig() p_config.setName("alice") p_config.setMethod("PKI-Paths") p_config.setUri("http://example.com") p_config.setConfig("certpath", os.path.join(PKIDATA, 'alice-cert.pem')) p_config.setConfig("keypath", os.path.join(PKIDATA, 'alice-key.pem')) assert p_config.isValid() # add authorities cacerts = QSslCertificate.fromPath( os.path.join(PKIDATA, 'subissuer-issuer-root-ca_issuer-2-root-2-ca_chains.pem')) assert cacerts is not None AUTHM.storeCertAuthorities(cacerts) AUTHM.rebuildCaCertsCache() AUTHM.rebuildTrustedCaCertsCache() # add alice cert # boundle = QgsPkiBundle.fromPemPaths(os.path.join(PKIDATA, 'alice-cert.pem'), # os.path.join(PKIDATA, 'alice-key_w-pass.pem'), # 'password', # cacerts) # assert boundle is not None # assert boundle.isValid() # register alice data in auth AUTHM.storeAuthenticationConfig(p_config) AUTHCFGID = p_config.id() assert (AUTHCFGID is not None) assert (AUTHCFGID != '') AUTHTYPE = p_config.method()
def initAuthConfigId(): am = QgsApplication.authManager() if AUTHCFGID not in am.configIds(): conf = dict( URL=serverLocationBasicAuth()+'/rest', USER=GSUSER, PASSWORD=GSPASSWORD, AUTHCFG=AUTHCFGID) conf.update([(k, os.getenv('GS%s' % k)) for k in conf if 'GS%s' % k in os.environ]) cfg = QgsAuthMethodConfig() cfg.setId(AUTHCFGID) cfg.setName('Geoserver test') cfg.setMethod('Basic') cfg.setConfig('username', conf['USER']) cfg.setConfig('password', conf['PASSWORD']) am.storeAuthenticationConfig(cfg)
def set_3di_auth(personal_api_key, username="******"): """Setting 3Di credentials in the QGIS Authorization Manager.""" settings = QSettings() authcfg = settings.value("threedi/authcfg", None) cfg = QgsAuthMethodConfig() auth_manager = QgsApplication.authManager() auth_manager.setMasterPassword() auth_manager.loadAuthenticationConfig(authcfg, cfg, True) if cfg.id(): cfg.setConfig("username", username) cfg.setConfig("password", personal_api_key) auth_manager.updateAuthenticationConfig(cfg) else: cfg.setMethod("Basic") cfg.setName("3Di Personal Api Key") cfg.setConfig("username", username) cfg.setConfig("password", personal_api_key) auth_manager.storeAuthenticationConfig(cfg) settings.setValue("threedi/authcfg", cfg.id())
def populatePKITestCerts(): """ Populate AuthManager with test certificates. heavily based on testqgsauthmanager.cpp. """ global AUTHM global AUTHCFGID global AUTHTYPE assert (AUTHM is not None) if AUTHCFGID: removePKITestCerts() assert (AUTHCFGID is None) # set alice PKI data p_config = QgsAuthMethodConfig() p_config.setName("alice") p_config.setMethod("PKI-Paths") p_config.setUri("http://example.com") p_config.setConfig("certpath", os.path.join(PKIDATA, 'alice-cert.pem')) p_config.setConfig("keypath", os.path.join(PKIDATA, 'alice-key.pem')) assert p_config.isValid() # add authorities cacerts = QSslCertificate.fromPath(os.path.join(PKIDATA, 'subissuer-issuer-root-ca_issuer-2-root-2-ca_chains.pem')) assert cacerts is not None AUTHM.storeCertAuthorities(cacerts) AUTHM.rebuildCaCertsCache() AUTHM.rebuildTrustedCaCertsCache() # add alice cert # boundle = QgsPkiBundle.fromPemPaths(os.path.join(PKIDATA, 'alice-cert.pem'), # os.path.join(PKIDATA, 'alice-key_w-pass.pem'), # 'password', # cacerts) # assert boundle is not None # assert boundle.isValid() # register alice data in auth AUTHM.storeAuthenticationConfig(p_config) AUTHCFGID = p_config.id() assert (AUTHCFGID is not None) assert (AUTHCFGID != '') AUTHTYPE = p_config.method()
def config_obj(self, kind, base=True): config = QgsAuthMethodConfig() config.setName(kind) config.setMethod(kind) config.setUri("http://example.com") if base: return config if kind == "Basic": config.setConfig("username", "username") config.setConfig("password", "password") config.setConfig("realm", "Realm") elif kind == "PKI-Paths": config.setConfig("certpath", os.path.join(PKIDATA, "gerardus_cert.pem")) config.setConfig("keypath", os.path.join(PKIDATA, "gerardus_key_w-pass.pem")) config.setConfig("keypass", "password") elif kind == "PKI-PKCS#12": config.setConfig("bundlepath", os.path.join(PKIDATA, "gerardus.p12")) config.setConfig("bundlepass", "password") return config
def testHTTPRequestsOverrider(self): """ Test that GDAL curl network requests are redirected through QGIS networking """ with mockedwebserver.install_http_server() as port: handler = mockedwebserver.SequentialHandler() # Check failed network requests # Check that the driver requested Accept header is well propagated handler.add('GET', '/collections/foo', 404, expected_headers={'Accept': 'application/json'}) with mockedwebserver.install_http_handler(handler): QgsVectorLayer("OAPIF:http://127.0.0.1:%d/collections/foo" % port, 'test', 'ogr') # Error coming from Qt network stack, not GDAL/CURL one assert 'server replied: Not Found' in gdal.GetLastErrorMsg() # Test a nominal case handler = mockedwebserver.SequentialHandler() handler.add('GET', '/collections/foo', 200, {'Content-Type': 'application/json'}, '{ "id": "foo" }') handler.add('GET', '/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') handler.add('GET', '/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') handler.add('GET', '/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') with mockedwebserver.install_http_handler(handler): vl = QgsVectorLayer("OAPIF:http://127.0.0.1:%d/collections/foo" % port, 'test', 'ogr') assert vl.isValid() # More complicated test using an anthentication configuration config = QgsAuthMethodConfig() config.setName('Basic') config.setMethod('Basic') config.setConfig('username', 'username') config.setConfig('password', 'password') QgsApplication.authManager().storeAuthenticationConfig(config) handler = mockedwebserver.SequentialHandler() # Check that the authcfg gets expanded during the network request ! handler.add('GET', '/collections/foo', 404, expected_headers={ 'Authorization': 'Basic dXNlcm5hbWU6cGFzc3dvcmQ='}) with mockedwebserver.install_http_handler(handler): QgsVectorLayer("OAPIF:http://127.0.0.1:%d/collections/foo authcfg='%s'" % (port, config.id()), 'test', 'ogr')
def test_db_methods(self): """Test auth DB operations""" # Create an auth configuration config = QgsAuthMethodConfig() config.setName("alice") config.setMethod('Basic') config.setConfig("username", "my user") config.setConfig("password", "my password") self.assertTrue(config.isValid()) res, cfg = self.am.storeAuthenticationConfig(config) self.assertTrue(res) self.assertTrue(config.id() != '') self.assertTrue(cfg.id() != '') self.assertEqual(cfg.id(), config.id()) uri = QgsDataSourceUri('db=/my/fake/uri authcfg=%s' % cfg.id()) # Note: string cut is necessary on 3.10 only # FIXME: remove when we switch to 3.16 self.assertEqual( uri.uri(True)[:55], "user='******' password='******' db='/my/fake/uri'")
def set_mergin_auth(url, username, password): settings = QSettings() authcfg = settings.value('Mergin/authcfg', None) cfg = QgsAuthMethodConfig() auth_manager = QgsApplication.authManager() auth_manager.setMasterPassword() auth_manager.loadAuthenticationConfig(authcfg, cfg, True) if cfg.id(): cfg.setUri(url) cfg.setConfig("username", username) cfg.setConfig("password", password) auth_manager.updateAuthenticationConfig(cfg) else: cfg.setMethod("Basic") cfg.setName("mergin") cfg.setUri(url) cfg.setConfig("username", username) cfg.setConfig("password", password) auth_manager.storeAuthenticationConfig(cfg) settings.setValue('Mergin/authcfg', cfg.id()) settings.setValue('Mergin/server', url)
def config_obj(self, kind, base=True): config = QgsAuthMethodConfig() config.setName(kind) config.setMethod(kind) config.setUri('http://example.com') if base: return config if kind == 'Basic': config.setConfig('username', 'username') config.setConfig('password', 'password') config.setConfig('realm', 'Realm') elif kind == 'PKI-Paths': config.setConfig('certpath', os.path.join(PKIDATA, 'gerardus_cert.pem')) config.setConfig('keypath', os.path.join(PKIDATA, 'gerardus_key_w-pass.pem')) config.setConfig('keypass', 'password') elif kind == 'PKI-PKCS#12': config.setConfig('bundlepath', os.path.join(PKIDATA, 'gerardus.p12')) config.setConfig('bundlepass', 'password') return config
def test_060_identities(self): client_cert_path = os.path.join(PKIDATA, 'fra_cert.pem') client_key_path = os.path.join(PKIDATA, 'fra_key_w-pass.pem') client_key_pass = '******' client_p12_path = os.path.join(PKIDATA, 'gerardus_w-chain.p12') client_p12_pass = '******' # store regular PEM cert/key and generate config # noinspection PyTypeChecker bundle1 = QgsPkiBundle.fromPemPaths(client_cert_path, client_key_path, client_key_pass) bundle1_cert = bundle1.clientCert() bundle1_key = bundle1.clientKey() bundle1_ca_chain = bundle1.caChain() bundle1_cert_sha = bundle1.certId() # with open(client_key_path, 'r') as f: # key_data = f.read() # # client_cert = QgsAuthCertUtils.certsFromFile(client_cert_path)[0] msg = 'Identity PEM certificate is null' self.assertFalse(bundle1_cert.isNull(), msg) # cert_sha = QgsAuthCertUtils.shaHexForCert(client_cert) # # client_key = QSslKey(key_data, QSsl.Rsa, QSsl.Pem, # QSsl.PrivateKey, client_key_pass) msg = 'Identity PEM key is null' self.assertFalse(bundle1_key.isNull(), msg) msg = 'Identity PEM certificate chain is not empty' self.assertEqual(len(bundle1_ca_chain), 0, msg) msg = "Identity PEM could not be stored in database" self.assertTrue( self.authm.storeCertIdentity(bundle1_cert, bundle1_key), msg) msg = "Identity PEM not found in database" self.assertTrue(self.authm.existsCertIdentity(bundle1_cert_sha), msg) config1 = QgsAuthMethodConfig() config1.setName('IdentityCert - PEM') config1.setMethod('Identity-Cert') config1.setConfig('certid', bundle1_cert_sha) msg = 'Could not store PEM identity config' self.assertTrue(self.authm.storeAuthenticationConfig(config1), msg) configid1 = config1.id() msg = 'Could not retrieve PEM identity config id from store op' self.assertIsNotNone(configid1, msg) config2 = QgsAuthMethodConfig() msg = 'Could not load PEM identity config' self.assertTrue( self.authm.loadAuthenticationConfig(configid1, config2, True), msg) # store PKCS#12 bundled cert/key and generate config # bundle = QgsPkcsBundle(client_p12_path, client_p12_pass) # noinspection PyTypeChecker bundle = QgsPkiBundle.fromPkcs12Paths(client_p12_path, client_p12_pass) bundle_cert = bundle.clientCert() bundle_key = bundle.clientKey() bundle_ca_chain = bundle.caChain() bundle_cert_sha = QgsAuthCertUtils.shaHexForCert(bundle_cert) msg = 'Identity bundle certificate is null' self.assertFalse(bundle_cert.isNull(), msg) msg = 'Identity bundle key is null' self.assertFalse(bundle_key.isNull(), msg) msg = 'Identity bundle CA chain is not correct depth' self.assertEqual(len(bundle_ca_chain), 3, msg) msg = "Identity bundle could not be stored in database" self.assertTrue(self.authm.storeCertIdentity(bundle_cert, bundle_key), msg) msg = "Identity bundle not found in database" self.assertTrue(self.authm.existsCertIdentity(bundle_cert_sha), msg) bundle_config = QgsAuthMethodConfig() bundle_config.setName('IdentityCert - Bundle') bundle_config.setMethod('Identity-Cert') bundle_config.setConfig('certid', bundle_cert_sha) msg = 'Could not store bundle identity config' self.assertTrue(self.authm.storeAuthenticationConfig(bundle_config), msg) bundle_configid = bundle_config.id() msg = 'Could not retrieve bundle identity config id from store op' self.assertIsNotNone(bundle_configid, msg) bundle_config2 = QgsAuthMethodConfig() msg = 'Could not load bundle identity config' self.assertTrue( self.authm.loadAuthenticationConfig(bundle_configid, bundle_config2, True), msg) # TODO: add more tests # self.show_editors_widget() msg = 'Could not remove PEM identity config' self.assertTrue(self.authm.removeAuthenticationConfig(configid1), msg) msg = 'Could not remove bundle identity config' self.assertTrue(self.authm.removeAuthenticationConfig(bundle_configid), msg)
def test_060_identities(self): client_cert_path = os.path.join(PKIDATA, 'fra_cert.pem') client_key_path = os.path.join(PKIDATA, 'fra_key_w-pass.pem') client_key_pass = '******' client_p12_path = os.path.join(PKIDATA, 'gerardus_w-chain.p12') client_p12_pass = '******' # store regular PEM cert/key and generate config # noinspection PyTypeChecker bundle1 = QgsPkiBundle.fromPemPaths(client_cert_path, client_key_path, client_key_pass) bundle1_cert = bundle1.clientCert() bundle1_key = bundle1.clientKey() bundle1_ca_chain = bundle1.caChain() bundle1_cert_sha = bundle1.certId() # with open(client_key_path, 'r') as f: # key_data = f.read() # # client_cert = QgsAuthCertUtils.certsFromFile(client_cert_path)[0] msg = 'Identity PEM certificate is null' self.assertFalse(bundle1_cert.isNull(), msg) # cert_sha = QgsAuthCertUtils.shaHexForCert(client_cert) # # client_key = QSslKey(key_data, QSsl.Rsa, QSsl.Pem, # QSsl.PrivateKey, client_key_pass) msg = 'Identity PEM key is null' self.assertFalse(bundle1_key.isNull(), msg) msg = 'Identity PEM certificate chain is not empty' self.assertEqual(len(bundle1_ca_chain), 0, msg) msg = "Identity PEM could not be stored in database" self.assertTrue( self.authm.storeCertIdentity(bundle1_cert, bundle1_key), msg) msg = "Identity PEM not found in database" self.assertTrue(self.authm.existsCertIdentity(bundle1_cert_sha), msg) config1 = QgsAuthMethodConfig() config1.setName('IdentityCert - PEM') config1.setMethod('Identity-Cert') config1.setConfig('certid', bundle1_cert_sha) msg = 'Could not store PEM identity config' self.assertTrue(self.authm.storeAuthenticationConfig(config1), msg) configid1 = config1.id() msg = 'Could not retrieve PEM identity config id from store op' self.assertIsNotNone(configid1, msg) config2 = QgsAuthMethodConfig() msg = 'Could not load PEM identity config' self.assertTrue( self.authm.loadAuthenticationConfig(configid1, config2, True), msg) # store PKCS#12 bundled cert/key and generate config # bundle = QgsPkcsBundle(client_p12_path, client_p12_pass) # noinspection PyTypeChecker bundle = QgsPkiBundle.fromPkcs12Paths(client_p12_path, client_p12_pass) bundle_cert = bundle.clientCert() bundle_key = bundle.clientKey() bundle_ca_chain = bundle.caChain() bundle_cert_sha = QgsAuthCertUtils.shaHexForCert(bundle_cert) msg = 'Identity bundle certificate is null' self.assertFalse(bundle_cert.isNull(), msg) msg = 'Identity bundle key is null' self.assertFalse(bundle_key.isNull(), msg) msg = 'Identity bundle CA chain is not correct depth' self.assertEqual(len(bundle_ca_chain), 3, msg) msg = "Identity bundle could not be stored in database" self.assertTrue( self.authm.storeCertIdentity(bundle_cert, bundle_key), msg) msg = "Identity bundle not found in database" self.assertTrue(self.authm.existsCertIdentity(bundle_cert_sha), msg) bundle_config = QgsAuthMethodConfig() bundle_config.setName('IdentityCert - Bundle') bundle_config.setMethod('Identity-Cert') bundle_config.setConfig('certid', bundle_cert_sha) msg = 'Could not store bundle identity config' self.assertTrue( self.authm.storeAuthenticationConfig(bundle_config), msg) bundle_configid = bundle_config.id() msg = 'Could not retrieve bundle identity config id from store op' self.assertIsNotNone(bundle_configid, msg) bundle_config2 = QgsAuthMethodConfig() msg = 'Could not load bundle identity config' self.assertTrue( self.authm.loadAuthenticationConfig(bundle_configid, bundle_config2, True), msg) # TODO: add more tests # self.show_editors_widget() msg = 'Could not remove PEM identity config' self.assertTrue(self.authm.removeAuthenticationConfig(configid1), msg) msg = 'Could not remove bundle identity config' self.assertTrue( self.authm.removeAuthenticationConfig(bundle_configid), msg)
from qgis.PyQt.QtCore import QSettings from qgis.core import QgsAuthManager, QgsAuthMethodConfig, QgsMessageLog, Qgis AUTHDB_MASTERPWD = 'password' QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=Qgis.Info) # Do not run twice! if not QSettings().value("InitScript/AuthCfgCreated", type=bool): QSettings().setValue("InitScript/AuthCfgCreated", True) # Check if authdb master password is set am = QgsAuthManager.instance() if not am.masterPasswordHashInDb(): # Set it! am.setMasterPassword(AUTHDB_MASTERPWD, True) # Create config am.authenticationDbPath() am.masterPasswordIsSet() cfg = QgsAuthMethodConfig() cfg.setId('myauth1') # Optional, useful for plugins to retrieve an authcfg cfg.setName('Example Auth Config HTTP Basic') cfg.setMethod('Basic') cfg.setConfig('username', 'username') cfg.setConfig('password', 'password') am.storeAuthenticationConfig(cfg) else: QgsMessageLog.logMessage("Master password was already set: aborting", tag="Init script", level=Qgis.Info) else: QgsMessageLog.logMessage("AuthCfg was already created: aborting", tag="Init script", level=Qgis.Info)
from qgis.PyQt.QtCore import QSettings from qgis.core import QgsAuthManager, QgsAuthMethodConfig, QgsMessageLog AUTHDB_MASTERPWD = 'password' QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=Qgis.Info) # Do not run twice! if not QSettings().value("InitScript/AuthCfgCreated", type=bool): QSettings().setValue("InitScript/AuthCfgCreated", True) # Check if authdb master password is set am = QgsAuthManager.instance() if not am.masterPasswordHashInDb(): # Set it! am.setMasterPassword(AUTHDB_MASTERPWD, True) # Create config am.authenticationDbPath() am.masterPasswordIsSet() cfg = QgsAuthMethodConfig() cfg.setId('myauth1') # Optional, useful for plugins to retrieve an authcfg cfg.setName('Example Auth Config HTTP Basic') cfg.setMethod('Basic') cfg.setConfig('username', 'username') cfg.setConfig('password', 'password') am.storeAuthenticationConfig(cfg) else: QgsMessageLog.logMessage("Master password was already set: aborting", tag="Init script", level=Qgis.Info) else: QgsMessageLog.logMessage("AuthCfg was already created: aborting", tag="Init script", level=Qgis.Info)