utils.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import logging
  2. import os
  3. from django.contrib.auth.mixins import UserPassesTestMixin
  4. from django.shortcuts import get_object_or_404
  5. from tickets.models import *
  6. log = logging.getLogger(__name__)
  7. class SuperuserStaffRequiredMixin(UserPassesTestMixin):
  8. def test_func(self):
  9. return self.request.user.is_superuser or self.request.user.is_staff
  10. class UserCanReadTicketListMixin(UserPassesTestMixin):
  11. def test_func(self):
  12. ticket_list = get_object_or_404(TicketList.objects.select_related('group'), pk=self.kwargs.get('pk'))
  13. return self.request.user.is_superuser or ticket_list.group in self.request.user.groups.all()
  14. class UserCanReadTicketMixin(UserPassesTestMixin):
  15. def test_func(self):
  16. ticket = get_object_or_404(Ticket.objects.select_related('ticket_list', 'ticket_list__group'), pk=self.kwargs.get('pk'))
  17. return self.request.user.is_superuser or ticket.ticket_list.group in self.request.user.groups.all()
  18. def remove_attachment_file(attachment_id: int) -> bool:
  19. """Delete an Attachment object and its corresponding file from the filesystem."""
  20. try:
  21. attachment = Attachment.objects.get(id=attachment_id)
  22. if attachment.file:
  23. if os.path.isfile(attachment.file.path):
  24. os.remove(attachment.file.path)
  25. attachment.delete()
  26. return True
  27. except Attachment.DoesNotExist:
  28. log.info(f"Attachment {attachment_id} not found.")
  29. return False