def showLogin(self):
        self.stackedWidget.setCurrentIndex(0)
        self.webView.setVisible(False)
        self.webView.setHtml("")
        self.leSearch.setText("")
        self.tabsContent.setCurrentIndex(0)
        self.svgLogo.show()
        self.lblSmallLogo.hide()
        connect.resetToken()
        self.token = None

        fillCredentials = pluginSetting("rememberCredentials")
        if fillCredentials:
            self.connectWidget.setRemember(Qt.Checked)

            username = ""
            password = ""
            if self.authId != "":
                authConfig = QgsAuthMethodConfig()
                if self.authId in QgsAuthManager.instance().configIds():
                    QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
                    username = authConfig.config("username")
                    password = authConfig.config("password")
                self.connectWidget.setLogin(username)
                self.connectWidget.setPassword(password)
        else:
            self.connectWidget.setRemember(Qt.Unchecked)
            self.connectWidget.setLogin("")
            self.connectWidget.setPassword("")
    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()
    def showEvent(self, event):
        fillCredentials = pluginSetting("rememberCredentials")
        if self.authId != '' and fillCredentials and not self.loggedIn:
            authConfig = QgsAuthMethodConfig()
            if self.authId in QgsAuthManager.instance().configIds():
                QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
                username = authConfig.config('username')
                password = authConfig.config('password')
            else:
                self.authId = ''
                utils.setRepositoryAuth(self.authId)
                self._showMessage('Could not find Connect credentials in the database.',
                                  QgsMessageBar.WARNING)
                username = ''
                password = ''

            self.connectWidget.setLogin(username)
            self.connectWidget.setPassword(password)

        BASE.showEvent(self, event)
    def __init__(self, parent=None):
        super(ConnectDialog, self).__init__(parent)
        self.setupUi(self)

        self.setWindowIcon(QIcon(os.path.join(pluginPath, 'icons', 'connect.svg')))
        self.svgLogo.load(os.path.join(pluginPath, 'icons', 'connect-logo.svg'))

        btnOk = self.buttonBox.button(QDialogButtonBox.Ok)
        btnOk.setText(self.tr('Login'))

        settings = QSettings()
        settings.beginGroup(reposGroup)
        self.authId = settings.value(boundlessRepoName + '/authcfg', '', unicode)
        settings.endGroup()

        if self.authId != '':
            authConfig = QgsAuthMethodConfig()
            QgsAuthManager.instance().loadAuthenticationConfig(self.authId, authConfig, True)
            username = authConfig.config('username')
            password = authConfig.config('password')
            self.leLogin.setText(username)
            self.lePassword.setText(password)

        self.buttonBox.helpRequested.connect(self.showHelp)
