예제 #1
0
def ScopedCertAuthority(username, password, sslrootcert_path=None):
    """
    Sets up the certificate authority in the authentication manager
    for the lifetime of this class and removes it when the class is deleted.
    """
    authm = QgsApplication.authManager()
    auth_config = QgsAuthMethodConfig("Basic")
    auth_config.setConfig('username', username)
    auth_config.setConfig('password', password)
    auth_config.setName('test_password_auth_config')
    if sslrootcert_path:
        sslrootcert = QSslCertificate.fromPath(sslrootcert_path)
        assert sslrootcert is not None
        authm.storeCertAuthorities(sslrootcert)
        authm.rebuildCaCertsCache()
        authm.rebuildTrustedCaCertsCache()
        authm.rebuildCertTrustCache()
    assert (authm.storeAuthenticationConfig(auth_config)[0])
    assert auth_config.isValid()
    yield auth_config
    if sslrootcert_path:
        for cert in sslrootcert:
            authm.removeCertAuthority(cert)
    authm.rebuildCaCertsCache()
    authm.rebuildTrustedCaCertsCache()
    authm.rebuildCertTrustCache()
예제 #2
0
    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
예제 #3
0
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)
예제 #4
0
 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) 
예제 #5
0
 def setUpAuth(cls, username, password):
     """Run before all tests and set up authentication"""
     assert (cls.authm.setMasterPassword('masterpassword', True))
     # Client side
     auth_config = QgsAuthMethodConfig("Basic")
     auth_config.setConfig('username', username)
     auth_config.setConfig('password', password)
     auth_config.setName('test_basic_auth_config')
     assert (cls.authm.storeAuthenticationConfig(auth_config)[0])
     assert auth_config.isValid()
     return auth_config
예제 #6
0
    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 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)
예제 #8
0
 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')
예제 #9
0
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
예제 #10
0
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)
예제 #11
0
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)
예제 #12
0
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()
예제 #13
0
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()
예제 #14
0
    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')
예제 #15
0
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
예제 #16
0
    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'")
예제 #17
0
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)
예제 #18
0
    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())
예제 #19
0
    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
예제 #20
0
    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)
예제 #22
0
    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
예제 #23
0
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)
예제 #24
0
    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)
예제 #25
0
    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
예제 #26
0
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