def saveOrUpdateAuthId(self): if self.authId == '': authConfig = QgsAuthMethodConfig('Basic') self.authId = QgsAuthManager.instance().uniqueConfigId() authConfig.setId(self.authId) authConfig.setConfig('username', self.connectWidget.login().strip()) authConfig.setConfig('password', self.connectWidget.password().strip()) authConfig.setName('Boundless Connect Portal') authConfig.setUri(pluginSetting('repoUrl')) if QgsAuthManager.instance().storeAuthenticationConfig(authConfig): utils.setRepositoryAuth(self.authId) else: self._showMessage('Unable to save credentials.', QgsMessageBar.WARNING) else: authConfig = QgsAuthMethodConfig() QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True) authConfig.setConfig('username', self.connectWidget.login().strip()) authConfig.setConfig('password', self.connectWidget.password().strip()) QgsAuthManager.instance().updateAuthenticationConfig(authConfig) # also setup OAuth2 configuration if possible if oauth2_supported(): endpointUrl = "{}/token/oauth?version={}".format(pluginSetting("connectEndpoint"), pluginSetting("apiVersion")) setup_oauth(self.connectWidget.login().strip(), self.connectWidget.password().strip(), endpointUrl)
def accept(self): utils.addBoundlessRepository() if self.leLogin.text() == '' or self.lePassword.text() == '': QDialog.accept(self) return if self.authId == '': authConfig = QgsAuthMethodConfig('Basic') authId = QgsAuthManager.instance().uniqueConfigId() authConfig.setId(authId) authConfig.setConfig('username', self.leLogin.text()) authConfig.setConfig('password', self.lePassword.text()) authConfig.setName('Boundless Connect Portal') settings = QSettings('Boundless', 'BoundlessConnect') authConfig.setUri(settings.value('repoUrl', '', unicode)) if QgsAuthManager.instance().storeAuthenticationConfig(authConfig): utils.setRepositoryAuth(authId) else: QMessageBox.information(self, self.tr('Error!'), self.tr('Unable to save credentials')) else: authConfig = QgsAuthMethodConfig() QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True) authConfig.setConfig('username', self.leLogin.text()) authConfig.setConfig('password', self.lePassword.text()) QgsAuthManager.instance().updateAuthenticationConfig(authConfig) QDialog.accept(self)
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 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 setup_oauth(username, password, token_uri, refresh_token_uri='', authcfg_id='oauth-2', authcfg_name='OAuth2 test configuration'): """Setup oauth configuration to access OAuth API, return authcfg_id on success, None on failure """ cfgjson = { "accessMethod": 0, "apiKey": "", "clientId": "", "clientSecret": "", "configType": 1, "grantFlow": 2, "password": password, "persistToken": False, "redirectPort": '7070', "redirectUrl": "", "refreshTokenUrl": refresh_token_uri, "requestTimeout": '30', "requestUrl": "", "scope": "", "state": "", "tokenUrl": token_uri, "username": username, "version": 1 } if authcfg_id not in QgsApplication.authManager().availableAuthMethodConfigs(): authConfig = QgsAuthMethodConfig('OAuth2') authConfig.setId(authcfg_id) authConfig.setName(authcfg_name) authConfig.setConfig('oauth2config', json.dumps(cfgjson)) if QgsApplication.authManager().storeAuthenticationConfig(authConfig): return authcfg_id else: authConfig = QgsAuthMethodConfig() QgsApplication.authManager().loadAuthenticationConfig(authcfg_id, authConfig, True) authConfig.setName(authcfg_name) authConfig.setConfig('oauth2config', json.dumps(cfgjson)) if QgsApplication.authManager().updateAuthenticationConfig(authConfig): return authcfg_id return None
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)
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')
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)
def old_version_import() -> Service: settings = QgsSettings() if settings.contains('plugins/geomapfsih_locator_plugin/geomapfish_url'): definition = dict() definition['name'] = settings.value( 'plugins/geomapfsih_locator_plugin/filter_name', 'geomapfish', type=str) definition['url'] = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_url', '', type=str) definition['crs'] = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_crs', '', type=str) definition['remove_leading_digits'] = settings.value( 'plugins/geomapfsih_locator_plugin/remove_leading_digits', True, type=bool) definition['replace_underscore'] = settings.value( 'plugins/geomapfsih_locator_plugin/replace_underscore', True, type=bool) definition['break_camelcase'] = settings.value( 'plugins/geomapfsih_locator_plugin/break_camelcase', True, type=bool) definition['category_limit'] = settings.value( 'plugins/geomapfsih_locator_plugin/category_limit', 8, type=int) definition['total_limit'] = settings.value( 'plugins/geomapfsih_locator_plugin/total_limit', 50, type=int) user = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_user', '', type=str) pwd = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_pass', '', type=str) info("importing old service: {}".format(definition)) if user: reply = QMessageBox.question( None, "Geomapfish Locator", QCoreApplication.translate( "Geomapfish Locator", "User and password were saved in clear text in former Geomapfish plugin. " "Would you like to use QGIS authentication to store these credentials? " "If not, they will be removed.")) if reply == QMessageBox.Yes: config = QgsAuthMethodConfig('Basic') config.setName('geomapfish_{}'.format(definition['name'])) config.setConfig('username', user) config.setConfig('password', pwd) QgsApplication.authManager().storeAuthenticationConfig(config) definition['authid'] = config.id() dbg_info("created new auth id: {}".format(config.id())) else: drop_keys() return None drop_keys() return Service(definition) else: return None