Esempio n. 5
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)
Esempio n. 6
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'
Esempio n. 7
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)
Esempio n. 9
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
Esempio n. 10
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)
Esempio n. 11
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()
Esempio n. 12
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)
Esempio n. 13
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')
Esempio n. 14
0
    def load_work_layers(self):

        def check_conn(host, port, database, user, password):
            try:
                conn = psycopg2.connect(host=host,port=port, database=database, user=user, password=password, connect_timeout=1)
                conn.close()
                #self.iface.messageBar().pushMessage(self.tr('Povezava uspešna'))
                return True
            except:
                #self.iface.messageBar().pushMessage(self.tr('Povezava neuspešna, napačen uporabnik ali geslo!'))
                return False


        host = parameters(self)[0]
        database =  parameters(self)[1]
        port =  parameters(self)[4]
        table = get_work_layers(self)
        uri = QgsDataSourceUri()
        root = QgsProject.instance().layerTreeRoot()

        self.host = parameters(self)[0]
        self.database =  parameters(self)[1]
        self.port =  parameters(self)[4]


        #Input authentication
        authcfg = self.dlg.mAuthConfigSelect.configId()
        auth_mgr = QgsApplication.authManager()
        auth_cfg = QgsAuthMethodConfig()
        auth_mgr.loadAuthenticationConfig(authcfg, auth_cfg, True)
        auth = auth_cfg.configMap()

        # Input Username, password
        user = self.dlg.user_input.text()
        password = self.dlg.pass_input.text()
        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) 

        aut_meth = 0 

        if user:
            check_conn(host, port, database, user, password)
            authentication = auth_text(user, password)  
            aut_meth = 1

        elif auth_mgr:
            try:
                check_conn(host, port, database, auth["username"], auth["password"])
                authentication = auth_cfg
            except:
                pass
        else:
            self.iface.messageBar().pushMessage(self.tr("Napačen uporabnik ali geslo."), self.tr("Potrdi za javni dostop."), level=Qgis.Critical)
            text = self.tr('Uporabljam javni dostop:')
            uri.setConnection(host, port, database, None, None)
            (success, user, passwd) = QgsCredentials.instance().get(text, parameters(self)[3],  parameters(self)[2])  
            if success:
                if check_conn(host, port, database, user, passwd):
                    user = user
                    password = passwd  
                else:
                    check_conn(host, port, database, user, passwd) 
                    self.iface.messageBar().pushMessage(self.tr('Povezava neuspešna, napačen uporabnik ali geslo!'))

        #List of groups and layers
        w_layers = [r[1] for r in table.getFeatures()]         
        groups = [self.tr('Delovni sloji')]



        def load_wl(shema, table, geom, sql, fid):   
            if geom == '':
                geom = None
            uri.setConnection(self.host, self.port, self.database, "", "", QgsDataSourceUri.SslDisable,"")
            uri.setAuthConfigId(authentication.id())
            uri.setDataSource(shema, table, geom, sql, fid)
            layer=QgsVectorLayer (uri .uri(False), table, "postgres")
            return layer
      



        #Attribute form config for layer ZLS Int
        def field_to_value_relation(layer):
            fields = layer.fields()
            pattern = re.compile(r'Vrsta')
            fields_vrsta = [field for field in fields if pattern.match(field.name())]
            if len(fields_vrsta) > 0:
                config = {'AllowMulti': False,
                        'AllowNull': False,
                        'FilterExpression': 'Sloj = current_value(\'Sloj\') and  \"Opombe\" =\'kategorije\'',
                        'Key': 'Vrsta',
                        'Layer': layer.id(),
                        'NofColumns': 1,
                        'OrderByValue': False,
                        'UseCompleter': False,
                        'Value': 'Vrsta'}
                for field in fields_vrsta:
                    field_idx = fields.indexOf(field.name())
                    if field_idx >= 0:
                        try:             
                            widget_setup = QgsEditorWidgetSetup('ValueRelation',config)
                            layer.setEditorWidgetSetup(field_idx, widget_setup) 
                        except:
                            pass
                    else:
                        return False
            else:
                return False
            return True

        #Join fields function
        def field_join(t_layer, s_layer, t_field, s_field):
            joinObject = QgsVectorLayerJoinInfo()
            joinObject.setJoinFieldName(s_field)
            joinObject.setTargetFieldName(t_field)
            joinObject.setJoinLayerId(s_layer.id())
            joinObject.setUsingMemoryCache(True)
            joinObject.setJoinLayer(s_layer)
            t_layer.addJoin(joinObject)


        #Populate list of accessible layers
        layers_list = []
        for f in table.getFeatures():
            if f[3] != 'admin':
                print(f[2])
                try:
                    layer = load_wl(f[2], f[1], f[4], "", f[5])
                    if layer.isValid():
                        layers_list.append(layer)  
                except:
                    continue

        if not root.findGroup(self.tr('Delovni sloji')) and len(layers_list) != 0:
            w_group = root.addGroup(self.tr('Delovni sloji'))
        else:
            w_group = root.findGroup(self.tr('Delovni sloji'))

        # load layers
        for current, layer in enumerate(layers_list):
            QgsProject.instance().addMapLayer(layer, False)   
            w_group.insertChildNode(current, QgsLayerTreeLayer(layer))
            myLayerNode = root.findLayer(layer.id())
            myLayerNode.setExpanded(False)
            if layer.name() == 'ZLS Interpretacija_delovno':
                field_to_value_relation(layer)
        
        if aut_meth == 1:
            authMgr = QgsApplication.authManager()
            authMgr.removeAuthenticationConfig(authentication.id())  
Esempio n. 15
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)
Esempio n. 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)
Esempio n. 17
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())
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": "",
        "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
Esempio n. 19
0
def get_authconfig_map(authconfigid):
    # to get username and password from the authconfig
    auth_mgr = QgsApplication.authManager()
    auth_cfg = QgsAuthMethodConfig()
    auth_mgr.loadAuthenticationConfig(authconfigid, auth_cfg, True)
    return auth_cfg.configMap()
Esempio n. 20
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()
Esempio n. 21
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)
    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)
Esempio n. 23
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
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": "",
        "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
Esempio n. 25
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)
Esempio n. 26
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
Esempio n. 27
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