Beispiel #1
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
Beispiel #2
0
def sync(model):
    """Syncs the model with the QGIS data base"""

    kwargs = {
        'signal': post_delete,
        'receiver': sync_auth_delete,
        'sender': QgisAuth,
        'dispatch_uid': None
    }

    with temp_disconnect_signal(**kwargs):
        kwargs = {
        'signal': pre_delete,
        'receiver': check_layer_dependencies,
        'sender': QgisAuth,
        'dispatch_uid': None
        }
        with temp_disconnect_signal(**kwargs):
            model._objects.all().delete()

    am = QgsApplication.instance().authManager()

    kwargs = {
        'signal': post_save,
        'receiver': sync_auth_save,
        'sender': QgisAuth,
        'dispatch_uid': None
    }

    with temp_disconnect_signal(**kwargs):
        for authcfg in sorted(am.configIds()):
            c = QgsAuthMethodConfig()
            am.loadAuthenticationConfig(authcfg, c, True)
            model._objects.create(id=c.id(), name=c.name(), config=c.configMap(
            ), uri=c.uri(), version=c.version(), method=c.method())
Beispiel #3
0
def get_postgres_conn_info(selected):
    """ Read PostgreSQL connection details from QgsSettings stored by QGIS
    """
    settings = QgsSettings()
    settings.beginGroup(u"/PostgreSQL/connections/" + selected)
    if not settings.contains("database"):  # non-existent entry?
        return {}

    conn_info = dict()

    #Check if a service is provided
    service = settings.value("service", '', type=str)
    hasService = len(service) > 0
    if hasService:
        conn_info["service"] = service

    # password and username
    username = ''
    password = ''
    authconf = settings.value('authcfg', '')
    if authconf:
        # password encrypted in AuthManager
        auth_manager = QgsApplication.authManager()
        conf = QgsAuthMethodConfig()
        auth_manager.loadAuthenticationConfig(authconf, conf, True)
        if conf.id():
            username = conf.config('username', '')
            password = conf.config('password', '')
    else:
        # basic (plain-text) settings
        username = settings.value('username', '', type=str)
        password = settings.value('password', '', type=str)

    # password and username could be stored in environment variables
    # if not present in AuthManager or plain-text settings, do not
    # add it to conn_info at all
    if len(username) > 0:
        conn_info["user"] = username
    if len(password) > 0:
        conn_info["password"] = password

    host = settings.value("host", "", type=str)
    database = settings.value("database", "", type=str)
    port = settings.value("port", "", type=str)

    #Prevent setting host, port or database to empty string or default value
    #It may by set in a provided service and would overload it
    if len(host) > 0:
        conn_info["host"] = host
    if len(database) > 0:
        conn_info["database"] = database
    if len(port) > 0:
        conn_info["port"] = int(port)

    return conn_info
Beispiel #4
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())
Beispiel #5
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'")
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)
Beispiel #7
0
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 getDbCursor(self):
        """
            Creates a psycopg2 connection based on the selected 
            connection and returns a cursor.
            
        """
        
        # Determine our current preference
        s = QSettings()
        selectedConnection = str(s.value("constraintchecker/postgisConnection", ''))
        if len(selectedConnection) == 0:
            # We have not yet specified a connection
            raise Exception('No PostGIS connection has been nominated for performing constraints queries. \n\n'
                            'Please select a PostGIS connection using Plugins > Constraint Checker > Edit Configuration'
                            ' \n\nPostGIS connections can be created in the Add PostGIS Table(s) dialog.')

        host = str(s.value("PostgreSQL/connections/%s/host" % selectedConnection, ''))
        if len(host) == 0:
            # Looks like the preferred connection could not be found
            raise Exception('The preferred PostGIS connection, '
                            '%s could not be found, please check your Constrain Checker settings')
        database = str(s.value("PostgreSQL/connections/%s/database" % selectedConnection, ''))
        user = str(s.value("PostgreSQL/connections/%s/username" % selectedConnection, ''))
        password = str(s.value("PostgreSQL/connections/%s/password" % selectedConnection, ''))
        port = int(s.value("PostgreSQL/connections/%s/port" % selectedConnection, 5432))

        auth_manager = QgsApplication.authManager()
        conf = QgsAuthMethodConfig()
        configs = {v.name(): k for k, v in auth_manager.availableAuthMethodConfigs().items()}
        # name of config in auth must match the name of selected connection
        try:
            auth_manager.loadAuthenticationConfig(configs[selectedConnection], conf, True)
            if conf.id():
                user = conf.config('username', '')
                password = conf.config('password', '')
        except KeyError:
            pass

        dbConn = psycopg2.connect(database=database,
                                  user=user,
                                  password=password,
                                  host=host,
                                  port=port)
        dbConn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
        return dbConn.cursor()
