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("")
Пример #2
0
    def post(self, url, headers, data=None, auth_id=None):
        self.json = None
        data = data.encode() if data is not None else None
        request = _prepare_request(url, headers, auth_id)
        # noinspection PyArgumentList
        self.reply = QgsNetworkAccessManager.instance().post(request, data)

        if auth_id:
            QgsAuthManager.instance().updateNetworkReply(self.reply, auth_id)

        self.reply.finished.connect(self.json_reply_finished)
Пример #3
0
 def app_initialized(self):
     """
     Semi-automated pre-population with minimal user interaction, but only at
     end of app launch, not after (like when loading via Plugin Manager).
     """
     # noinspection PyArgumentList
     if (not QgsAuthManager.instance().masterPasswordHashInDb()
             or not QgsAuthManager.instance().getCertIdentities()):
         authdlg = PopulateAuthSystemDialog(parent=self.mw,
                                            qgis_iface=self.iface,
                                            title=self.title,
                                            init_run=True)
         authdlg.exec_()
Пример #4
0
def initAuthManager():
    """
    Setup AuthManager instance.

    heavily based on testqgsauthmanager.cpp.
    """
    global AUTHM
    if not AUTHM:
        AUTHM = QgsAuthManager.instance()
        # check if QgsAuthManager has been already initialised... a side effect
        # of the QgsAuthManager.init() is that AuthDbPath is set
        if AUTHM.authenticationDbPath():
            # already initilised => we are inside QGIS. Assumed that the
            # actual qgis_auth.db has the same master pwd as AUTHDB_MASTERPWD
            if AUTHM.masterPasswordIsSet():
                msg = 'Auth master password not set from passed string'
                assert AUTHM.masterPasswordSame(AUTHDB_MASTERPWD)
            else:
                msg = 'Master password could not be set'
                assert AUTHM.setMasterPassword(AUTHDB_MASTERPWD, True), msg
        else:
            # outside qgis => setup env var before db init
            os.environ['QGIS_AUTH_DB_DIR_PATH'] = AUTHDBDIR
            msg = 'Master password could not be set'
            assert AUTHM.setMasterPassword(AUTHDB_MASTERPWD, True), msg
            AUTHM.init(AUTHDBDIR)
 def auth_manager():
     """Return auth manager relative to QGIS version singleton pattern
     """
     if hasattr(QgsApplication, 'authManager'):
         return QgsApplication.authManager()  # QGIS 3
     else:
         return QgsAuthManager.instance()  # QGIS 2
Пример #6
0
def initAuthManager():
    """
    Setup AuthManager instance.

    heavily based on testqgsauthmanager.cpp.
    """
    global AUTHM
    if not AUTHM:
        AUTHM = QgsAuthManager.instance()
        # check if QgsAuthManager has been already initialised... a side effect
        # of the QgsAuthManager.init() is that AuthDbPath is set
        if AUTHM.authenticationDbPath():
            # already initilised => we are inside QGIS. Assumed that the
            # actual qgis_auth.db has the same master pwd as AUTHDB_MASTERPWD
            if AUTHM.masterPasswordIsSet():
                msg = 'Auth master password not set from passed string'
                assert AUTHM.masterPasswordSame(AUTHDB_MASTERPWD)
            else:
                msg = 'Master password could not be set'
                assert AUTHM.setMasterPassword(AUTHDB_MASTERPWD, True), msg
        else:
            # outside qgis => setup env var before db init
            os.environ['QGIS_AUTH_DB_DIR_PATH'] = AUTHDBDIR
            msg = 'Master password could not be set'
            assert AUTHM.setMasterPassword(AUTHDB_MASTERPWD, True), msg
            AUTHM.init(AUTHDBDIR)
Пример #7
0
    def __init__(self, parent, plugin):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.plugin = plugin
        self.mResult = ""
        self.progressBar.setRange(0, 0)
        self.progressBar.setFormat("%p%")
        self.labelName.setText(plugin["name"])
        self.buttonBox.clicked.connect(self.abort)

        url = QUrl(plugin["download_url"])

        fileName = plugin["filename"]
        tmpDir = QDir.tempPath()
        tmpPath = QDir.cleanPath(tmpDir + "/" + fileName)
        self.file = QFile(tmpPath)

        self.request = QNetworkRequest(url)
        authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"]
        if authcfg and isinstance(authcfg, basestring):
            if not QgsAuthManager.instance().updateNetworkRequest(
                    self.request, authcfg.strip()):
                self.mResult = self.tr(
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(
                        authcfg)
                self.request = None

        if self.request is not None:
            self.reply = QgsNetworkAccessManager.instance().get(self.request)
            self.reply.downloadProgress.connect(self.readProgress)
            self.reply.finished.connect(self.requestFinished)

            self.stateChanged(4)
Пример #8
0
    def requestFetching(self, key):
        """ start fetching the repository given by key """
        self.mRepositories[key]["state"] = 1
        url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
        #v=str(Qgis.QGIS_VERSION_INT)
        #url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!

        self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
        authcfg = self.mRepositories[key]["authcfg"]
        if authcfg and isinstance(authcfg, str):
            if not QgsAuthManager.instance().updateNetworkRequest(
                    self.mRepositories[key]["QRequest"], authcfg.strip()):
                msg = QCoreApplication.translate(
                    "QgsPluginInstaller",
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(
                        authcfg)
                iface.pluginManagerInterface().pushMessage(
                    msg, QgsMessageBar.WARNING)
                self.mRepositories[key]["QRequest"] = None
                return
        self.mRepositories[key]["QRequest"].setAttribute(
            QNetworkRequest.User, key)
        self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance(
        ).get(self.mRepositories[key]["QRequest"])
        self.mRepositories[key]["xmlData"].setProperty('reposName', key)
        self.mRepositories[key]["xmlData"].downloadProgress.connect(
            self.mRepositories[key]["Relay"].dataReadProgress)
        self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
    def __init__(self, parent, plugin):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.plugin = plugin
        self.mResult = ""
        self.progressBar.setRange(0, 0)
        self.progressBar.setFormat("%p%")
        self.labelName.setText(plugin["name"])
        self.buttonBox.clicked.connect(self.abort)

        url = QUrl(plugin["download_url"])

        fileName = plugin["filename"]
        tmpDir = QDir.tempPath()
        tmpPath = QDir.cleanPath(tmpDir + "/" + fileName)
        self.file = QFile(tmpPath)

        self.request = QNetworkRequest(url)
        authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"]
        if authcfg and isinstance(authcfg, basestring):
            if not QgsAuthManager.instance().updateNetworkRequest(
                    self.request, authcfg.strip()):
                self.mResult = self.tr(
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(authcfg)
                self.request = None

        if self.request is not None:
            self.reply = QgsNetworkAccessManager.instance().get(self.request)
            self.reply.downloadProgress.connect(self.readProgress)
            self.reply.finished.connect(self.requestFinished)

            self.stateChanged(4)
Пример #10
0
 def _getOnlineLayer(self, type_name, layer_name=None):
     """
     Return a new WFS layer, overriding the WFS cache
     """
     if layer_name is None:
         layer_name = 'wfs_' + type_name
     parms = {
         'srsname':
         'EPSG:4326',
         'typename':
         type_name,
         'url':
         'http://127.0.0.1:%s/%s/?map=%s' %
         (self.port, self.counter, self.project_path),
         'version':
         'auto',
         'table':
         '',
         #'sql': '',
     }
     self.counter += 1
     uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())])
     wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS')
     wfs_layer.setParent(QgsAuthManager.instance())
     assert wfs_layer.isValid()
     return wfs_layer
Пример #11
0
 def _getLayer(cls, layer_name):
     """
     Layer factory (return the backend layer), provider specific
     """
     path = cls.testdata_path + layer_name + '.shp'
     layer = QgsVectorLayer(path, layer_name, "ogr")
     layer.setParent(QgsAuthManager.instance())
     assert layer.isValid()
     return layer
Пример #12
0
 def _getLayer(cls, layer_name):
     """
     Layer factory (return the backend layer), provider specific
     """
     path = cls.testdata_path + layer_name + '.shp'
     layer = QgsVectorLayer(path, layer_name, "ogr")
     layer.setParent(QgsAuthManager.instance())
     assert layer.isValid()
     return layer
Пример #13
0
    def setUpClass(cls):
        cls.authm = QgsAuthManager.instance()
        assert not cls.authm.isDisabled(), cls.authm.disabledMessage()

        cls.mpass = '******'  # master password

        db1 = QFileInfo(cls.authm.authenticationDatabasePath()).canonicalFilePath()
        db2 = QFileInfo(AUTHDBDIR + '/qgis-auth.db').canonicalFilePath()
        msg = 'Auth db temp path does not match db path of manager'
        assert db1 == db2, msg
