예제 #1
0
def get_qgis_proxy_config(url=None):
    """Check if a proxy is enabled and needed for the given url. Return the settings and additional info."""
    proxy_config = None
    s = QSettings()
    proxy_enabled = s.value("proxy/proxyEnabled", False, type=bool)
    if proxy_enabled:
        proxy_type = s.value("proxy/proxyType")
        if proxy_type not in ("HttpProxy", "HttpCachingProxy"):
            raise ClientError(
                f"Not supported proxy server type ({proxy_type})")
        excluded = [
            e.rstrip("/")
            for e in s.value("proxy/proxyExcludedUrls", "").split("|")
        ]
        if url is not None and url.rstrip("/") in excluded:
            return proxy_config
        proxy_config = dict()
        proxy_config["url"] = s.value("proxy/proxyHost", None)
        if proxy_config["url"] is None:
            raise ClientError("No URL given for proxy server")
        proxy_config["port"] = s.value("proxy/proxyPort", 3128)
        auth_conf_id = s.value("proxy/authcfg", None)
        if auth_conf_id:
            auth_manager = QgsApplication.authManager()
            auth_conf = QgsAuthMethodConfig()
            auth_manager.loadAuthenticationConfig(auth_conf_id, auth_conf,
                                                  True)
            proxy_config["user"] = auth_conf.configMap()["username"]
            proxy_config["password"] = auth_conf.configMap()["password"]
        else:
            proxy_config["user"] = s.value("proxy/proxyUser", None)
            proxy_config["password"] = s.value("proxy/proxyPassword", None)
    return proxy_config
    def authenticate(self, reply, auth):
        """
        :param reply:
        :param auth:
        :return:
        """

        if not self.connection:
            self.report_error("No connection set for authentication!")
            reply.abort()

        if self.connection.auth_cfg == '':
            return

        self.report_info('Authenticating connection \'' +
                         self.connection.name + '\' with auth_cfg \'' +
                         str(self.connection.auth_cfg) + '\'')
        self.auth += 1
        if self.auth >= 3:
            reply.abort()

        config = QgsAuthMethodConfig()
        QgsApplication.authManager().loadAuthenticationConfig(
            self.connection.auth_cfg, config, True)
        if 'username' in config.configMap():
            auth.setUser(config.configMap()['username'])
            auth.setPassword(config.configMap()['password'])
예제 #3
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())
    def process_put_call(self, url, data=None, report_url=True):
        """
        Run a PUT request and return reply data
        :param url: url for request
        :param data:
        :param report_url: True if URL should be reported to feedback
        :return: response or error message in json format
        """

        if self.connection.read_only:
            return {
                "error": {
                    "msg": "Graphium connection is set to read-only!"
                }
            }

        url_query = QUrl(url)
        if report_url:
            self.report_info('PUT ' + url_query.toString())

        data_byte_array = QJsonDocument.fromVariant(data)

        request = QNetworkRequest(url_query)
        if self.connection.auth_cfg != '':
            self.auth = 0
            config = QgsAuthMethodConfig()
            QgsApplication.authManager().loadAuthenticationConfig(
                self.connection.auth_cfg, config, True)
            concatenated = config.configMap(
            )['username'] + ":" + config.configMap()['password']

            data = base64.encodebytes(concatenated.encode("utf-8")).replace(
                '\n'.encode("utf-8"), ''.encode("utf-8"))
            request.setRawHeader("Authorization".encode("utf-8"),
                                 ("Basic %s" % data).encode("utf-8"))
            request.setRawHeader("Accept".encode("utf-8"),
                                 "*/*".encode("utf-8"))
        loop = QEventLoop()  # https://stackoverflow.com/a/46514984
        reply = self.network_access_manager.put(request,
                                                data_byte_array.toJson())
        reply.finished.connect(loop.quit)
        loop.exec_()

        return self.process_q_reply(reply)
