Skip to content
Permalink
Browse files

Add api to retrieve user groups

  • Loading branch information
nyalldawson committed Dec 21, 2020
1 parent d6fa533 commit 23b1533d582335e2312c988312790d7414e3fe17
@@ -42,6 +42,23 @@ If ``user`` is blank then the user associated with the current logon details wil
- errorText: error text of any encountered errors
%End

static QVariantList retrieveUserGroups( const QString &communityUrl, const QString &user, const QString &authcfg, QString &errorTitle /Out/, QString &errorText /Out/, const QMap< QString, QString > &requestHeaders = QMap< QString, QString >(), QgsFeedback *feedback = 0 );
%Docstring
Retrieves JSON definitions for all groups which the specified user name is a member of.

If ``user`` is blank then the user associated with the current logon details will be retrieved

:param communityUrl: should be set to the Portal's community URL, e.g. https://mysite.com/portal/sharing/rest/community
:param user: username to query, or an empty string to query the current user
:param authcfg: authentification configuration ID
:param requestHeaders: optional additional request headers
:param feedback: optional feedback argument for cancelation support

:return: - a list of JSON group info
- errorTitle: title summary of any encountered errrors
- errorText: error text of any encountered errors
%End

};

/************************************************************************
@@ -35,3 +35,9 @@ QVariantMap QgsArcGisPortalUtils::retrieveUserInfo( const QString &communityUrl,

return QgsArcGisRestQueryUtils::queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, feedback );
}

QVariantList QgsArcGisPortalUtils::retrieveUserGroups( const QString &communityUrl, const QString &user, const QString &authcfg, QString &errorTitle, QString &errorText, const QMap<QString, QString> &requestHeaders, QgsFeedback *feedback )
{
const QVariantMap info = retrieveUserInfo( communityUrl, user, authcfg, errorTitle, errorText, requestHeaders, feedback );
return info.value( QStringLiteral( "groups" ) ).toList();
}
@@ -53,6 +53,23 @@ class CORE_EXPORT QgsArcGisPortalUtils
*/
static QVariantMap retrieveUserInfo( const QString &communityUrl, const QString &user, const QString &authcfg, QString &errorTitle SIP_OUT, QString &errorText SIP_OUT, const QMap< QString, QString > &requestHeaders = QMap< QString, QString >(), QgsFeedback *feedback = nullptr );

/**
* Retrieves JSON definitions for all groups which the specified user name is a member of.
*
* If \a user is blank then the user associated with the current logon details will be retrieved
*
* \param communityUrl should be set to the Portal's community URL, e.g. https://mysite.com/portal/sharing/rest/community/
* \param user username to query, or an empty string to query the current user
* \param authcfg authentification configuration ID
* \param errorTitle title summary of any encountered errrors
* \param errorText error text of any encountered errors
* \param requestHeaders optional additional request headers
* \param feedback optional feedback argument for cancelation support
*
* \returns a list of JSON group info
*/
static QVariantList retrieveUserGroups( const QString &communityUrl, const QString &user, const QString &authcfg, QString &errorTitle SIP_OUT, QString &errorText SIP_OUT, const QMap< QString, QString > &requestHeaders = QMap< QString, QString >(), QgsFeedback *feedback = nullptr );

};

#endif // QGSARCGISPORTALUTILS_H
@@ -248,9 +248,9 @@ QUrl QgsArcGisRestQueryUtils::parseUrl( const QUrl &url )
return modifiedUrl;
}

