attachments.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from django import forms
  2. from django.utils.translation import gettext_lazy as _
  3. from ...acl import algebra
  4. from ...acl.models import Role
  5. from ...admin.forms import YesNoSwitch
  6. from ..models import Attachment
  7. # Admin Permissions Forms
  8. class PermissionsForm(forms.Form):
  9. legend = _("Attachments")
  10. max_attachment_size = forms.IntegerField(
  11. label=_("Max attached file size (in kb)"),
  12. help_text=_("Enter 0 to don't allow uploading end deleting attachments."),
  13. initial=500,
  14. min_value=0,
  15. )
  16. can_download_other_users_attachments = YesNoSwitch(
  17. label=_("Can download other users attachments")
  18. )
  19. can_delete_other_users_attachments = YesNoSwitch(
  20. label=_("Can delete other users attachments")
  21. )
  22. class AnonymousPermissionsForm(forms.Form):
  23. legend = _("Attachments")
  24. can_download_other_users_attachments = YesNoSwitch(
  25. label=_("Can download attachments")
  26. )
  27. def change_permissions_form(role):
  28. if isinstance(role, Role):
  29. if role.special_role == "anonymous":
  30. return AnonymousPermissionsForm
  31. return PermissionsForm
  32. def build_acl(acl, roles, key_name):
  33. new_acl = {
  34. "max_attachment_size": 0,
  35. "can_download_other_users_attachments": False,
  36. "can_delete_other_users_attachments": False,
  37. }
  38. new_acl.update(acl)
  39. return algebra.sum_acls(
  40. new_acl,
  41. roles=roles,
  42. key=key_name,
  43. max_attachment_size=algebra.greater,
  44. can_download_other_users_attachments=algebra.greater,
  45. can_delete_other_users_attachments=algebra.greater,
  46. )
  47. def add_acl_to_attachment(user_acl, attachment):
  48. if user_acl["is_authenticated"] and user_acl["user_id"] == attachment.uploader_id:
  49. attachment.acl.update({"can_delete": True})
  50. else:
  51. user_can_delete = user_acl["can_delete_other_users_attachments"]
  52. attachment.acl.update(
  53. {"can_delete": user_acl["is_authenticated"] and user_can_delete}
  54. )
  55. def register_with(registry):
  56. registry.acl_annotator(Attachment, add_acl_to_attachment)