예제 #5
0
def get_db_connection_params(plan: LandUsePlanEnum) -> Dict[str, str]:
    """
    :return: Psycopg2 connection params for Qaava database
    """

    s = QSettings()
    s.beginGroup(f"{PG_CONNECTIONS}/{get_qaava_connection_name(plan)}")
    auth_cfg_id = parse_value(s.value("authcfg"))
    username_saved = parse_value(s.value("saveUsername"))
    pwd_saved = parse_value(s.value("savePassword"))

    params = {}

    for qgs_key, psyc_key in QGS_SETTINGS_PSYCOPG2_PARAM_MAP.items():
        params[psyc_key] = parse_value(s.value(qgs_key))

    s.endGroup()
    # username or password might have to be asked separately
    if not username_saved:
        params["user"] = None

    if not pwd_saved:
        params["password"] = None

    if auth_cfg_id is not None and auth_cfg_id != "":
        LOGGER.debug(f"Auth cfg: {auth_cfg_id}")
        # Auth config is being used to store the username and password
        auth_config = QgsAuthMethodConfig()
        # noinspection PyArgumentList
        QgsApplication.authManager().loadAuthenticationConfig(
            auth_cfg_id, auth_config, True)

        if auth_config.isValid():
            params["user"] = auth_config.configMap().get("username")
            params["password"] = auth_config.configMap().get("password")
        else:
            raise QaavaAuthConfigException(
                tr("Auth config error occurred while fetching database connection parameters"
                   ),
                bar_msg=bar_msg(
                    tr(f"Check auth config with id: {auth_cfg_id}")))

    return params
    def process_delete_call(self, url, report_url=True):
        """
        Run a DELETE request and return reply data
        :param url: url for request
        :param report_url: True if URL should be reported to feedback
        :return: response or error message in json format
        """

        if self.connection.read_only:
            return {
                "error": {
                    "msg": "Graphium connection is set to read-only!"
                }
            }

        url_query = QUrl(url)
        if report_url:
            self.report_info('DELETE ' + url_query.toString())

        request = QNetworkRequest(url_query)
        if self.connection.auth_cfg != '':
            self.auth = 0
            config = QgsAuthMethodConfig()
            QgsApplication.authManager().loadAuthenticationConfig(
                self.connection.auth_cfg, config, True)
            concatenated = config.configMap(
            )['username'] + ":" + config.configMap()['password']

            data = base64.encodebytes(concatenated.encode("utf-8")).replace(
                '\n'.encode("utf-8"), ''.encode("utf-8"))
            request.setRawHeader("Authorization".encode("utf-8"),
                                 ("Basic %s" % data).encode("utf-8"))
            request.setRawHeader("Accept".encode("utf-8"),
                                 "*/*".encode("utf-8"))
        loop = QEventLoop()
        reply = self.network_access_manager.deleteResource(request)
        reply.finished.connect(loop.quit)
        loop.exec_()

        return self.process_q_reply(reply)
예제 #7
0
    def readDatabaseParamsFromSettings(self, usedDatabaseConnectionName):
        settings = QSettings()
        settings.beginGroup(YleiskaavaSettings.PG_CONNECTIONS + "/" +
                            usedDatabaseConnectionName)

        params = {}

        auth_cfg_id = parse_value(settings.value("authcfg"))
        username_saved = parse_value(settings.value("saveUsername"))
        pwd_saved = parse_value(settings.value("savePassword"))

        for qgs_key, psyc_key in YleiskaavaDatabase.QGS_SETTINGS_PSYCOPG2_PARAM_MAP.items(
        ):
            params[psyc_key] = parse_value(settings.value(qgs_key))

        settings.endGroup()
        # username or password might have to be asked separately
        if not username_saved:
            params["user"] = None

        if not pwd_saved:
            params["password"] = None

        if auth_cfg_id is not None and auth_cfg_id != "":
            # LOGGER.info(f"Auth cfg: {auth_cfg_id}")
            # Auth config is being used to store the username and password
            auth_config = QgsAuthMethodConfig()
            authMgr = QgsApplication.authManager()
            authMgr.loadAuthenticationConfig(auth_cfg_id, auth_config, True)

            if auth_config.isValid():
                params["user"] = auth_config.configMap().get("username")
                params["password"] = auth_config.configMap().get("password")
            else:
                raise QaavaAuthConfigException()

        # LOGGER.info(f"PR{params} {username_saved} {pwd_saved}")

        return params
예제 #8
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()
예제 #9
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())