You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.8 KiB
39 lines
1.8 KiB
from rest_framework.permissions import BasePermission
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
|
|
class CanCreateDynamicForm(BasePermission):
|
|
"""
|
|
Permission to create dynamic forms:
|
|
1. User must be authenticated and active.
|
|
2. Platform staff, superusers, or regional admins are permitted.
|
|
3. Regular users must have an associated institution AND
|
|
the 'can_create_forms' permission flag (toggled via role or user custom_permissions in panel admin).
|
|
"""
|
|
message = _("Only users affiliated with an institution and granted form creation permissions can create dynamic forms.")
|
|
|
|
def has_permission(self, request, view):
|
|
user = request.user
|
|
if not user or not user.is_authenticated or not user.is_active:
|
|
return False
|
|
|
|
if user.is_staff or getattr(user, 'is_super_admin', False) or getattr(user, 'is_regional_admin', False) or user.is_superuser:
|
|
return True
|
|
|
|
# Check if user has an associated institution
|
|
has_institution = bool(
|
|
(hasattr(user, 'institution_memberships') and user.institution_memberships.exists()) or
|
|
(hasattr(user, 'created_institutions') and user.created_institutions.exists()) or
|
|
bool(getattr(user, 'institution_name', None))
|
|
)
|
|
if not has_institution:
|
|
self.message = _("Only users affiliated with an institution can create dynamic forms.")
|
|
return False
|
|
|
|
# Check togglable permission flag from panel admin (Role or custom_permissions)
|
|
has_permission_flag = user.has_perm_flag('can_create_forms') if hasattr(user, 'has_perm_flag') else False
|
|
if not has_permission_flag:
|
|
self.message = _("You do not have permission to create dynamic forms. Please contact an administrator.")
|
|
return False
|
|
|
|
return True
|