api: allow patch/put API to empty a role (#36918)

This commit is contained in:
Frédéric Péters 2019-10-14 18:38:19 +02:00
parent da9857d8b7
commit 6438cffd29
2 changed files with 30 additions and 2 deletions

View File

@ -779,6 +779,9 @@ class RoleMembershipsAPI(ExceptionHandlerMixin, APIView):
if not isinstance(request.data, dict):
raise ValidationError(_('Payload must be a dictionary'))
if request.method != 'GET' and not 'data' in request.data:
raise ValidationError(_("Invalid payload (missing 'data' key)"))
for entry in request.data.get('data', ()):
try:
uuid = entry['uuid']
@ -794,8 +797,7 @@ class RoleMembershipsAPI(ExceptionHandlerMixin, APIView):
raise ValidationError(
_('No known user for UUID %s') % entry['uuid'])
if not len(self.members) and \
request.method.lower() in self.http_method_names:
if not len(self.members) and request.method in ('POST', 'DELETE'):
raise ValidationError(_('No valid user UUID'))
def post(self, request, *args, **kwargs):

View File

@ -775,6 +775,32 @@ def test_api_role_set_members(app, api_user, role, member, member_rando2):
assert resp.json['errors'] == 'User not allowed to change role'
def test_api_role_set_empty_members(app, api_user):
app.authorization = ('Basic', (api_user.username, api_user.username))
ou = get_default_ou()
User = get_user_model()
user = User.objects.create(ou=ou, username='john.doe', first_name=u'Jôhn',
last_name=u'Doe', email='john.doe@example.net')
user.save()
Role = get_role_model()
role = Role.objects.create(name='Role1', ou=ou)
role.members.add(user)
status = 200
if not api_user.has_perm('a2_rbac.change_role', role):
status = 403
resp = app.put_json(
'/api/roles/{}/relationships/members/'.format(role.uuid),
params={'data': []}, status=status)
if api_user.has_perm('a2_rbac.change_role', role):
assert len(role.members.all()) == 0
else:
assert len(role.members.all()) == 1
def test_api_role_get_members(app, api_user, role):
app.authorization = ('Basic', (api_user.username, api_user.username))
authorized = api_user.has_perm('a2_rbac.change_role', role)