Пример #14
0
    def setUpClass(cls):
        cls.authm = QgsAuthManager.instance()
        assert not cls.authm.isDisabled(), cls.authm.disabledMessage()

        cls.mpass = '******'  # master password

        db1 = QFileInfo(cls.authm.authenticationDbPath()).canonicalFilePath()
        db2 = QFileInfo(AUTHDBDIR + '/qgis-auth.db').canonicalFilePath()
        msg = 'Auth db temp path does not match db path of manager'
        assert db1 == db2, msg
Пример #15
0
    def process_requests(self, requests, headers=None, auth_id=None):
        for r in requests:
            req = _prepare_request(r.url, headers, auth_id)
            req.setAttribute(QNetworkRequest.User, r.fid)
            req.setAttribute(QNetworkRequest.User + 1, r.image_id)
            req.setAttribute(QNetworkRequest.User + 2, r.file_path)

            if r.method.lower() == "get":
                # noinspection PyArgumentList
                reply = QgsNetworkAccessManager.instance().get(req)
            else:
                # noinspection PyArgumentList
                reply = QgsNetworkAccessManager.instance().post(req)

            if auth_id:
                QgsAuthManager.instance().updateNetworkReply(reply, auth_id)

            reply.finished.connect(self.image_reply_finished)
            self.replies.append(reply)
Пример #16
0
    def setUpAuth(cls):
        """Run before all tests and set up authentication"""
        authm = QgsAuthManager.instance()
        assert (authm.setMasterPassword('masterpassword', True))
        cls.pg_conf = os.path.join(cls.tempfolder, 'postgresql.conf')
        cls.pg_hba = os.path.join(cls.tempfolder, 'pg_hba.conf')
        # Client side
        cls.sslrootcert_path = os.path.join(
            cls.certsdata_path,
            'chains_subissuer-issuer-root_issuer2-root2.pem')
        cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem')
        cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem')
        assert os.path.isfile(cls.sslcert)
        assert os.path.isfile(cls.sslkey)
        assert os.path.isfile(cls.sslrootcert_path)
        os.chmod(cls.sslcert, stat.S_IRUSR)
        os.chmod(cls.sslkey, stat.S_IRUSR)
        os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
        cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
        cls.auth_config.setConfig('certpath', cls.sslcert)
        cls.auth_config.setConfig('keypath', cls.sslkey)
        cls.auth_config.setName('test_pki_auth_config')
        cls.username = '******'
        cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
        assert cls.sslrootcert is not None
        authm.storeCertAuthorities(cls.sslrootcert)
        authm.rebuildCaCertsCache()
        authm.rebuildTrustedCaCertsCache()
        authm.rebuildCertTrustCache()
        assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
        assert cls.auth_config.isValid()

        # Server side
        cls.server_cert = os.path.join(cls.certsdata_path,
                                       'localhost_ssl_cert.pem')
        cls.server_key = os.path.join(cls.certsdata_path,
                                      'localhost_ssl_key.pem')
        cls.server_rootcert = cls.sslrootcert_path
        os.chmod(cls.server_cert, stat.S_IRUSR)
        os.chmod(cls.server_key, stat.S_IRUSR)
        os.chmod(cls.server_rootcert, stat.S_IRUSR)

        # Place conf in the data folder
        with open(cls.pg_conf, 'w+') as f:
            f.write(
                QGIS_POSTGRES_CONF_TEMPLATE % {
                    'port': cls.port,
                    'tempfolder': cls.tempfolder,
                    'server_cert': cls.server_cert,
                    'server_key': cls.server_key,
                    'sslrootcert_path': cls.sslrootcert_path,
                })

        with open(cls.pg_hba, 'w+') as f:
            f.write(QGIS_POSTGRES_HBA_TEMPLATE)
    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 setUpClass(cls):
        cls.authm = QgsAuthManager.instance()
        cls.authdbdir = tempfile.mkdtemp()
        cls.authm.init(cls.authdbdir)
        msg = 'Auth db could not be created in temp dir'
        assert os.path.exists(cls.authm.authenticationDbPath()), msg

        db1 = QFileInfo(cls.authm.authenticationDbPath()).canonicalFilePath()
        db2 = QFileInfo(cls.authdbdir + '/qgis-auth.db').canonicalFilePath()
        msg = 'Auth db path does not match db path of manager'
        assert db1 == db2, msg
Пример #19
0
    def fetch(self):
        """Fetch the content (in the background).
        :return: (status, error message)
        :rtype: (boolean, string)
        """
        # Initialize some properties again
        self._content = None
        self._network_finished = False
        self._network_timeout = False

        request = QNetworkRequest(QUrl(self._url))
        request.setAttribute(
            QNetworkRequest.CacheLoadControlAttribute,
            QNetworkRequest.AlwaysNetwork)

        if self._auth_cfg and qgis_version() >= 21200:
            LOGGER.debug('Update request with auth_cfg %s' % self._auth_cfg)
            QgsAuthManager.instance().updateNetworkRequest(
                request, self._auth_cfg
            )

        self._reply = self._network_manager.get(request)
        self._reply.finished.connect(self.fetch_finished)
        self._network_manager.requestTimedOut.connect(self.request_timeout)

        while not self._reply.isFinished():
            # noinspection PyArgumentList
            QCoreApplication.processEvents()

        # Finished
        description = None
        if self._reply.error() != QNetworkReply.NoError:
            status = False
            description = self._reply.errorString()
        else:
            status = True
            self._content = self._reply.readAll()

        self._reply.deleteLater()

        return status, description
Пример #20
0
def get_oauth_authcfg(authcfg_id=AUTHCFG_ID):
    """Check if the given authcfg_id (or the default) exists, and if it's valid
    OAuth2, return the configuration or None"""
    # Handle empty strings
    if not authcfg_id:
        authcfg_id = AUTHCFG_ID
    configs = QgsAuthManager.instance().availableAuthMethodConfigs()
    if authcfg_id in configs \
        and configs[authcfg_id].isValid() \
        and configs[authcfg_id].method() == 'OAuth2':
        return configs[authcfg_id]
    return None
Пример #21
0
 def testProxyIsUpdated(self):
     """
     Test that proxy is updated
     """
     authm = QgsAuthManager.instance()
     nam = QgsNetworkAccessManager.instance()
     proxy = nam.proxy()
     self.assertEqual(proxy.password(), '')
     self.assertEqual(proxy.user(), '')
     self.assertTrue(authm.updateNetworkProxy(proxy, self.auth_config.id()))
     self.assertEqual(proxy.user(), self.username)
     self.assertEqual(proxy.password(), self.password)
Пример #22
0
    def setUpAuth(cls):
        """Run before all tests and set up authentication"""
        authm = QgsAuthManager.instance()
        assert authm.setMasterPassword("masterpassword", True)
        cls.pg_conf = os.path.join(cls.tempfolder, "postgresql.conf")
        cls.pg_hba = os.path.join(cls.tempfolder, "pg_hba.conf")
        # Client side
        cls.sslrootcert_path = os.path.join(cls.certsdata_path, "chains_subissuer-issuer-root_issuer2-root2.pem")
        cls.sslcert = os.path.join(cls.certsdata_path, "gerardus_cert.pem")
        cls.sslkey = os.path.join(cls.certsdata_path, "gerardus_key.pem")
        assert os.path.isfile(cls.sslcert)
        assert os.path.isfile(cls.sslkey)
        assert os.path.isfile(cls.sslrootcert_path)
        os.chmod(cls.sslcert, stat.S_IRUSR)
        os.chmod(cls.sslkey, stat.S_IRUSR)
        os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
        cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
        cls.auth_config.setConfig("certpath", cls.sslcert)
        cls.auth_config.setConfig("keypath", cls.sslkey)
        cls.auth_config.setName("test_pki_auth_config")
        cls.username = "******"
        cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
        assert cls.sslrootcert is not None
        authm.storeCertAuthorities(cls.sslrootcert)
        authm.rebuildCaCertsCache()
        authm.rebuildTrustedCaCertsCache()
        authm.rebuildCertTrustCache()
        assert authm.storeAuthenticationConfig(cls.auth_config)[0]
        assert cls.auth_config.isValid()

        # Server side
        cls.server_cert = os.path.join(cls.certsdata_path, "localhost_ssl_cert.pem")
        cls.server_key = os.path.join(cls.certsdata_path, "localhost_ssl_key.pem")
        cls.server_rootcert = cls.sslrootcert_path
        os.chmod(cls.server_cert, stat.S_IRUSR)
        os.chmod(cls.server_key, stat.S_IRUSR)
        os.chmod(cls.server_rootcert, stat.S_IRUSR)

        # Place conf in the data folder
        with open(cls.pg_conf, "w+") as f:
            f.write(
                QGIS_POSTGRES_CONF_TEMPLATE
                % {
                    "port": cls.port,
                    "tempfolder": cls.tempfolder,
                    "server_cert": cls.server_cert,
                    "server_key": cls.server_key,
                    "sslrootcert_path": cls.sslrootcert_path,
                }
            )

        with open(cls.pg_hba, "w+") as f:
            f.write(QGIS_POSTGRES_HBA_TEMPLATE)
