floodprotection.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from datetime import timedelta
  2. from django.utils import timezone
  3. from django.utils.translation import ugettext 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 not self.user.acl_cache['can_omit_flood_protection'
  10. ] and self.mode != PostingEndpoint.EDIT
  11. def interrupt_posting(self, serializer):
  12. now = timezone.now()
  13. if self.user.last_posted_on:
  14. previous_post = now - self.user.last_posted_on
  15. if previous_post.total_seconds() < MIN_POSTING_PAUSE:
  16. raise PostingInterrupt(_("You can't post message so quickly after previous one."))
  17. self.user.last_posted_on = timezone.now()
  18. self.user.update_fields.append('last_posted_on')
  19. if settings.MISAGO_HOURLY_POST_LIMIT:
  20. cutoff = now - timedelta(hours=24)
  21. if self.is_limit_exceeded(cutoff, settings.MISAGO_HOURLY_POST_LIMIT):
  22. raise PostingInterrupt(_("Your account has excceed hourly post limit."))
  23. if settings.MISAGO_DIALY_POST_LIMIT:
  24. cutoff = now - timedelta(hours=1)
  25. if self.is_limit_exceeded(cutoff, settings.MISAGO_DIALY_POST_LIMIT):
  26. raise PostingInterrupt(_("Your account has excceed dialy post limit."))
  27. def is_limit_exceeded(self, cutoff, limit):
  28. return self.user.post_set.filter(posted_on__gte=cutoff).count() >= limit