void QgsArcGisRestQueryUtils::adjustBaseUrl( QString &baseUrl, const QString name )
void QgsArcGisRestQueryUtils::adjustBaseUrl( QString &baseUrl, const QString &name )
{
QStringList parts = name.split( '/' );
const QStringList parts = name.split( '/' );
QString checkString;
for ( const QString &part : parts )
{
@@ -102,7 +102,7 @@ class CORE_EXPORT QgsArcGisRestQueryUtils
private:

static QUrl parseUrl( const QUrl &url );
static void adjustBaseUrl( QString &baseUrl, const QString name );
static void adjustBaseUrl( QString &baseUrl, const QString &name );

friend class TestQgsArcGisRestUtils;
};
@@ -14,6 +14,7 @@ ADD_PYTHON_TEST(PyQgsActionManager test_qgsactionmanager.py)
ADD_PYTHON_TEST(PyQgsAFSProvider test_provider_afs.py)
ADD_PYTHON_TEST(PyQgsAggregateMappingWidget test_qgsaggregatemappingwidget.py)
ADD_PYTHON_TEST(PyQgsAlignmentComboBox test_qgsalignmentcombobox.py)
ADD_PYTHON_TEST(PyQgsArcGisPortalUtils test_qgsarcgisportalutils.py)
ADD_PYTHON_TEST(PyQgsPythonProvider test_provider_python.py)
ADD_PYTHON_TEST(PyQgsAggregateCalculator test_qgsaggregatecalculator.py)
ADD_PYTHON_TEST(PyQgsAnnotation test_qgsannotation.py)
@@ -0,0 +1,178 @@
# -*- coding: utf-8 -*-
"""QGIS Unit tests for the AFS provider.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Nyall Dawson'
__date__ = '2018-02-16'
__copyright__ = 'Copyright 2018, Nyall Dawson'

import hashlib
import os
import tempfile

from qgis.PyQt.QtCore import QCoreApplication, QObject
from qgis.core import (QgsArcGisPortalUtils,
QgsApplication,
QgsSettings
)
from qgis.testing import (start_app,
unittest
)


def sanitize(endpoint, x):
if not os.path.exists(endpoint):
os.makedirs(endpoint)
if x.startswith('/query'):
x = x[len('/query'):]
endpoint = endpoint + '_query'

if len(endpoint + x) > 150:
ret = endpoint + hashlib.md5(x.encode()).hexdigest()
# print('Before: ' + endpoint + x)
# print('After: ' + ret)
return ret
return endpoint + x.replace('?', '_').replace('&', '_').replace('<', '_').replace('>', '_').replace('"',
'_').replace(
"'", '_').replace(' ', '_').replace(':', '_').replace('/', '_').replace('\n', '_')


class MessageLogger(QObject):

def __init__(self, tag=None):
QObject.__init__(self)
self.log = []
self.tag = tag

def __enter__(self):
QgsApplication.messageLog().messageReceived.connect(self.logMessage)
return self

def __exit__(self, type, value, traceback):
QgsApplication.messageLog().messageReceived.disconnect(self.logMessage)

def logMessage(self, msg, tag, level):
if tag == self.tag or not self.tag:
self.log.append(msg.encode('UTF-8'))

def messages(self):
return self.log


class TestPyQgsArcGisPortalUtils(unittest.TestCase):

@classmethod
def setUpClass(cls):
"""Run before all tests"""

QCoreApplication.setOrganizationName("QGIS_Test")
QCoreApplication.setOrganizationDomain("TestPyQgsAFSProvider.com")
QCoreApplication.setApplicationName("TestPyQgsAFSProvider")
QgsSettings().clear()
start_app()

# On Windows we must make sure that any backslash in the path is
# replaced by a forward slash so that QUrl can process it
cls.basetestpath = tempfile.mkdtemp().replace('\\', '/')

@classmethod
def tearDownClass(cls):
"""Run after all tests"""
QgsSettings().clear()
# shutil.rmtree(cls.basetestpath, True)

def testUserInfoSelf(self):
"""
Test retrieving logged on user info
"""
print(self.basetestpath)
endpoint = self.basetestpath + '/user_fake_qgis_http_endpoint'
with open(sanitize(endpoint, '/self?f=json'), 'wb') as f:
f.write("""{
"username": "me",
"id": "2a",
"groups": [
{
"id": "c4",
"title": "A Group"
},
{
"id": "d4",
"title": "Another Group"
}
]
}""".encode('UTF-8'))

res = QgsArcGisPortalUtils.retrieveUserInfo('http://' + endpoint, '', '')
# no errors
self.assertFalse(res[1])
self.assertFalse(res[2])
self.assertEqual(res[0], {'groups': [{'id': 'c4', 'title': 'A Group'}, {'id': 'd4', 'title': 'Another Group'}],
'id': '2a', 'username': 'me'})

def testUserInfoExplicit(self):
"""
Test retrieving explicitly specified user info
"""
print(self.basetestpath)
endpoint = self.basetestpath + '/user_fake_qgis_http_endpoint'

with open(sanitize(endpoint + '_users/', 'some_user?f=json'), 'wb') as f:
f.write("""{
"username": "some_user",
"id": "2b",
"groups": [
{
"id": "c4",
"title": "A Group"
},
{
"id": "d4",
"title": "Another Group"
}
]
}""".encode('UTF-8'))

res = QgsArcGisPortalUtils.retrieveUserInfo('http://' + endpoint, 'some_user', '')
# no errors
self.assertFalse(res[1])
self.assertFalse(res[2])
self.assertEqual(res[0], {'groups': [{'id': 'c4', 'title': 'A Group'}, {'id': 'd4', 'title': 'Another Group'}],
'id': '2b', 'username': 'some_user'})

def test_retrieve_groups(self):
"""
Test retrieving user groups
"""
print(self.basetestpath)
endpoint = self.basetestpath + '/group_fake_qgis_http_endpoint'

with open(sanitize(endpoint + '_users/', 'some_user?f=json'), 'wb') as f:
f.write("""{
"username": "some_user",
"id": "2b",
"groups": [
{
"id": "c4",
"title": "A Group"
},
{
"id": "d4",
"title": "Another Group"
}
]
}""".encode('UTF-8'))

res = QgsArcGisPortalUtils.retrieveUserGroups('http://' + endpoint, 'some_user', '')
# no errors
self.assertFalse(res[1])
self.assertFalse(res[2])
self.assertEqual(res[0], [{'id': 'c4', 'title': 'A Group'}, {'id': 'd4', 'title': 'Another Group'}])


if __name__ == '__main__':
unittest.main()

0 comments on commit 23b1533

Please sign in to comment.
You can’t perform that action at this time.