utils.py 1.6 KB

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