Beispiel #9
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()
Beispiel #10
0
    def getConfig(self, auth_method_id):

        auth_cfg = QgsAuthMethodConfig()
        auth_mgr = QgsApplication.authManager()
        auth_mgr.loadAuthenticationConfig(auth_method_id, auth_cfg, True)

        # Default values
        username = None,
        password = None,
        url = "https://openapi-test.kartverket.no/v1/"

        if auth_cfg.id():
            username = auth_cfg.config('username', '')
            password = auth_cfg.config('password', '')

        if auth_cfg.uri():
            url = auth_cfg.uri()

        return url, username, password
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()
Beispiel #12
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')
Beispiel #13
0
    def run(self):
        QgsMessageLog.logMessage(f"GeoRectifyTask.run, process: %s" %
                                 self.name,
                                 tag="OAW",
                                 level=Qgis.Info)
        try:
            self.set_status('running', 'started')

            input_tif = os.path.join(self.options["staging_folder"],
                                     self.name + ".tif")
            scripts_folder = os.path.join(QgsApplication.prefixPath(), "..",
                                          "Python37/Scripts")
            geo_rectify = GeoRectifyFactory.create(
                input=input_tif,
                qgis_scripts=scripts_folder,
                min_points=self.options["min_points"],
                gdal_threads=self.options["gdal_threads"])
            geo_rectify.on_progress += self.on_progress
            geo_rectify.process()

            auth_id = self.options["remote_authid"]
            auth_manager = QgsApplication.authManager()
            auth_cfg = QgsAuthMethodConfig()
            auth_manager.loadAuthenticationConfig(auth_id, auth_cfg, True)
            if auth_cfg.id():
                username = auth_cfg.config('username', '')
                password = auth_cfg.config('password', '')
                uri = auth_cfg.uri()
                # call FTP task
                QgsMessageLog.logMessage(f"GeoRectifyTask.run, URI: %s" %
                                         str(uri),
                                         tag="OAW",
                                         level=Qgis.Info)
                QgsMessageLog.logMessage(f"GeoRectifyTask.run, username: %s" %
                                         str(username),
                                         tag="OAW",
                                         level=Qgis.Info)
                QgsMessageLog.logMessage(f"GeoRectifyTask.run, password: %s" %
                                         "***********",
                                         tag="OAW",
                                         level=Qgis.Info)
                # upload file via SFTP
                output_tif = input_tif.replace(".tif", "_grf_fin.tif")
                remote_folder = self.options[
                    "remote_folder"] if "remote_folder" in self.options else "public"
                cnopts = pysftp.CnOpts()
                cnopts.hostkeys = None
                with pysftp.Connection(uri,
                                       username=username,
                                       password=password,
                                       cnopts=cnopts) as sftp:
                    with sftp.cd(remote_folder):
                        sftp.put(output_tif, remotepath=self.name + ".tif")

                # Remove intermediate file (if requested)
                if self.options["remove_file_after"] == Qt.Checked:
                    os.remove(output_tif)
                    QgsMessageLog.logMessage(
                        f"GeoRectifyTask.run, removing intermediate file: %s" %
                        output_tif,
                        tag="OAW",
                        level=Qgis.Info)
            else:
                raise Exception(
                    "Failed to extract information from the QGIS authentication manager using authid: %s"
                    % auth_id)
            self.set_status('completed', 'done')
        except Exception as e:
            self.exception = e
            self.set_status('failed', str(e))
            QgsMessageLog.logMessage(f"GeoRectifyTask.run, exception: %s" %
                                     str(e),
                                     tag="OAW",
                                     level=Qgis.Warning)
        self.handlers["on_completed"](self)
        QgsMessageLog.logMessage(f"GeoRectifyTask.run, result: %s" %
                                 self.status,
                                 tag="OAW",
                                 level=Qgis.Info)
        return self.status == 'completed'
