floodprotection.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from datetime import timedelta
  2. from django.utils import timezone
  3. from django.utils.translation import gettext as _
  4. from misago.conf import settings
  5. from . import PostingEndpoint, PostingInterrupt, PostingMiddleware
  6. MIN_POSTING_PAUSE = 3
  7. class FloodProtectionMiddleware(PostingMiddleware):
  8. def use_this_middleware(self):
  9. return (
  10. not self.user_acl['can_omit_flood_protection'] and
  11. self.mode != PostingEndpoint.EDIT
  12. )
  13. def interrupt_posting(self, serializer):
  14. now = timezone.now()
  15. if self.user.last_posted_on:
  16. previous_post = now - self.user.last_posted_on
  17. if previous_post.total_seconds() < MIN_POSTING_PAUSE:
  18. raise PostingInterrupt(_("You can't post message so quickly after previous one."))
  19. self.user.last_posted_on = timezone.now()
  20. self.user.update_fields.append('last_posted_on')
  21. if settings.MISAGO_HOURLY_POST_LIMIT:
  22. cutoff = now - timedelta(hours=24)
  23. if self.is_limit_exceeded(cutoff, settings.MISAGO_HOURLY_POST_LIMIT):
  24. raise PostingInterrupt(_("Your account has excceed hourly post limit."))
  25. if settings.MISAGO_DIALY_POST_LIMIT:
  26. cutoff = now - timedelta(hours=1)
  27. if self.is_limit_exceeded(cutoff, settings.MISAGO_DIALY_POST_LIMIT):
  28. raise PostingInterrupt(_("Your account has excceed dialy post limit."))
  29. def is_limit_exceeded(self, cutoff, limit):
  30. return self.user.post_set.filter(posted_on__gte=cutoff).count() >= limit