Skip to content

Commit

Permalink
Merge d72d4d3 into 6289a71
Browse files Browse the repository at this point in the history
  • Loading branch information
csenger committed Apr 23, 2019
2 parents 6289a71 + d72d4d3 commit 41f41f2
Show file tree
Hide file tree
Showing 24 changed files with 645 additions and 55 deletions.
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,10 @@ Bugfixes:

New Features:

- Enhance ``@user`` endpoint to save and return groups. In GET groups
are not included unless ``include_groups`` is passed.
[csenger]

- Document the use of the `Accept-Language` HTTP header.
[erral]

Expand Down
1 change: 1 addition & 0 deletions docs/source/_json/.#users_created.req
23 changes: 22 additions & 1 deletion docs/source/users.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ The server will respond with a list the filtered users in the portal with userna

The endpoint also takes a ``limit`` parameter that defaults to a maximum of 25 users at a time for performance reasons.

It also supports an :doc:`expander <expansion>` named ``user-groups`` that includes the groups for each user: ``...?expand=user-groups``.

.. http:example:: curl httpie python-requests
:request: ../../src/plone/restapi/tests/http-examples/users_groups_expander.req

The server will respond with a list of all users in the portal:

.. literalinclude:: ../../src/plone/restapi/tests/http-examples/users_groups_expander.resp
:language: http

Create User
-----------
Expand Down Expand Up @@ -119,6 +128,18 @@ In this case, the server will respond with a 200 OK status code and the JSON res
.. literalinclude:: ../../src/plone/restapi/tests/http-examples/users_authorized_get.resp
:language: http

GET supports an :doc:`expander <expansion>` named ``user-groups`` that includes the groups of the user: ``...?expand=user-groups``.

.. http:example:: curl httpie python-requests
:request: ../../src/plone/restapi/tests/http-examples/users_authorized_get_groups_expander.req

In this case, the server will respond with a 200 OK status code and the JSON respresentation of the user in the body:

.. literalinclude:: ../../src/plone/restapi/tests/http-examples/users_authorized_get_groups_expander.resp
:language: http



Update User
-----------

