User edit form: prevent accidentally revoking roles

Prevent accidentally revoking roles that were not part of the form.
This commit is contained in:
Sybren A. Stüvel 2017-06-08 11:35:33 +02:00
parent 263c274774
commit 740df09b9d
2 changed files with 24 additions and 7 deletions

View File

@ -59,8 +59,21 @@ class UserSettingsEmailsForm(Form):
'Notifications', choices=choices, coerce=int)
# TODO: refactor roles to be obtainable from the Pillar application.
class UserEditForm(Form):
role_choices = [('admin', 'admin'),
('subscriber', 'subscriber'),
('demo', 'demo')]
ROLES = [
'admin',
'badger',
'demo',
'flamenco-admin',
'flamenco_manager',
'flamenco-user',
'homeproject',
'protected',
'service',
'subscriber',
'svner',
'urler',
]
role_choices = [(r, r) for r in ROLES]
roles = SelectMultipleField('Roles', choices=role_choices)

View File

@ -236,7 +236,7 @@ def users_edit(user_id):
def _users_edit(form, user, api):
"""Performs the actual user editing."""
from pillar.api.service import role_to_group_id, ROLES_WITH_GROUPS
from pillar.api.service import role_to_group_id
current_user_roles = set(user.roles or [])
current_user_groups = set(user.groups or [])
@ -244,11 +244,15 @@ def _users_edit(form, user, api):
roles_in_form = set(form.roles.data)
granted_roles = roles_in_form - current_user_roles
revoked_roles = ROLES_WITH_GROUPS - roles_in_form
revoked_roles = set(UserEditForm.ROLES) - roles_in_form
# role_to_group_id contains ObjectIDs, but the SDK works with strings.
granted_groups = {str(role_to_group_id[role]) for role in granted_roles}
revoked_groups = {str(role_to_group_id[role]) for role in revoked_roles}
granted_groups = {str(role_to_group_id[role])
for role in granted_roles
if role in role_to_group_id}
revoked_groups = {str(role_to_group_id[role])
for role in revoked_roles
if role in role_to_group_id}
user.roles = list((current_user_roles - revoked_roles).union(granted_roles))
user.groups = list((current_user_groups - revoked_groups).union(granted_groups))