Пример #23
0
 def testProxyIsUpdated(self):
     """
     Test that proxy is updated
     """
     authm = QgsAuthManager.instance()
     nam = QgsNetworkAccessManager.instance()
     proxy = nam.proxy()
     self.assertEqual(proxy.password(), '')
     self.assertEqual(proxy.user(), '')
     self.assertTrue(authm.updateNetworkProxy(proxy, self.auth_config.id()))
     self.assertEqual(proxy.user(), self.username)
     self.assertEqual(proxy.password(), self.password)
Пример #24
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)
Пример #25
0
def setup_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME):
    """Setup oauth configuration to access the BCS 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" : "",
     "requestTimeout" : '30',
     "requestUrl" : "",
     "scope" : "",
     "state" : "",
     "tokenUrl" : basemaps_token_uri,
     "username" : username,
     "version" : 1
    }

    if authcfg_id not in QgsAuthManager.instance().availableAuthMethodConfigs():
        authConfig = QgsAuthMethodConfig('OAuth2')
        authConfig.setId(authcfg_id)
        authConfig.setName(authcfg_name)
        authConfig.setConfig('oauth2config', json.dumps(cfgjson))
        if QgsAuthManager.instance().storeAuthenticationConfig(authConfig):
            return authcfg_id
    else:
        authConfig = QgsAuthMethodConfig()
        QgsAuthManager.instance().loadAuthenticationConfig(authcfg_id, authConfig, True)
        authConfig.setName(authcfg_name)
        authConfig.setConfig('oauth2config', json.dumps(cfgjson))
        if QgsAuthManager.instance().updateAuthenticationConfig(authConfig):
            return authcfg_id
    return None
    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)
    def fetch(self):
        """Fetch the content."""
        # Initialize some properties again
        self._content = None
        self._network_finished = False
        self._network_timeout = False

        request = QNetworkRequest(QUrl(self._url))
        request.setAttribute(
            QNetworkRequest.CacheLoadControlAttribute,
            QNetworkRequest.AlwaysNetwork)

        if self._auth_cfg and qgis_version() >= 21200:
            LOGGER.info('Update request with auth_cfg %s' % self._auth_cfg)
            QgsAuthManager.instance().updateNetworkRequest(
                request, self._auth_cfg
            )

        self._reply = self._network_manager.get(request)
        self._reply.finished.connect(self.fetch_finished)
        self._network_manager.requestTimedOut.connect(self.request_timeout)

        while not self._reply.isFinished():
            # noinspection PyArgumentList
            QCoreApplication.processEvents()

        # Finished
        description = None
        if self._reply.error() != QNetworkReply.NoError:
            status = False
            description = self._reply.errorString()
        else:
            status = True
            self._content = self._reply.readAll()

        self._reply.deleteLater()

        return status, description
Пример #28
0
 def setUpClass(cls):
     """Run before all tests:
     Creates an auth configuration"""
     # Enable auth
     # os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
     authm = QgsAuthManager.instance()
     assert (authm.setMasterPassword('masterpassword', True))
     cls.auth_config = QgsAuthMethodConfig('Basic')
     cls.auth_config.setName('test_auth_config')
     cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
     cls.password = cls.username[::-1]  # reversed
     cls.auth_config.setConfig('username', cls.username)
     cls.auth_config.setConfig('password', cls.password)
     assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
Пример #29
0
 def setUpClass(cls):
     """Run before all tests:
     Creates an auth configuration"""
     # Enable auth
     # os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
     authm = QgsAuthManager.instance()
     assert (authm.setMasterPassword('masterpassword', True))
     cls.auth_config = QgsAuthMethodConfig('Basic')
     cls.auth_config.setName('test_auth_config')
     cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
     cls.password = cls.username[::-1]  # reversed
     cls.auth_config.setConfig('username', cls.username)
     cls.auth_config.setConfig('password', cls.password)
     assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
    def setUpAuth(cls):
        """Run before all tests and set up authentication"""
        authm = QgsAuthManager.instance()
        assert (authm.setMasterPassword('masterpassword', True))
        cls.pg_conf = os.path.join(cls.tempfolder, 'postgresql.conf')
        cls.pg_hba = os.path.join(cls.tempfolder, 'pg_hba.conf')
        # Client side
        cls.sslrootcert_path = os.path.join(cls.certsdata_path, 'chains_subissuer-issuer-root_issuer2-root2.pem')
        cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem')
        cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem')
        assert os.path.isfile(cls.sslcert)
        assert os.path.isfile(cls.sslkey)
        assert os.path.isfile(cls.sslrootcert_path)
        os.chmod(cls.sslcert, stat.S_IRUSR)
        os.chmod(cls.sslkey, stat.S_IRUSR)
        os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
        cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
        cls.auth_config.setConfig('certpath', cls.sslcert)
        cls.auth_config.setConfig('keypath', cls.sslkey)
        cls.auth_config.setName('test_pki_auth_config')
        cls.username = '******'
        cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
        assert cls.sslrootcert is not None
        authm.storeCertAuthorities(cls.sslrootcert)
        authm.rebuildCaCertsCache()
        authm.rebuildTrustedCaCertsCache()
        authm.rebuildCertTrustCache()
        assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
        assert cls.auth_config.isValid()

        # Server side
        cls.server_cert = os.path.join(cls.certsdata_path, 'localhost_ssl_cert.pem')
        cls.server_key = os.path.join(cls.certsdata_path, 'localhost_ssl_key.pem')
        cls.server_rootcert = cls.sslrootcert_path
        os.chmod(cls.server_cert, stat.S_IRUSR)
        os.chmod(cls.server_key, stat.S_IRUSR)
        os.chmod(cls.server_rootcert, stat.S_IRUSR)

        # Place conf in the data folder
        with open(cls.pg_conf, 'w+') as f:
            f.write(QGIS_POSTGRES_CONF_TEMPLATE % {
                'port': cls.port,
                'tempfolder': cls.tempfolder,
                'server_cert': cls.server_cert,
                'server_key': cls.server_key,
                'sslrootcert_path': cls.sslrootcert_path,
            })

        with open(cls.pg_hba, 'w+') as f:
            f.write(QGIS_POSTGRES_HBA_TEMPLATE)
Пример #31
0
    def setUpClass(cls):
        """Run before all tests:
        Creates an auth configuration"""
        cls.port = QGIS_SERVER_ENDPOINT_PORT
        # Clean env just to be sure
        env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE']
        for ev in env_vars:
            try:
                del os.environ[ev]
            except KeyError:
                pass
        cls.testdata_path = unitTestDataPath('qgis_server') + '/'
        cls.project_path = cls.testdata_path + "test_project.qgs"
        # Enable auth
        # os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
        authm = QgsAuthManager.instance()
        assert (authm.setMasterPassword('masterpassword', True))
        cls.auth_config = QgsAuthMethodConfig('Basic')
        cls.auth_config.setName('test_auth_config')
        cls.username = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(6))
        cls.password = cls.username[::-1]  # reversed
        cls.auth_config.setConfig('username', cls.username)
        cls.auth_config.setConfig('password', cls.password)
        assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
        cls.hostname = '127.0.0.1'
        cls.protocol = 'http'

        os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1'
        os.environ['QGIS_SERVER_USERNAME'] = cls.username
        os.environ['QGIS_SERVER_PASSWORD'] = cls.password
        os.environ['QGIS_SERVER_PORT'] = str(cls.port)
        os.environ['QGIS_SERVER_HOST'] = cls.hostname

        server_path = os.path.dirname(os.path.realpath(__file__)) + \
            '/qgis_wrapped_server.py'
        cls.server = subprocess.Popen([sys.executable, server_path],
                                      env=os.environ,
                                      stdout=subprocess.PIPE)

        line = cls.server.stdout.readline()
        cls.port = int(re.findall(b':(\d+)', line)[0])
        assert cls.port != 0
        # Wait for the server process to start
        assert waitServer(
            '%s://%s:%s' % (cls.protocol, cls.hostname, cls.port)
        ), "Server is not responding! %s://%s:%s" % (cls.protocol,
                                                     cls.hostname, cls.port)
Пример #32
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)
Пример #33
0
def config_entries():
    """
    :return: Returns a list of tuples with each tuple containing the ID
    and name of an authentication configuration entry stored in QGIS's
    authentication framework.
    :rtype: list
    """
    auth_configs = []
    auth_mgr = QgsAuthManager.instance()
    conf_map = auth_mgr.availableAuthMethodConfigs()
    for id, conf in conf_map.iteritems():
        name = conf.name()
        auth_configs.append((id, name))

    return auth_configs
Пример #34
0
    def setUpClass(cls):
        cls.data_dir = os.path.join(os.path.dirname(__file__), 'data')
        cls.authcfg = None
        if hasattr(QgsApplication, 'authManager'):
            cls.authm = QgsApplication.authManager()  # QGIS 3
        else:
            cls.authm = QgsAuthManager.instance()  # QGIS 2
        assert cls.authm is not None, 'QgsAuthManager instance not available'
        assert not cls.authm.isDisabled(), cls.authm.disabledMessage()
        cls.mpass = AUTHDB_MASTERPWD  # master password

        if AUTHDBDIR is not None:
            db1 = QFileInfo(cls.authm.authenticationDbPath()).canonicalFilePath()
            db2 = QFileInfo(AUTHDBDIR + '/qgis-auth.db').canonicalFilePath()
            msg = 'Auth db temp path does not match db path of manager'
            assert db1 == db2, msg
    def setUpClass(cls):
        cls.data_dir = os.path.join(os.path.dirname(__file__), 'data')
        cls.local_maps_uri = os.path.join(cls.data_dir, 'basemaps.json')
        cls.local_providers_uri = os.path.join(cls.data_dir, 'providers.json')
        cls.tpl_path = os.path.join(
            os.path.dirname(__file__), os.path.pardir, 'project_default.qgs.tpl')
        cls.authcfg = None
        cls.authm = QgsAuthManager.instance()
        assert not cls.authm.isDisabled(), cls.authm.disabledMessage()
        cls.mpass = AUTHDB_MASTERPWD  # master password

        if AUTHDBDIR is not None:
            db1 = QFileInfo(cls.authm.authenticationDbPath()).canonicalFilePath()
            db2 = QFileInfo(AUTHDBDIR + '/qgis-auth.db').canonicalFilePath()
            msg = 'Auth db temp path does not match db path of manager'
            assert db1 == db2, msg
Пример #36
0
    def setUpAuth(cls):
        """Run before all tests and set up authentication"""
        authm = QgsAuthManager.instance()
        assert (authm.setMasterPassword('masterpassword', True))
        cls.sslrootcert_path = os.path.join(
            cls.certsdata_path,
            'chains_subissuer-issuer-root_issuer2-root2.pem')
        cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem')
        cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem')
        assert os.path.isfile(cls.sslcert)
        assert os.path.isfile(cls.sslkey)
        assert os.path.isfile(cls.sslrootcert_path)
        os.chmod(cls.sslcert, stat.S_IRUSR)
        os.chmod(cls.sslkey, stat.S_IRUSR)
        os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
        cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
        cls.auth_config.setConfig('certpath', cls.sslcert)
        cls.auth_config.setConfig('keypath', cls.sslkey)
        cls.auth_config.setName('test_pki_auth_config')
        cls.username = '******'
        cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
        assert cls.sslrootcert is not None
        authm.storeCertAuthorities(cls.sslrootcert)
        authm.rebuildCaCertsCache()
        authm.rebuildTrustedCaCertsCache()
        assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
        assert cls.auth_config.isValid()

        # cls.server_cert = os.path.join(cls.certsdata_path, 'localhost_ssl_cert.pem')
        cls.server_cert = os.path.join(cls.certsdata_path,
                                       '127_0_0_1_ssl_cert.pem')
        # cls.server_key = os.path.join(cls.certsdata_path, 'localhost_ssl_key.pem')
        cls.server_key = os.path.join(cls.certsdata_path,
                                      '127_0_0_1_ssl_key.pem')
        cls.server_rootcert = cls.sslrootcert_path
        os.chmod(cls.server_cert, stat.S_IRUSR)
        os.chmod(cls.server_key, stat.S_IRUSR)
        os.chmod(cls.server_rootcert, stat.S_IRUSR)

        os.environ['QGIS_SERVER_HOST'] = cls.hostname
        os.environ['QGIS_SERVER_PORT'] = str(cls.port)
        os.environ['QGIS_SERVER_PKI_KEY'] = cls.server_key
        os.environ['QGIS_SERVER_PKI_CERTIFICATE'] = cls.server_cert
        os.environ['QGIS_SERVER_PKI_USERNAME'] = cls.username
        os.environ['QGIS_SERVER_PKI_AUTHORITY'] = cls.server_rootcert
    def setUpClass(cls):
        """Run before all tests:
        Creates an auth configuration"""
        cls.port = QGIS_SERVER_ENDPOINT_PORT
        # Clean env just to be sure
        env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE']
        for ev in env_vars:
            try:
                del os.environ[ev]
            except KeyError:
                pass
        cls.testdata_path = unitTestDataPath('qgis_server') + '/'
        cls.project_path = cls.testdata_path + "test_project.qgs"
        # Enable auth
        #os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE
        authm = QgsAuthManager.instance()
        assert (authm.setMasterPassword('masterpassword', True))
        cls.auth_config = QgsAuthMethodConfig('Basic')
        cls.auth_config.setName('test_auth_config')
        cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
        cls.password = cls.username[::-1] # reversed
        cls.auth_config.setConfig('username', cls.username)
        cls.auth_config.setConfig('password', cls.password)
        assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
        cls.hostname = '127.0.0.1'
        cls.protocol = 'http'

        os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1'
        os.environ['QGIS_SERVER_USERNAME'] = cls.username
        os.environ['QGIS_SERVER_PASSWORD'] = cls.password
        os.environ['QGIS_SERVER_PORT'] = str(cls.port)
        os.environ['QGIS_SERVER_HOST'] = cls.hostname

        server_path = os.path.dirname(os.path.realpath(__file__)) + \
            '/qgis_wrapped_server.py'
        cls.server = subprocess.Popen([sys.executable, server_path],
                                      env=os.environ, stdout=subprocess.PIPE)

        line = cls.server.stdout.readline()
        cls.port = int(re.findall(b':(\d+)', line)[0])
        assert cls.port != 0
        # Wait for the server process to start
        assert waitServer('%s://%s:%s' % (cls.protocol, cls.hostname, cls.port)), "Server is not responding! %s://%s:%s" % (cls.protocol, cls.hostname, cls.port)
Пример #38
0
 def _getOnlineLayer(self, type_name, layer_name=None):
     """
     Return a new WFS layer, overriding the WFS cache
     """
     if layer_name is None:
         layer_name = "wfs_" + type_name
     parms = {
         "srsname": "EPSG:4326",
         "typename": type_name,
         "url": "http://127.0.0.1:%s/%s/?map=%s" % (self.port, self.counter, self.project_path),
         "version": "auto",
         "table": "",
         #'sql': '',
     }
     self.counter += 1
     uri = " ".join([("%s='%s'" % (k, v)) for k, v in list(parms.items())])
     wfs_layer = QgsVectorLayer(uri, layer_name, "WFS")
     wfs_layer.setParent(QgsAuthManager.instance())
     assert wfs_layer.isValid()
     return wfs_layer
Пример #39
0
    def setUpAuth(cls):
        """Run before all tests and set up authentication"""
        authm = QgsAuthManager.instance()
        assert (authm.setMasterPassword('masterpassword', True))
        cls.sslrootcert_path = os.path.join(cls.certsdata_path, 'chains_subissuer-issuer-root_issuer2-root2.pem')
        cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem')
        cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem')
        assert os.path.isfile(cls.sslcert)
        assert os.path.isfile(cls.sslkey)
        assert os.path.isfile(cls.sslrootcert_path)
        os.chmod(cls.sslcert, stat.S_IRUSR)
        os.chmod(cls.sslkey, stat.S_IRUSR)
        os.chmod(cls.sslrootcert_path, stat.S_IRUSR)
        cls.auth_config = QgsAuthMethodConfig("PKI-Paths")
        cls.auth_config.setConfig('certpath', cls.sslcert)
        cls.auth_config.setConfig('keypath', cls.sslkey)
        cls.auth_config.setName('test_pki_auth_config')
        cls.username = '******'
        cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path)
        assert cls.sslrootcert is not None
        authm.storeCertAuthorities(cls.sslrootcert)
        authm.rebuildCaCertsCache()
        authm.rebuildTrustedCaCertsCache()
        assert (authm.storeAuthenticationConfig(cls.auth_config)[0])
        assert cls.auth_config.isValid()

        # cls.server_cert = os.path.join(cls.certsdata_path, 'localhost_ssl_cert.pem')
        cls.server_cert = os.path.join(cls.certsdata_path, '127_0_0_1_ssl_cert.pem')
        # cls.server_key = os.path.join(cls.certsdata_path, 'localhost_ssl_key.pem')
        cls.server_key = os.path.join(cls.certsdata_path, '127_0_0_1_ssl_key.pem')
        cls.server_rootcert = cls.sslrootcert_path
        os.chmod(cls.server_cert, stat.S_IRUSR)
        os.chmod(cls.server_key, stat.S_IRUSR)
        os.chmod(cls.server_rootcert, stat.S_IRUSR)

        os.environ['QGIS_SERVER_HOST'] = cls.hostname
        os.environ['QGIS_SERVER_PORT'] = str(cls.port)
        os.environ['QGIS_SERVER_PKI_KEY'] = cls.server_key
        os.environ['QGIS_SERVER_PKI_CERTIFICATE'] = cls.server_cert
        os.environ['QGIS_SERVER_PKI_USERNAME'] = cls.username
        os.environ['QGIS_SERVER_PKI_AUTHORITY'] = cls.server_rootcert
Пример #40
0
 def _getOnlineLayer(self, type_name, layer_name=None):
     """
     Return a new WFS layer, overriding the WFS cache
     """
     if layer_name is None:
         layer_name = 'wfs_' + type_name
     parms = {
         'srsname': 'EPSG:4326',
         'typename': type_name,
         'url': 'http://127.0.0.1:%s/%s/?map=%s' % (self.port,
                                                    self.counter,
                                                    self.project_path),
         'version': 'auto',
         'table': '',
         #'sql': '',
     }
     self.counter += 1
     uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())])
     wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS')
     wfs_layer.setParent(QgsAuthManager.instance())
     assert wfs_layer.isValid()
     return wfs_layer
Пример #41
0
def auth_config_from_id(config_id):
    """
    Gets authentication configuration object containing the username and
    password for the configuration object with the given ID.
    :param config_id: Configuration ID stored in the QGIS authentication
    framework.
    :return: Returns a QgsAuthMethodConfig object containing the username
    and password else None if the configuration ID is invalid.
    :rtype: QgsAuthMethodConfig
    """
    auth_mgr = QgsAuthManager.instance()
    if not config_id in auth_mgr.configIds():
        return None

    # Object containing authentication information
    auth_config = QgsAuthMethodConfig()
    status, auth_config = auth_mgr.loadAuthenticationConfig(
        config_id, auth_config, True)
    if not status:
        return None

    return auth_config
Пример #42
0
    def requestFetching(self, key):
        """ start fetching the repository given by key """
        self.mRepositories[key]["state"] = 1
        url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
        # v=str(QGis.QGIS_VERSION_INT)
        # url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!

        self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
        authcfg = self.mRepositories[key]["authcfg"]
        if authcfg and isinstance(authcfg, basestring):
            if not QgsAuthManager.instance().updateNetworkRequest(self.mRepositories[key]["QRequest"], authcfg.strip()):
                msg = QCoreApplication.translate(
                    "QgsPluginInstaller",
                    "Update of network request with authentication " "credentials FAILED for configuration '{0}'",
                ).format(authcfg)
                iface.pluginManagerInterface().pushMessage(msg, QgsMessageBar.WARNING)
                self.mRepositories[key]["QRequest"] = None
                return
        self.mRepositories[key]["QRequest"].setAttribute(QNetworkRequest.User, key)
        self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance().get(self.mRepositories[key]["QRequest"])
        self.mRepositories[key]["xmlData"].setProperty("reposName", key)
        self.mRepositories[key]["xmlData"].downloadProgress.connect(self.mRepositories[key]["Relay"].dataReadProgress)
        self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
Пример #43
0
def bcs_supported():
    """Check wether current QGIS installation has all requirements to
    consume BCS services, current checks
    - OAuth2 auth plugin is available
    """
    return 'OAuth2' in QgsAuthManager.instance().authMethodsKeys()
Пример #44
0
    def request(self,
                url,
                method="GET",
                body=None,
                headers=None,
                redirections=DEFAULT_MAX_REDIRECTS,
                connection_type=None):
        """
        Make a network request by calling QgsNetworkAccessManager.
        redirections argument is ignored and is here only for httplib2 compatibility.
        """
        self.msg_log(u'http_call request: {0}'.format(url))
        self.http_call_result = Response({
            'status': 0,
            'status_code': 0,
            'status_message': '',
            'text': '',
            'ok': False,
            'headers': {},
            'reason': '',
            'exception': None,
        })
        req = QNetworkRequest()
        # Avoid double quoting form QUrl
        if PYTHON_VERSION >= 3:
            url = urllib.parse.unquote(url)
        else:
            url = urllib2.unquote(url)
        req.setUrl(QUrl(url))

        if self.cookie is not None:
            if headers is not None:
                headers['Cookie'] = self.cookie
            else:
                headers = {'Cookie': self.cookie}

        if self.basicauth is not None:
            if headers is not None:
                headers['Authorization'] = self.basicauth
            else:
                headers = {'Authorization': self.basicauth}

        if headers is not None:
            # This fixes a wierd error with compressed content not being correctly
            # inflated.
            # If you set the header on the QNetworkRequest you are basically telling
            # QNetworkAccessManager "I know what I'm doing, please don't do any content
            # encoding processing".
            # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
            try:
                del headers['Accept-Encoding']
            except KeyError:
                pass
            for k, v in headers.items():
                if PYTHON_VERSION >= 3:
                    if isinstance(k, str):
                        k = k.encode('utf-8')
                    if isinstance(v, str):
                        v = v.encode('utf-8')
                req.setRawHeader(k, v)

        if self.authid:
            self.msg_log("Update request w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkRequest(req, self.authid)
        if self.reply is not None and self.reply.isRunning():
            self.reply.close()
        if method.lower() == 'delete':
            func = getattr(QgsNetworkAccessManager.instance(),
                           'deleteResource')
        else:
            func = getattr(QgsNetworkAccessManager.instance(), method.lower())
        # Calling the server ...
        # Let's log the whole call for debugging purposes:
        self.msg_log("Sending %s request to %s" %
                     (method.upper(), req.url().toString()))
        headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}
        for k, v in headers.items():
            self.msg_log("%s: %s" % (k, v))
        if method.lower() in ['post', 'put']:
            if PYTHON_VERSION >= 3:
                if isinstance(body, str):
                    body = body.encode('utf-8')
            self.reply = func(req, body)
        else:
            self.reply = func(req)
        if self.authid:
            self.msg_log("Update reply w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkReply(
                self.reply, self.authid)

        self.reply.sslErrors.connect(self.sslErrors)
        self.reply.finished.connect(self.replyFinished)

        # Call and block
        self.el = QEventLoop()
        self.reply.finished.connect(self.el.quit)
        self.reply.downloadProgress.connect(self.downloadProgress)

        # Catch all exceptions (and clean up requests)
        try:
            self.el.exec_()
            # Let's log the whole response for debugging purposes:
            self.msg_log("Got response %s %s from %s" % \
                        (self.http_call_result.status_code,
                         self.http_call_result.status_message,
                         self.reply.url().toString()))
            headers = {
                str(h): str(self.reply.rawHeader(h))
                for h in self.reply.rawHeaderList()
            }
            for k, v in headers.items():
                self.msg_log("%s: %s" % (k, v))
            if len(self.http_call_result.text) < 1024:
                self.msg_log("Payload :\n%s" % self.http_call_result.text)
            else:
                self.msg_log("Payload is > 1 KB ...")
        except Exception as e:
            raise e
        finally:
            if self.reply is not None:
                if self.reply.isRunning():
                    self.reply.close()
                self.msg_log("Deleting reply ...")
                self.reply.deleteLater()
                self.reply = None
            else:
                self.msg_log("Reply was already deleted ...")
        if not self.http_call_result.ok:
            if self.http_call_result.exception and not self.exception_class:
                raise self.http_call_result.exception
            else:
                raise self.exception_class(self.http_call_result.reason)
        return (self.http_call_result, self.http_call_result.text)
    def request(self, url, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
        """
        Make a network request by calling QgsNetworkAccessManager.
        redirections argument is ignored and is here only for httplib2 compatibility.
        """
        self.msg_log(u'http_call request: {0}'.format(url))
        self.http_call_result = Response({
            'status': 0,
            'status_code': 0,
            'status_message': '',
            'text' : '',
            'ok': False,
            'headers': {},
            'reason': '',
            'exception': None,
        })
        req = QNetworkRequest()
        req.setUrl(QUrl(url))
        if headers is not None:
            # This fixes a wierd error with compressed content not being correctly
            # inflated.
            # If you set the header on the QNetworkRequest you are basically telling
            # QNetworkAccessManager "I know what I'm doing, please don't do any content
            # encoding processing".
            # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
            try:
                del headers['Accept-Encoding']
            except KeyError:
                pass
            for k, v in headers.items():
                self.msg_log("Setting header %s to %s" % (k, v))
                req.setRawHeader(k, v)
        if self.authid:
            self.msg_log("Update request w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkRequest(req, self.authid)
        if self.reply is not None and self.reply.isRunning():
            self.reply.close()
        if method.lower() == 'delete':
            func = getattr(QgsNetworkAccessManager.instance(), 'deleteResource')
        else:
            func = getattr(QgsNetworkAccessManager.instance(), method.lower())
        # Calling the server ...
        # Let's log the whole call for debugging purposes:
        self.msg_log("Sending %s request to %s" % (method.upper(), req.url().toString()))
        headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}
        for k, v in headers.items():
            self.msg_log("%s: %s" % (k, v))
        if method.lower() in ['post', 'put']:
            if isinstance(body, file):
                body = body.read()
            self.reply = func(req, body)
        else:
            self.reply = func(req)
        if self.authid:
            self.msg_log("Update reply w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkReply(self.reply, self.authid)

        self.reply.sslErrors.connect(self.sslErrors)
        self.reply.finished.connect(self.replyFinished)

        # Call and block
        self.el = QEventLoop()
        self.reply.finished.connect(self.el.quit)
        self.reply.downloadProgress.connect(self.downloadProgress)

        # Catch all exceptions (and clean up requests)
        try:
            self.el.exec_()
            # Let's log the whole response for debugging purposes:
            self.msg_log("Got response %s %s from %s" % \
                        (self.http_call_result.status_code,
                         self.http_call_result.status_message,
                         self.reply.url().toString()))
            headers = {str(h): str(self.reply.rawHeader(h)) for h in self.reply.rawHeaderList()}
            for k, v in headers.items():
                self.msg_log("%s: %s" % (k, v))
            if len(self.http_call_result.text) < 1024:
                self.msg_log("Payload :\n%s" % self.http_call_result.text)
            else:
                self.msg_log("Payload is > 1 KB ...")
        except Exception, e:
            raise e
Пример #46
0
# only once on a fresh QGIS installation before the user 
# started QGIS for the first time.


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)
Пример #47
0
    def request(self, url, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, blocking=True):
        """
        Make a network request by calling QgsNetworkAccessManager.
        redirections argument is ignored and is here only for httplib2 compatibility.
        """
        self.msg_log(u'http_call request: {0}'.format(url))

        self.blocking_mode = blocking
        req = QNetworkRequest()
        # Avoid double quoting form QUrl
        url = urllib.parse.unquote(url)
        req.setUrl(QUrl(url))
        if headers is not None:
            # This fixes a wierd error with compressed content not being correctly
            # inflated.
            # If you set the header on the QNetworkRequest you are basically telling
            # QNetworkAccessManager "I know what I'm doing, please don't do any content
            # encoding processing".
            # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
            try:
                del headers['Accept-Encoding']
            except KeyError:
                pass
            for k, v in list(headers.items()):
                self.msg_log("Setting header %s to %s" % (k, v))
                req.setRawHeader(k, v)
        if self.authid:
            self.msg_log("Update request w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkRequest(req, self.authid)
        if self.reply is not None and self.reply.isRunning():
            self.reply.close()
        if method.lower() == 'delete':
            func = getattr(QgsNetworkAccessManager.instance(), 'deleteResource')
        else:
            func = getattr(QgsNetworkAccessManager.instance(), method.lower())
        # Calling the server ...
        # Let's log the whole call for debugging purposes:
        self.msg_log("Sending %s request to %s" % (method.upper(), req.url().toString()))
        self.on_abort = False
        headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}
        for k, v in list(headers.items()):
            self.msg_log("%s: %s" % (k, v))
        if method.lower() in ['post', 'put']:
            if isinstance(body, file):
                body = body.read()
            self.reply = func(req, body)
        else:
            self.reply = func(req)
        if self.authid:
            self.msg_log("Update reply w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkReply(self.reply, self.authid)

        # necessary to trap local timout manage by QgsNetworkAccessManager
        # calling QgsNetworkAccessManager::abortRequest
        QgsNetworkAccessManager.instance().requestTimedOut.connect(self.requestTimedOut)

        self.reply.sslErrors.connect(self.sslErrors)
        self.reply.finished.connect(self.replyFinished)
        self.reply.downloadProgress.connect(self.downloadProgress)

        # block if blocking mode otherwise return immediatly
        # it's up to the caller to manage listeners in case of no blocking mode
        if not self.blocking_mode:
            return (None, None)

        # Call and block
        self.el = QEventLoop()
        self.reply.finished.connect(self.el.quit)

        # Catch all exceptions (and clean up requests)
        try:
            self.el.exec_(QEventLoop.ExcludeUserInputEvents)
        except Exception as e:
            raise e

        if self.reply:
            self.reply.finished.disconnect(self.el.quit)

        # emit exception in case of error
        if not self.http_call_result.ok:
            if self.http_call_result.exception and not self.exception_class:
                raise self.http_call_result.exception
            else:
                raise self.exception_class(self.http_call_result.reason)

        return (self.http_call_result, self.http_call_result.content)
Пример #48
0
def main(user='', masterpass='', pkidir=''):
    if not user or not pkidir:
        print 'Missing parameters for user or pkidir'
        print '  user: {0}'.format(user)
        print '  pkidir: {0}'.format(pkidir)
        sys.exit(1)

    # Get user's pre-defined QGIS master password.
    # This can be done in a variety of ways, depending upon user auth
    # systems (queried from LDAP, etc.), using a variety of Python packages.
    # As an example, we could hard-code define it as a standard password that
    # must be changed later by user, OR if we know the user's defined password.
    #masterpass = some_user_query_function(user)

    if not masterpass:
        print 'Master password must be defined'
        sys.exit(1)

    print 'Setting authentication config using:'
    print '  user: {0}'.format(user)
    print '  master pass: {0}'.format(masterpass)
    print '  pkidir: {0}'.format(pkidir)

    # instantiate QGIS
    qgsapp = QgsApplication(sys.argv, True)

    # These are for referencing the correct QSettings for the QGIS app
    QCoreApplication.setOrganizationName('QGIS')
    QCoreApplication.setOrganizationDomain('qgis.org')
    QCoreApplication.setApplicationName('QGIS2')

    # Initialize QGIS
    qgsapp.initQgis()
    print qgsapp.showSettings()

    # Initialize the auth system
    # noinspection PyArgumentList
    authm = QgsAuthManager.instance()
    authm.init()
    # This will use the standard qgis-auth.db location, but the rest of this
    # script will not work if qgis-auth.db already exists and you do NOT know
    # the user's chosen master password already stored in it.

    # If you want to generate individual qgis-auth.db for a list of users, just
    # do:
    #   authdbdir = tempfile.mkdtemp()
    #   authm.init(authdbdir)
    # Note that the saved paths to PKI components in the db will need to be the
    # same absolute paths as when the auth db is copied to the user's machine.
    # This means paths with the current user's name in them will not work when
    # copied to a different user (unless names are the same).

    print authm.authenticationDbPath()

    # Define pool of users and loop through them, or use the current user.
    #users = ["user"]
    #for user in users:

    # Set master password for QGIS and (optionally) store it in qgis-auth.db.
    # This also verifies the set password against by comparing password
    # against its derived hash stored in auth db.
    if not authm.setMasterPassword(masterpass, True):
        print 'Failed to verify or store/verify password'
        sys.exit(1)

    # Now that we have a master password set/stored, we can use it to
    # encrypt and store authentication configurations.
    # There are 3 configurations that can be stored (as of Nov 2014), and
    # examples of their initialization are in the unit tests for
    # QGIS-with-PKI source tree (test_qgsauthsystem_api-sample.py).

    # Add authentication configuration.
    # You can add as many auth configs as needed, but only one can be linked
    # to a given custom server config; although, you can create as many custom
    # server configs as needed. In this example, we are defining only one auth
    # config and linking it to multiple custom server configs, representing
    # different OWS services located at the same domain.

    # NOTE: PKI file components need to *already* exist on the filesystem in a
    # location that doesn't change, as their paths are stored in the auth db.

    # # Basic configuration
    # configname = 'My Basic Config'
    # config = QgsAuthConfigBasic()
    # config.setName(kind)
    # config.setUri('https://localhost:8443')
    # config.setUsername('username')
    # config.setPassword('password')  # will need queried or set per user
    # config.setRealm('Realm')

    # ^^  OR  vv

    # # PKI-Paths (PEM-based) configuration
    # configname = 'My PKI Paths Config'
    # config = QgsAuthConfigPkiPaths()
    # config.setName(configname)
    # config.setUri('https://localhost:8443')
    # config.setCertId(os.path.join(pkidir, '{0}_cert.pem'.format(user)))
    # config.setKeyId(os.path.join(pkidir, '{0}_key.pem'.format(user)))
    # config.setKeyPassphrase('')  # will need queried and set per user
    # config.setIssuerId(os.path.join(pkidir, 'ca.pem'))
    # config.setIssuerSelfSigned(True)

    # ^^  OR  vv

    # PKI-PKCS#12 (*.p12-based) configuration
    configname = 'My PKI PKCS#12 Config'
    config = QgsAuthConfigPkiPkcs12()
    config.setName(configname)
    config.setUri('https://localhost:8443')
    config.setBundlePath(os.path.join(pkidir, '{0}.p12'.format(user)))
    config.setBundlePassphrase(
        'password')  # will need queried and set per user
    config.setIssuerPath(os.path.join(pkidir, 'ca.pem'))
    config.setIssuerSelfSigned(True)

    # Securely store the config in database (encrypted with master password)
    res = authm.storeAuthenticationConfig(config)
    if not res[0]:
        print 'Failed to store {0} config'.format(configname)
        sys.exit(1)

    # The auth config has been given a unique ID from the auth system when it
    # was stored; retrieve it, so it can be linked to a custom server config.
    configid = config.id()

    # If the user does not have the OWS connection(s) that this auth config is
    # meant to connect to, define now.
    # NOTE: this assumes the individual connections do not already exist. If the
    # connection settings do exist, this will OVERWRITE them.

    settings = QSettings()  # get application's settings object

    print 'settings.fileName(): {0}'.format(settings.fileName())
    print 'settings.organizationName(): {0}'.format(
        settings.organizationName())
    print 'settings.applicationName(): {0}'.format(settings.applicationName())

    # WMS
    connkind = 'WMS'
    connname = 'My {0} SSL Server'.format(connkind)
    credskey = '/Qgis/{0}/{1}'.format(connkind, connname)
    connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname)

    settings.setValue(credskey + '/authid', configid)  # link to auth config
    settings.setValue(credskey + '/username',
                      '')  # deprecated; use auth config
    settings.setValue(credskey + '/password',
                      '')  # deprecated; use auth config

    settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wms')

    # Optional settings for WMS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + '/dpiMode', 7)
    settings.setValue(connkey + '/ignoreAxisOrientation', False)
    settings.setValue(connkey + '/ignoreGetFeatureInfoURI', False)
    settings.setValue(connkey + '/ignoreGetMapURI', False)
    settings.setValue(connkey + '/invertAxisOrientation', False)
    settings.setValue(connkey + '/referer', '')
    settings.setValue(connkey + '/smoothPixmapTransform', False)

    # WCS
    connkind = 'WCS'
    connname = 'My {0} SSL Server'.format(connkind)
    credskey = '/Qgis/{0}/{1}'.format(connkind, connname)
    connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname)

    settings.setValue(credskey + '/authid', configid)  # link to auth config
    settings.setValue(credskey + '/username',
                      '')  # deprecated; use auth config
    settings.setValue(credskey + '/password',
                      '')  # deprecated; use auth config

    settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wcs')

    # Optional settings for WCS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + '/dpiMode', 7)
    settings.setValue(connkey + '/ignoreAxisOrientation', False)
    settings.setValue(connkey + '/ignoreGetMapURI', False)
    settings.setValue(connkey + '/invertAxisOrientation', False)
    settings.setValue(connkey + '/referer', '')
    settings.setValue(connkey + '/smoothPixmapTransform', False)

    # WFS
    connkind = 'WFS'
    connname = 'My {0} SSL Server'.format(connkind)
    credskey = '/Qgis/{0}/{1}'.format(connkind, connname)
    connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname)

    settings.setValue(credskey + '/authid', configid)  # link to auth config
    settings.setValue(credskey + '/username',
                      '')  # deprecated; use auth config
    settings.setValue(credskey + '/password',
                      '')  # deprecated; use auth config

    settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wfs')

    # Optional settings for WFS (these are the defaults)
    settings.setValue(connkey + '/referer', '')
Пример #49
0
    def request(self,
                url,
                method="GET",
                body=None,
                headers=None,
                redirections=DEFAULT_MAX_REDIRECTS,
                connection_type=None,
                blocking=True):
        """
        Make a network request by calling QgsNetworkAccessManager.
        redirections argument is ignored and is here only for httplib2 compatibility.
        """
        self.http_call_result.url = url
        self.msg_log(u'http_call request: {0}'.format(url))

        self.blocking_mode = blocking
        req = QNetworkRequest()
        # Avoid double quoting form QUrl
        url = urllib.parse.unquote(url)
        req.setUrl(QUrl(url))
        if headers is not None:
            # This fixes a weird error with compressed content not being correctly
            # inflated.
            # If you set the header on the QNetworkRequest you are basically telling
            # QNetworkAccessManager "I know what I'm doing, please don't do any content
            # encoding processing".
            # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
            try:
                del headers['Accept-Encoding']
            except KeyError:
                pass
            for k, v in list(headers.items()):
                self.msg_log("Setting header %s to %s" % (k, v))
                req.setRawHeader(k, v)
        if self.authid:
            self.msg_log("Update request w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkRequest(req, self.authid)
        if self.reply is not None and self.reply.isRunning():
            self.reply.close()
        if method.lower() == 'delete':
            func = getattr(QgsNetworkAccessManager.instance(),
                           'deleteResource')
        else:
            func = getattr(QgsNetworkAccessManager.instance(), method.lower())
        # Calling the server ...
        # Let's log the whole call for debugging purposes:
        self.msg_log("Sending %s request to %s" %
                     (method.upper(), req.url().toString()))
        self.on_abort = False
        headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}
        for k, v in list(headers.items()):
            self.msg_log("%s: %s" % (k, v))
        if method.lower() in ['post', 'put']:
            if isinstance(body, file):
                body = body.read()
            self.reply = func(req, body)
        else:
            self.reply = func(req)
        if self.authid:
            self.msg_log("Update reply w/ authid: {0}".format(self.authid))
            QgsAuthManager.instance().updateNetworkReply(
                self.reply, self.authid)

        # necessary to trap local timeout manage by QgsNetworkAccessManager
        # calling QgsNetworkAccessManager::abortRequest
        QgsNetworkAccessManager.instance().requestTimedOut.connect(
            self.requestTimedOut)

        self.reply.sslErrors.connect(self.sslErrors)
        self.reply.finished.connect(self.replyFinished)
        self.reply.downloadProgress.connect(self.downloadProgress)

        # block if blocking mode otherwise return immediately
        # it's up to the caller to manage listeners in case of no blocking mode
        if not self.blocking_mode:
            return None, None

        # Call and block
        self.el = QEventLoop()
        self.reply.finished.connect(self.el.quit)

        # Catch all exceptions (and clean up requests)
        try:
            self.el.exec_(QEventLoop.ExcludeUserInputEvents)
        except Exception as e:
            raise e

        if self.reply:
            self.reply.finished.disconnect(self.el.quit)

        # emit exception in case of error
        if not self.http_call_result.ok:
            if self.http_call_result.exception and not self.exception_class:
                raise self.http_call_result.exception
            elif self.exception_class:
                raise self.exception_class(self.http_call_result.reason)
            else:
                raise RequestsException('Unknown reason')

        return self.http_call_result, self.http_call_result.content
# only once on a fresh QGIS installation before the user 
# started QGIS for the first time.


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)
    def __init__(self, parent=None, visible=False):
        super(ConnectDockWidget, self).__init__(parent)
        self.setupUi(self)

        self.loggedIn = False
        self.token = None

        self.progressBar.hide()

        self.setVisible(visible)

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

        self.lblSmallLogo.setPixmap(QPixmap(os.path.join(pluginPath, 'icons', 'connect.png')))
        self.lblSmallLogo.hide()

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

        # setup tab bar
        self.tabsContent.addTab('Knowledge')
        self.tabsContent.addTab('Data')
        self.tabsContent.addTab('Plugins')
        self.tabsContent.setDocumentMode(True)
        self.tabsContent.setDrawBase(False)
        self._toggleCategoriesSelector(True)
        self.tabsContent.setCurrentIndex(0)
        self.tabsContent.currentChanged.connect(self.tabChanged)

        self.buttonBox.helpRequested.connect(self.showHelp)
        self.buttonBox.accepted.connect(self.logIn)
        self.btnSignOut.clicked.connect(self.showLogin)

        self.labelLevel.linkActivated.connect(self.showLogin)
        self.leSearch.buttonClicked.connect(self.search)
        self.leSearch.returnPressed.connect(self.search)
        self.connectWidget.rememberStateChanged.connect(self.updateSettings)

        self.webView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        cssFile = os.path.join(pluginPath, "resources", "search.css")
        with open(cssFile) as f:
            content = f.read()

        self.css = content.replace("#PLUGIN_PATH#", QUrl.fromLocalFile(pluginPath).toString())

        self.webView.linkClicked.connect(self.linkClicked)

        for cat, cls in connect.categories.items():
            self.cmbContentType.addItem(cls[1], cat)

        settings = QSettings()
        settings.beginGroup(reposGroup)
        self.authId = settings.value(boundlessRepoName + '/authcfg', '')
        settings.endGroup()
        if self.authId not in QgsAuthManager.instance().configIds():
            self.authId = ''
            utils.setRepositoryAuth(self.authId)

        self._toggleSearchControls(True)
        self.showLogin()
def main(user="", masterpass="", pkidir=""):
    if not user or not pkidir:
        print "Missing parameters for user or pkidir"
        print "  user: {0}".format(user)
        print "  pkidir: {0}".format(pkidir)
        sys.exit(1)

    # Get user's pre-defined QGIS master password.
    # This can be done in a variety of ways, depending upon user auth
    # systems (queried from LDAP, etc.), using a variety of Python packages.
    # As an example, we could hard-code define it as a standard password that
    # must be changed later by user, OR if we know the user's defined password.
    # masterpass = some_user_query_function(user)

    if not masterpass:
        print "Master password must be defined"
        sys.exit(1)

    print "Setting authentication config using:"
    print "  user: {0}".format(user)
    print "  master pass: {0}".format(masterpass)
    print "  pkidir: {0}".format(pkidir)

    # instantiate QGIS
    qgsapp = QgsApplication(sys.argv, True)

    # These are for referencing the correct QSettings for the QGIS app
    QCoreApplication.setOrganizationName("QGIS")
    QCoreApplication.setOrganizationDomain("qgis.org")
    QCoreApplication.setApplicationName("QGIS2")

    # Initialize QGIS
    qgsapp.initQgis()
    print qgsapp.showSettings()

    # Initialize the auth system
    # noinspection PyArgumentList
    authm = QgsAuthManager.instance()
    authm.init()
    # This will use the standard qgis-auth.db location, but the rest of this
    # script will not work if qgis-auth.db already exists and you do NOT know
    # the user's chosen master password already stored in it.

    # If you want to generate individual qgis-auth.db for a list of users, just
    # do:
    #   authdbdir = tempfile.mkdtemp()
    #   authm.init(authdbdir)
    # Note that the saved paths to PKI components in the db will need to be the
    # same absolute paths as when the auth db is copied to the user's machine.
    # This means paths with the current user's name in them will not work when
    # copied to a different user (unless names are the same).

    print authm.authenticationDbPath()

    # Define pool of users and loop through them, or use the current user.
    # users = ["user"]
    # for user in users:

    # Set master password for QGIS and (optionally) store it in qgis-auth.db.
    # This also verifies the set password against by comparing password
    # against its derived hash stored in auth db.
    if not authm.setMasterPassword(masterpass, True):
        print "Failed to verify or store/verify password"
        sys.exit(1)

    # Now that we have a master password set/stored, we can use it to
    # encrypt and store authentication configurations.
    # There are 3 configurations that can be stored (as of Nov 2014), and
    # examples of their initialization are in the unit tests for
    # QGIS-with-PKI source tree (test_qgsauthsystem_api-sample.py).

    # Add authentication configuration.
    # You can add as many auth configs as needed, but only one can be linked
    # to a given custom server config; although, you can create as many custom
    # server configs as needed. In this example, we are defining only one auth
    # config and linking it to multiple custom server configs, representing
    # different OWS services located at the same domain.

    # NOTE: PKI file components need to *already* exist on the filesystem in a
    # location that doesn't change, as their paths are stored in the auth db.

    # # Basic configuration
    # configname = 'My Basic Config'
    # config = QgsAuthConfigBasic()
    # config.setName(kind)
    # config.setUri('https://localhost:8443')
    # config.setUsername('username')
    # config.setPassword('password')  # will need queried or set per user
    # config.setRealm('Realm')

    # ^^  OR  vv

    # # PKI-Paths (PEM-based) configuration
    # configname = 'My PKI Paths Config'
    # config = QgsAuthConfigPkiPaths()
    # config.setName(configname)
    # config.setUri('https://localhost:8443')
    # config.setCertId(os.path.join(pkidir, '{0}_cert.pem'.format(user)))
    # config.setKeyId(os.path.join(pkidir, '{0}_key.pem'.format(user)))
    # config.setKeyPassphrase('')  # will need queried and set per user
    # config.setIssuerId(os.path.join(pkidir, 'ca.pem'))
    # config.setIssuerSelfSigned(True)

    # ^^  OR  vv

    # PKI-PKCS#12 (*.p12-based) configuration
    configname = "My PKI PKCS#12 Config"
    config = QgsAuthConfigPkiPkcs12()
    config.setName(configname)
    config.setUri("https://localhost:8443")
    config.setBundlePath(os.path.join(pkidir, "{0}.p12".format(user)))
    config.setBundlePassphrase("password")  # will need queried and set per user
    config.setIssuerPath(os.path.join(pkidir, "ca.pem"))
    config.setIssuerSelfSigned(True)

    # Securely store the config in database (encrypted with master password)
    res = authm.storeAuthenticationConfig(config)
    if not res[0]:
        print "Failed to store {0} config".format(configname)
        sys.exit(1)

    # The auth config has been given a unique ID from the auth system when it
    # was stored; retrieve it, so it can be linked to a custom server config.
    configid = config.id()

    # If the user does not have the OWS connection(s) that this auth config is
    # meant to connect to, define now.
    # NOTE: this assumes the individual connections do not already exist. If the
    # connection settings do exist, this will OVERWRITE them.

    settings = QSettings()  # get application's settings object

    print "settings.fileName(): {0}".format(settings.fileName())
    print "settings.organizationName(): {0}".format(settings.organizationName())
    print "settings.applicationName(): {0}".format(settings.applicationName())

    # WMS
    connkind = "WMS"
    connname = "My {0} SSL Server".format(connkind)
    credskey = "/Qgis/{0}/{1}".format(connkind, connname)
    connkey = "/Qgis/connections-{0}/{1}".format(connkind.lower(), connname)

    settings.setValue(credskey + "/authid", configid)  # link to auth config
    settings.setValue(credskey + "/username", "")  # deprecated; use auth config
    settings.setValue(credskey + "/password", "")  # deprecated; use auth config

    settings.setValue(connkey + "/url", "https://localhost:8443/geoserver/wms")

    # Optional settings for WMS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + "/dpiMode", 7)
    settings.setValue(connkey + "/ignoreAxisOrientation", False)
    settings.setValue(connkey + "/ignoreGetFeatureInfoURI", False)
    settings.setValue(connkey + "/ignoreGetMapURI", False)
    settings.setValue(connkey + "/invertAxisOrientation", False)
    settings.setValue(connkey + "/referer", "")
    settings.setValue(connkey + "/smoothPixmapTransform", False)

    # WCS
    connkind = "WCS"
    connname = "My {0} SSL Server".format(connkind)
    credskey = "/Qgis/{0}/{1}".format(connkind, connname)
    connkey = "/Qgis/connections-{0}/{1}".format(connkind.lower(), connname)

    settings.setValue(credskey + "/authid", configid)  # link to auth config
    settings.setValue(credskey + "/username", "")  # deprecated; use auth config
    settings.setValue(credskey + "/password", "")  # deprecated; use auth config

    settings.setValue(connkey + "/url", "https://localhost:8443/geoserver/wcs")

    # Optional settings for WCS (these are the defaults)
    # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default)
    settings.setValue(connkey + "/dpiMode", 7)
    settings.setValue(connkey + "/ignoreAxisOrientation", False)
    settings.setValue(connkey + "/ignoreGetMapURI", False)
    settings.setValue(connkey + "/invertAxisOrientation", False)
    settings.setValue(connkey + "/referer", "")
    settings.setValue(connkey + "/smoothPixmapTransform", False)

    # WFS
    connkind = "WFS"
    connname = "My {0} SSL Server".format(connkind)
    credskey = "/Qgis/{0}/{1}".format(connkind, connname)
    connkey = "/Qgis/connections-{0}/{1}".format(connkind.lower(), connname)

    settings.setValue(credskey + "/authid", configid)  # link to auth config
    settings.setValue(credskey + "/username", "")  # deprecated; use auth config
    settings.setValue(credskey + "/password", "")  # deprecated; use auth config

    settings.setValue(connkey + "/url", "https://localhost:8443/geoserver/wfs")

    # Optional settings for WFS (these are the defaults)
    settings.setValue(connkey + "/referer", "")