Expand All @@ -133,7 +154,7 @@ A successful response to a PATCH request will be indicated by a :term:`204 No Co
:language: http

.. note::
The 'roles' object is a mapping of a role and a boolean indicating adding or removing.
The 'roles' and 'groups' object is a mapping of a role/group and a boolean indicating adding or removing.

Any user is able to update their own properties and password (if allowed) by using the same request.

Expand Down
1 change: 1 addition & 0 deletions src/plone/restapi/serializer/configure.zcml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
<adapter factory=".catalog.BrainSerializer" />
<adapter factory=".catalog.LazyCatalogResultSerializer" />

<adapter factory=".user.UserGroupsExpander" name="user-groups"/>
<adapter factory=".user.SerializeUserToJson" />
<adapter factory=".user.SerializeUserToJsonSummary" />
<adapter factory=".group.SerializeGroupToJson" />
Expand Down
42 changes: 42 additions & 0 deletions src/plone/restapi/serializer/user.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
# -*- coding: utf-8 -*-
from plone.restapi.interfaces import IExpandableElement
from plone.restapi.interfaces import ISerializeToJson
from plone.restapi.interfaces import ISerializeToJsonSummary
from plone.restapi.serializer.expansion import expandable_elements
from Products.CMFCore.interfaces._tools import IMemberData
from Products.CMFCore.utils import getToolByName

from Products.CMFPlone.utils import safe_unicode
from zope.component import adapter
from zope.component import getMultiAdapter
from zope.component import getUtility
from zope.component.hooks import getSite
from zope.interface import Interface
from zope.interface import implementer
from zope.publisher.interfaces import IRequest
from zope.schema import getFieldNames
Expand All @@ -21,6 +26,20 @@
HAS_TTW_SCHEMAS = False


def get_groups(portal, request, user):
group_tool = getToolByName(portal, 'portal_groups')
group_ids = group_tool.getGroupsForPrincipal(user)
group_ids = list(set(group_ids) - set(['AuthenticatedUsers']))
groups = []
for group_id in group_ids:
group = group_tool.getGroupById(group_id)
if group:
groups.append(
getMultiAdapter((group, request),
interface=ISerializeToJsonSummary)())
return groups


class BaseSerializer(object):

def __init__(self, context, request):
Expand Down Expand Up @@ -68,9 +87,32 @@ def __call__(self):
value = safe_unicode(value)
data[name] = value

# Insert expandable elements
data.update(expandable_elements(self.context, self.request))

return data


@implementer(IExpandableElement)
@adapter(IMemberData, Interface)
class UserGroupsExpander(object):

def __init__(self, context, request):
self.context = context
self.request = request

def __call__(self, expand=False):
result = {
'user-groups': {
'@id': '{}/@user-groups'.format(self.context.absolute_url()),
},
}
if expand:
result['user-groups']['groups'] = get_groups(
self.context, self.request, self.context)
return result


@implementer(ISerializeToJson)
@adapter(IMemberData, IRequest)
class SerializeUserToJson(BaseSerializer):
Expand Down
10 changes: 8 additions & 2 deletions src/plone/restapi/services/users/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def validate_input_data(self, portal, original_data):

# remove data we don't want to check for
data = {}
for key in ['username', 'email', 'password',
for key in ['username', 'email', 'groups', 'password',
'roles', 'sendPasswordReset']:
if key in original_data:
data[key] = original_data[key]
Expand All @@ -72,6 +72,7 @@ def validate_input_data(self, portal, original_data):
allowed.append('password')
allowed.append('sendPasswordReset')
allowed.append('roles')
allowed.append('groups')
else:
if security.enable_user_pwd_choice:
allowed.append('password')
Expand Down Expand Up @@ -150,6 +151,7 @@ def reply(self):
email = data.pop('email', None)
password = data.pop('password', None)
roles = data.pop('roles', ['Member', ])
groups = data.pop('groups', [])
send_password_reset = data.pop('sendPasswordReset', None)
properties = data

Expand Down Expand Up @@ -204,8 +206,12 @@ def reply(self):
username,
password,
roles,
properties=properties
properties=properties,
)
portal_groups = getToolByName(portal, 'portal_groups')
for group_id in groups:
portal_groups.addPrincipalToGroup(username, group_id)

except ValueError as e:
self.request.response.setStatus(400)
return dict(error=dict(
Expand Down
5 changes: 4 additions & 1 deletion src/plone/restapi/services/users/get.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ def __init__(self, context, request):
super(UsersGet, self).__init__(context, request)
self.params = []
self.query = self.request.form.copy()
# expand is handled in the serializer/expander code
self.query.pop('expand', None)

def publishTraverse(self, request, name):
# Consume any path segments after /@users as parameters
Expand Down Expand Up @@ -65,7 +67,8 @@ def reply(self):
(user, self.request),
ISerializeToJson
)
result.append(serializer())
result.append(
serializer())
return result
else:
self.request.response.setStatus(401)
Expand Down
118 changes: 74 additions & 44 deletions src/plone/restapi/services/users/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,70 @@ def _change_user_password(self, user, value):
acl_users = getToolByName(self.context, 'acl_users')
acl_users.userSetPassword(user.getUserId(), value)

def update_as_manager(self, user, user_settings_to_update):
for key, value in user_settings_to_update.items():
if key == 'password':
self._change_user_password(user, value)
elif key == 'username':
set_own_login_name(user, value)
else:
if key == 'portrait' and value.get('data'):
self.set_member_portrait(user, value)
user.setMemberProperties(mapping={key: value})

roles = user_settings_to_update.get('roles', {})
if roles:
to_add = [key for key, enabled in roles.items() if enabled]
to_remove = [key for key, enabled in roles.items()
if not enabled]

target_roles = set(user.getRoles()) - set(to_remove)
target_roles = target_roles | set(to_add)

acl_users = getToolByName(self.context, 'acl_users')
acl_users.userFolderEditUser(
principal_id=user.id,
password=None,
roles=target_roles,
domains=user.getDomains(),
)

groups = user_settings_to_update.get('groups', {})
if groups:
to_add = [key for key, enabled in groups.items() if enabled]
to_remove = [key for key, enabled in groups.items()
if not enabled]
groups_tool = getToolByName(self.context, 'portal_groups')
current = groups_tool.getGroupsForPrincipal(user)
for group in to_add:
if group not in current:
groups_tool.addPrincipalToGroup(user.id, group)
for group in to_remove:
if group in current:
groups_tool.removePrincipalFromGroup(user.id, group)

def update_own_settings(self, user, user_settings_to_update):
if not self.can_manage_users:
if 'roles' in user_settings_to_update:
return self._error(
403, 'Forbidden',
'You can\'t update your roles')
if 'groups' in user_settings_to_update:
return self._error(
403, 'Forbidden',
'You can\'t update your groups')

for key, value in user_settings_to_update.items():
security = getAdapter(self.context, ISecuritySchema)
if key == 'password' and \
security.enable_user_pwd_choice and \
self.can_set_own_password:
self._change_user_password(user, value)
else:
if key == 'portrait' and value.get('data'):
self.set_member_portrait(user, value)
user.setMemberProperties(mapping={key: value})

def reply(self):
user_settings_to_update = json.loads(self.request.get('BODY', '{}'))
user = self._get_user(self._get_user_id)
Expand All @@ -63,56 +127,22 @@ def reply(self):
alsoProvides(self.request,
plone.protect.interfaces.IDisableCSRFProtection)

security = getAdapter(self.context, ISecuritySchema)
self.request.response.setStatus(204)

if self.can_manage_users:
for key, value in user_settings_to_update.items():
if key == 'password':
self._change_user_password(user, value)
elif key == 'username':
set_own_login_name(user, value)
else:
if key == 'portrait' and value.get('data'):
self.set_member_portrait(user, value)
user.setMemberProperties(mapping={key: value})

roles = user_settings_to_update.get('roles', {})
if roles:
to_add = [key for key, enabled in roles.items() if enabled]
to_remove = [key for key, enabled in roles.items()
if not enabled]

target_roles = set(user.getRoles()) - set(to_remove)
target_roles = target_roles | set(to_add)

acl_users = getToolByName(self.context, 'acl_users')
acl_users.userFolderEditUser(
principal_id=user.id,
password=None,
roles=target_roles,
domains=user.getDomains(),
)
return self.update_as_manager(user, user_settings_to_update)

elif self._get_current_user == self._get_user_id:
for key, value in user_settings_to_update.items():
if key == 'password' and \
security.enable_user_pwd_choice and \
self.can_set_own_password:
self._change_user_password(user, value)
else:
if key == 'portrait' and value.get('data'):
self.set_member_portrait(user, value)
user.setMemberProperties(mapping={key: value})
return self.update_own_settings(user, user_settings_to_update)

if self._is_anonymous:
return self._error(401, 'Unauthorized',
'You are not authorized to perform this '
'action')
else:
if self._is_anonymous:
return self._error(401, 'Unauthorized',
'You are not authorized to perform this '
'action')
else:
return self._error(403, 'Forbidden', 'You can\'t update the '
'properties of this user')
return self._error(403, 'Forbidden', 'You can\'t update the '
'properties of this user')

self.request.response.setStatus(204)
return None

@property
Expand Down
28 changes: 28 additions & 0 deletions src/plone/restapi/tests/http-examples/users.resp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ Content-Type: application/json

[
{
"@components": {
"actions": {
"@id": "http://localhost:55001/plone/portal_memberdata/admin/@actions"
},
"breadcrumbs": {
"@id": "http://localhost:55001/plone/portal_memberdata/admin/@breadcrumbs"
},
"navigation": {
"@id": "http://localhost:55001/plone/portal_memberdata/admin/@navigation"
},
"user-groups": {
"@id": "http://localhost:55001/plone/portal_memberdata/admin/@user-groups"
}
},
"@id": "http://localhost:55001/plone/@users/admin",
"description": "This is an admin user",
"email": "admin@example.com",
Expand All @@ -17,6 +31,20 @@ Content-Type: application/json
"username": "admin"
},
{
"@components": {
"actions": {
"@id": "http://localhost:55001/plone/portal_memberdata/test_user_1_/@actions"
},
"breadcrumbs": {
"@id": "http://localhost:55001/plone/portal_memberdata/test_user_1_/@breadcrumbs"
},
"navigation": {
"@id": "http://localhost:55001/plone/portal_memberdata/test_user_1_/@navigation"
},
"user-groups": {
"@id": "http://localhost:55001/plone/portal_memberdata/test_user_1_/@user-groups"
}
},
"@id": "http://localhost:55001/plone/@users/test_user_1_",
"description": "This is a test user",
"email": "test@example.com",
Expand Down
14 changes: 14 additions & 0 deletions src/plone/restapi/tests/http-examples/users_add.resp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ Location: http://localhost:55001/plone/@users/noamchomsky
Content-Type: application/json

{
"@components": {
"actions": {
"@id": "http://localhost:55001/plone/portal_memberdata/noamchomsky/@actions"
},
"breadcrumbs": {
"@id": "http://localhost:55001/plone/portal_memberdata/noamchomsky/@breadcrumbs"
},
"navigation": {
"@id": "http://localhost:55001/plone/portal_memberdata/noamchomsky/@navigation"
},
"user-groups": {
"@id": "http://localhost:55001/plone/portal_memberdata/noamchomsky/@user-groups"
}
},
"@id": "http://localhost:55001/plone/@users/noamchomsky",
"description": "Professor of Linguistics",
"email": "noam.chomsky@example.com",
Expand Down
Loading

0 comments on commit 41f41f2

Please sign in to comment.