Beispiel #14
0
    def connChanged(self, conn_name='', schema_name=''):
        # close any existing connection to a river database
        if self.rdb:
            self.addInfo("Closing existing connection to {0}@{1} river database".format(self.rdb.dbname, self.rdb.host))
            self.rdb.disconnect_pg()
            self.rdb = None
        else:
            pass
        s = QSettings()
        s.beginGroup('/PostgreSQL/connections')
        connsNames = s.childGroups()

        if conn_name in connsNames:
            self.curConnName = conn_name
        else:
            self.curConnName = self.ui.connsCbo.currentText()

        self.ui.connsCbo.clear()
        self.ui.connsCbo.addItem('')
        for conn in connsNames:
            self.ui.connsCbo.addItem(conn)
        try:
            i = connsNames.index(self.curConnName) + 1
        except ValueError:
            i = 0
        self.ui.connsCbo.setCurrentIndex(i)
        if self.ui.connsCbo.currentIndex() == 0:
            self.ui.schemasCbo.clear()
            self.ui.schemasCbo.addItem('')
            self.disableActions()
            return
        connName = self.ui.connsCbo.currentText()
        s.endGroup()
        s.beginGroup('/PostgreSQL/connections/{0}'.format(connName))

        # first try to get the credentials from AuthManager, then from the basic settings
        authconf = s.value('authcfg', None)
        if authconf:
            auth_manager = QgsApplication.authManager()
            conf = QgsAuthMethodConfig()
            auth_manager.loadAuthenticationConfig(authconf, conf, True)
            if conf.id():
                self.user = conf.config('username', '')
                self.passwd = conf.config('password', '')
        else:
            self.user = s.value('username')
            self.passwd = s.value('password')

        self.host = s.value('host')
        self.port = s.value('port')
        self.database = s.value('database')

        s.endGroup()

        # create a new connection to river database
        self.rdb = rivdb.RiverDatabase(self, self.database, self.host, self.port, self.user, self.passwd)
        self.rdb.SRID = int(self.crs.postgisSrid())
        if self.rdb.connect_pg():
            self.addInfo('Created connection to river database: {0}@{1}'.format(self.rdb.dbname, self.rdb.host))
            self.rdb.last_conn = connName
        else:
            info = 'Couldn\'t connect to river database: {0}@{1}'.format(self.rdb.dbname, self.rdb.host)
            info += '\nPlease, check you database connection settings!'
            self.addInfo(info)
            self.ui.schemasCbo.clear()
            return

        # refresh schemas combo
        schemaName = self.ui.schemasCbo.currentText()
        qry = "SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname != 'information_schema' ORDER BY nspname"
        schemas = self.rdb.run_query(qry, fetch=True)
        self.ui.schemasCbo.clear()
        self.ui.schemasCbo.addItem('')
        if not schemas:
            schemas = []
        for schema in schemas:
            self.ui.schemasCbo.addItem(schema[0])
        if schema_name:
            schemaExists = self.ui.schemasCbo.findText(schema_name)
        else:
            schemaExists = self.ui.schemasCbo.findText(schemaName)
        if schemaExists:
            self.ui.schemasCbo.setCurrentIndex(schemaExists)
        self.enableDBActions()
        self.schemaChanged()
Beispiel #15
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)
Beispiel #16
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)
Beispiel #17
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