utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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() or ticket.assigned_to == self.request.user
  18. class UserCanWriteTicketMixin(UserPassesTestMixin):
  19. def test_func(self):
  20. ticket = get_object_or_404(Ticket.objects.all(), pk=self.kwargs.get('pk'))
  21. return self.request.user.is_superuser or self.request.user.is_staff or ticket.created_by == self.request.user
  22. def remove_attachment_file(attachment_id: int) -> bool:
  23. """Delete an Attachment object and its corresponding file from the filesystem."""
  24. try:
  25. attachment = Attachment.objects.get(id=attachment_id)
  26. if attachment.file:
  27. if os.path.isfile(attachment.file.path):
  28. os.remove(attachment.file.path)
  29. attachment.delete()
  30. return True
  31. except Attachment.DoesNotExist:
  32. log.info(f"Attachment {attachment_id} not found.")
  33. return False