예제 #1
0
 def getCredentials(self):
     if self._username is None or self._password is None:
         auth_config = QgsAuthMethodConfig()
         QgsApplication.authManager().loadAuthenticationConfig(self.authId, auth_config, True)  # noqa
         self._username = auth_config.config('username')
         self._password = auth_config.config('password')
     return self._username, self._password
    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("")
예제 #3
0
 def getCredentials(self):
     authConfig = QgsAuthMethodConfig()
     QgsApplication.authManager().loadAuthenticationConfig(
         self.authid, authConfig, True)
     username = authConfig.config('username')
     password = authConfig.config('password')
     return username, password
    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()
예제 #5
0
    def test_model(self):
        """Test QGIS Auth model"""

        self.assertEqual(QgisAuth.objects.count(), 0)

        # Create an auth config
        cfg = QgisAuth.objects.create(
            id='aabbcc1',
            name='my config 1',
            config="{'password': '******', 'username': '******', 'realm': ''}")

        # Check the DB
        self.assertTrue('aabbcc1' in self.am.configIds())
        self.assertEqual(QgisAuth.objects.count(), 1)

        config = QgsAuthMethodConfig()
        self.am.loadAuthenticationConfig('aabbcc1', config, True)
        self.assertEqual(config.config('username'), 'user')
        self.assertEqual(config.config('password'), 'pass')

        # Change
        cfg.config = "{'password': '******', 'username': '******', 'realm': ''}"
        cfg.save()

        self.am.loadAuthenticationConfig('aabbcc1', config, True)
        self.assertEqual(config.config('username'), 'user_new')
        self.assertEqual(config.config('password'), 'pass_new')

        self.fakelayer.datasource = 'dbname=\'geo_demo\' host=localhost port=5432 authcfg=\'aabbcc1\' user=\'\' password=\'\' sslmode=disable key=\'id\' srid=3003 type=Polygon checkPrimaryKeyUnicity=\'1\' table="casentino"."piano_parco" (geom) sql='
        self.fakelayer.save()

        # Try delete, but there is a layer using it
        with transaction.atomic():
            with self.assertRaises(LayerDependenciesError):
                cfg.delete()

        self.fakelayer.datasource = self.fakelayer_datasource
        self.fakelayer.save()

        cfg.delete()

        self.assertFalse('aabbcc1' in self.am.configIds())
        self.assertEqual(QgisAuth.objects.count(), 0)
예제 #6
0
 def get_3di_auth():
     """Getting 3Di credentials from the QGIS Authorization Manager."""
     settings = QSettings()
     authcfg = settings.value("threedi/authcfg", None)
     auth_manager = QgsApplication.authManager()
     cfg = QgsAuthMethodConfig()
     auth_manager.loadAuthenticationConfig(authcfg, cfg, True)
     username = cfg.config("username")
     password = cfg.config("password")
     return username, password
예제 #7
0
 def login(self):
     authManager = QgsApplication.authManager()
     if KEY_NAME in authManager.configIds():
         authConfig = QgsAuthMethodConfig()
         authManager.loadAuthenticationConfig(KEY_NAME, authConfig, True)
         key = authConfig.config('licensekey')
         if doEnterpriseLogin(key):
             return True
     dlg = LoginDialog(self.iface.mainWindow())
     return dlg.exec_() == QDialog.Accepted
예제 #8
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
예제 #9
0
def get_mergin_auth():
    settings = QSettings()
    save_credentials = settings.value('Mergin/saveCredentials', 'false').lower() == 'true'
    mergin_url = settings.value('Mergin/server', MERGIN_URL)
    auth_manager = QgsApplication.authManager()
    if not save_credentials or not auth_manager.masterPasswordHashInDatabase():
        return mergin_url, '', ''

    authcfg = settings.value('Mergin/authcfg', None)
    cfg = QgsAuthMethodConfig()
    auth_manager.loadAuthenticationConfig(authcfg, cfg, True)
    url = cfg.uri()
    username = cfg.config('username')
    password = cfg.config('password')
    return url, username, password
예제 #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 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)
예제 #12
0
    def set_proxy_values(self):
        settings = QSettings()
        proxyEnabled = settings.value("proxy/proxyEnabled")
        base_url = self.base_url.lower()
        excluded = False
        noProxyUrls = settings.value("proxy/noProxyUrls") or []
        excluded = any([base_url.startswith(url.lower()) for url in noProxyUrls])
        if proxyEnabled and not excluded:
            proxyType = settings.value("proxy/proxyType")
            if proxyType != "HttpProxy":
                QgsMessageLog.logMessage(
                    "Planet Explorer: Only HttpProxy is supported "
                    "for connecting to the Planet API",
                    level=Qgis.Warning,
                )
                return

            proxyHost = settings.value("proxy/proxyHost")
            proxyPort = settings.value("proxy/proxyPort")
            url = f"{proxyHost}:{proxyPort}"
            authid = settings.value("proxy/authcfg", "")
            if authid:
                authConfig = QgsAuthMethodConfig()
                QgsApplication.authManager().loadAuthenticationConfig(
                    authid, authConfig, True
                )
                username = authConfig.config("username")
                password = authConfig.config("password")
            else:
                username = settings.value("proxy/proxyUser")
                password = settings.value("proxy/proxyPassword")

            if username:
                tokens = url.split("://")
                url = f"{tokens[0]}://{username}:{password}@{tokens[-1]}"

            self.dispatcher.session.proxies["http"] = url
            self.dispatcher.session.proxies["https"] = url
        else:
            self.dispatcher.session.proxies = {}
예제 #13
0
    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)
예제 #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()
예제 #15
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'