forked from CGM_Public/pretix_original
Pluggable permissions (#5728)
* Data model draft * Refactor query and assignment usages of old permissions * Backend UI * API serializer * Big string replace * Docs, tests and fixes for teams api * Update docs for device auth * Eliminate old names * Make tests pass * Use new permissions, remove inconsistencies * Add test for translations * Show plugin permissions * Add permission for seating plans * Fix plugin activation * Fix failing test * Refactor to permission groups * Update doc/api/resources/devices.rst Co-authored-by: luelista <weller@rami.io> * Update doc/api/resources/events.rst Co-authored-by: luelista <weller@rami.io> * Update src/pretix/api/serializers/organizer.py Co-authored-by: luelista <weller@rami.io> * Fix typo * Fix python version compat * Replacement after rebase * Add proper permission handling for exports * Docs for exporters * Runtime linting of permission names * Fix typos * Show export page even without orders permission * More legacy compat * Do not strongly validate before plugins are loaded * Rebase migration * Add permission for outgoing mails * Review notes * Update doc/api/resources/teams.rst Co-authored-by: Richard Schreiber <schreiber@pretix.eu> * Clean up logic around exporters * Review and failures * Fix migration leading to forbidden combination * Handle permissions on event copying * Remove print-statements * Make test clearer * Review feedback * Add AnyPermissionOf * migration safety --------- Co-authored-by: luelista <weller@rami.io> Co-authored-by: Richard Schreiber <schreiber@pretix.eu>
This commit is contained in:
@@ -45,12 +45,19 @@ from pretix.base.models import (
|
||||
SalesChannel, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
|
||||
)
|
||||
from pretix.base.models.seating import SeatingPlanLayoutValidator
|
||||
from pretix.base.permissions import (
|
||||
get_all_event_permission_groups, get_all_organizer_permission_groups,
|
||||
)
|
||||
from pretix.base.plugins import (
|
||||
PLUGIN_LEVEL_EVENT, PLUGIN_LEVEL_EVENT_ORGANIZER_HYBRID,
|
||||
PLUGIN_LEVEL_ORGANIZER,
|
||||
)
|
||||
from pretix.base.services.mail import mail
|
||||
from pretix.base.settings import validate_organizer_settings
|
||||
from pretix.helpers.permission_migration import (
|
||||
OLD_TO_NEW_EVENT_COMPAT, OLD_TO_NEW_EVENT_MIGRATION,
|
||||
OLD_TO_NEW_ORGANIZER_COMPAT, OLD_TO_NEW_ORGANIZER_MIGRATION,
|
||||
)
|
||||
from pretix.helpers.urls import build_absolute_uri as build_global_uri
|
||||
from pretix.multidomain.urlreverse import build_absolute_uri
|
||||
|
||||
@@ -306,23 +313,128 @@ class EventSlugField(serializers.SlugRelatedField):
|
||||
return self.context['organizer'].events.all()
|
||||
|
||||
|
||||
class PermissionMultipleChoiceField(serializers.MultipleChoiceField):
|
||||
def to_internal_value(self, data):
|
||||
return {
|
||||
p: True for p in super().to_internal_value(data)
|
||||
}
|
||||
|
||||
def to_representation(self, value):
|
||||
return [p for p, v in value.items() if v]
|
||||
|
||||
|
||||
class TeamSerializer(serializers.ModelSerializer):
|
||||
limit_events = EventSlugField(slug_field='slug', many=True)
|
||||
limit_event_permissions = PermissionMultipleChoiceField(choices=[], required=False, allow_null=False, allow_empty=True)
|
||||
limit_organizer_permissions = PermissionMultipleChoiceField(choices=[], required=False, allow_null=False, allow_empty=True)
|
||||
|
||||
# Legacy fields, handled in to_representation and validate
|
||||
can_change_event_settings = serializers.BooleanField(required=False, write_only=True)
|
||||
can_change_items = serializers.BooleanField(required=False, write_only=True)
|
||||
can_view_orders = serializers.BooleanField(required=False, write_only=True)
|
||||
can_change_orders = serializers.BooleanField(required=False, write_only=True)
|
||||
can_checkin_orders = serializers.BooleanField(required=False, write_only=True)
|
||||
can_view_vouchers = serializers.BooleanField(required=False, write_only=True)
|
||||
can_change_vouchers = serializers.BooleanField(required=False, write_only=True)
|
||||
can_create_events = serializers.BooleanField(required=False, write_only=True)
|
||||
can_change_organizer_settings = serializers.BooleanField(required=False, write_only=True)
|
||||
can_change_teams = serializers.BooleanField(required=False, write_only=True)
|
||||
can_manage_gift_cards = serializers.BooleanField(required=False, write_only=True)
|
||||
can_manage_customers = serializers.BooleanField(required=False, write_only=True)
|
||||
can_manage_reusable_media = serializers.BooleanField(required=False, write_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Team
|
||||
fields = (
|
||||
'id', 'name', 'require_2fa', 'all_events', 'limit_events', 'can_create_events', 'can_change_teams',
|
||||
'can_change_organizer_settings', 'can_manage_gift_cards', 'can_change_event_settings',
|
||||
'can_change_items', 'can_view_orders', 'can_change_orders', 'can_view_vouchers',
|
||||
'can_change_vouchers', 'can_checkin_orders', 'can_manage_customers', 'can_manage_reusable_media'
|
||||
'id', 'name', 'require_2fa', 'all_events', 'limit_events', 'all_event_permissions', 'limit_event_permissions',
|
||||
'all_organizer_permissions', 'limit_organizer_permissions', 'can_change_event_settings',
|
||||
'can_change_items', 'can_view_orders', 'can_change_orders', 'can_checkin_orders', 'can_view_vouchers',
|
||||
'can_change_vouchers', 'can_create_events', 'can_change_organizer_settings', 'can_change_teams',
|
||||
'can_manage_gift_cards', 'can_manage_customers', 'can_manage_reusable_media'
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
event_perms_flattened = []
|
||||
organizer_perms_flattened = []
|
||||
for pg in get_all_event_permission_groups().values():
|
||||
for action in pg.actions:
|
||||
event_perms_flattened.append(f"{pg.name}:{action}")
|
||||
for pg in get_all_organizer_permission_groups().values():
|
||||
for action in pg.actions:
|
||||
organizer_perms_flattened.append(f"{pg.name}:{action}")
|
||||
|
||||
self.fields['limit_event_permissions'].choices = [(p, p) for p in event_perms_flattened]
|
||||
self.fields['limit_organizer_permissions'].choices = [(p, p) for p in organizer_perms_flattened]
|
||||
|
||||
def to_representation(self, instance):
|
||||
r = super().to_representation(instance)
|
||||
for old, new in OLD_TO_NEW_EVENT_COMPAT.items():
|
||||
r[old] = instance.all_event_permissions or all(instance.limit_event_permissions.get(n) for n in new)
|
||||
for old, new in OLD_TO_NEW_ORGANIZER_COMPAT.items():
|
||||
r[old] = instance.all_organizer_permissions or all(instance.limit_organizer_permissions.get(n) for n in new)
|
||||
return r
|
||||
|
||||
def validate(self, data):
|
||||
old_data_set = any(k.startswith("can_") for k in data)
|
||||
new_data_set = any(k in data for k in [
|
||||
"all_event_permissions", "limit_event_permissions", "all_organizer_permissions", "limit_organizer_permissions"
|
||||
])
|
||||
if old_data_set and new_data_set:
|
||||
raise ValidationError("You cannot set deprecated and current permission attributes at the same time.")
|
||||
|
||||
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
|
||||
full_data.update(data)
|
||||
|
||||
if new_data_set:
|
||||
if full_data.get('limit_event_permissions') and full_data.get('all_event_permissions'):
|
||||
raise ValidationError('Do not set both limit_event_permissions and all_event_permissions.')
|
||||
if full_data.get('limit_organizer_permissions') and full_data.get('all_organizer_permissions'):
|
||||
raise ValidationError('Do not set both limit_organizer_permissions and all_organizer_permissions.')
|
||||
|
||||
if old_data_set:
|
||||
# Migrate with same logic as in migration 0297_pluggable_permissions
|
||||
if all(full_data.get(k) is True for k in OLD_TO_NEW_EVENT_MIGRATION.keys() if k != "can_checkin_orders"):
|
||||
data["all_event_permissions"] = True
|
||||
data["limit_event_permissions"] = {}
|
||||
else:
|
||||
data["all_event_permissions"] = False
|
||||
data["limit_event_permissions"] = {}
|
||||
for k, v in OLD_TO_NEW_EVENT_MIGRATION.items():
|
||||
if full_data.get(k) is True:
|
||||
data["limit_event_permissions"].update({kk: True for kk in v})
|
||||
if all(full_data.get(k) is True for k in OLD_TO_NEW_ORGANIZER_MIGRATION.keys() if k != "can_checkin_orders"):
|
||||
data["all_organizer_permissions"] = True
|
||||
data["limit_organizer_permissions"] = {}
|
||||
else:
|
||||
data["all_organizer_permissions"] = False
|
||||
data["limit_organizer_permissions"] = {}
|
||||
for k, v in OLD_TO_NEW_ORGANIZER_MIGRATION.items():
|
||||
if full_data.get(k) is True:
|
||||
data["limit_organizer_permissions"].update({kk: True for kk in v})
|
||||
|
||||
if full_data.get('limit_events') and full_data.get('all_events'):
|
||||
raise ValidationError('Do not set both limit_events and all_events.')
|
||||
|
||||
full_data.update(data)
|
||||
for pg in get_all_event_permission_groups().values():
|
||||
requested = ",".join(sorted(
|
||||
a for a in pg.actions if self.instance and full_data["limit_event_permissions"].get(f"{pg.name}:{a}")
|
||||
))
|
||||
if requested not in (",".join(sorted(opt.actions)) for opt in pg.options):
|
||||
possible = '\' or \''.join(','.join(opt.actions) for opt in pg.options)
|
||||
raise ValidationError(f"For permission group {pg.name}, the valid combinations of actions are "
|
||||
f"'{possible}' but you tried to set '{requested}'.")
|
||||
for pg in get_all_organizer_permission_groups().values():
|
||||
requested = ",".join(sorted(
|
||||
a for a in pg.actions if self.instance and full_data["limit_organizer_permissions"].get(f"{pg.name}:{a}")
|
||||
))
|
||||
if requested not in (",".join(sorted(opt.actions)) for opt in pg.options):
|
||||
possible = '\' or \''.join(','.join(opt.actions) for opt in pg.options)
|
||||
raise ValidationError(f"For permission group {pg.name}, the valid combinations of actions are "
|
||||
f"'{possible}' but you tried to set '{requested}'.")
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -339,7 +451,7 @@ class DeviceSerializer(serializers.ModelSerializer):
|
||||
created = serializers.DateTimeField(read_only=True)
|
||||
revoked = serializers.BooleanField(read_only=True)
|
||||
initialized = serializers.DateTimeField(read_only=True)
|
||||
initialization_token = serializers.DateTimeField(read_only=True)
|
||||
initialization_token = serializers.CharField(read_only=True)
|
||||
security_profile = serializers.ChoiceField(choices=[], required=False, default="full")
|
||||
|
||||
class Meta:
|
||||
@@ -353,6 +465,8 @@ class DeviceSerializer(serializers.ModelSerializer):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['security_profile'].choices = [(k, v.verbose_name) for k, v in get_all_security_profiles().items()]
|
||||
if not self.context['can_see_tokens']:
|
||||
del self.fields['initialization_token']
|
||||
|
||||
|
||||
class TeamInviteSerializer(serializers.ModelSerializer):
|
||||
@@ -437,7 +551,10 @@ class TeamMemberSerializer(serializers.ModelSerializer):
|
||||
|
||||
|
||||
class OrganizerSettingsSerializer(SettingsSerializer):
|
||||
default_write_permission = 'organizer.settings.general:write'
|
||||
default_fields = [
|
||||
# These are readable for all users with access to the events, therefore secrets stored in the settings store
|
||||
# should not be included!
|
||||
'customer_accounts',
|
||||
'customer_accounts_native',
|
||||
'customer_accounts_link_by_email',
|
||||
|
||||
Reference in New Issue
Block a user