models.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from datetime import timedelta
  2. from random import randint
  3. from django.db import models
  4. from django.utils import timezone
  5. from django.utils.translation import ugettext_lazy as _
  6. """
  7. IP's that have exhausted their quota of sign-in attempts are automatically banned for set amount of time.
  8. That IP ban cuts bad IP address from signing into board by either making another sign-in attempts or
  9. registering "fresh" account.
  10. """
  11. class SignInAttemptsManager(models.Manager):
  12. """
  13. Attempts manager
  14. """
  15. def register_attempt(self, ip):
  16. attempt = SignInAttempt(ip=ip, date=timezone.now())
  17. attempt.save(force_insert=True)
  18. def is_jammed(self, settings, ip):
  19. # Limit is off, dont jam IPs?
  20. if settings['login_attempts_limit'] == 0:
  21. return False
  22. # Check jam
  23. if settings['jams_lifetime'] > 0:
  24. attempts = SignInAttempt.objects.filter(
  25. date__gt=timezone.now() - timedelta(minutes=settings['jams_lifetime']),
  26. ip=ip
  27. )
  28. else:
  29. attempts = SignInAttempt.objects.filter(ip=ip)
  30. return attempts.count() > settings['login_attempts_limit']
  31. class SignInAttempt(models.Model):
  32. ip = models.GenericIPAddressField(db_index=True)
  33. date = models.DateTimeField()
  34. objects = SignInAttemptsManager()
  35. class JamCache(object):
  36. jammed = False
  37. expires = timezone.now()
  38. def check_for_updates(self, request):
  39. if self.expires < timezone.now():
  40. self.jammed = SignInAttempt.objects.is_jammed(request.settings, request.session.get_ip(request))
  41. self.expires = timezone.now() + timedelta(minutes=request.settings['jams_lifetime'])
  42. return True
  43. return False
  44. def is_jammed(self):
  45. return self.jammed
  46. """
  47. Question-Answer Tests
  48. """
  49. class QATestManager(models.Manager):
  50. def random(self):
  51. count = self.aggregate(count=models.Count('id'))['count']
  52. random_index = randint(0, count - 1)
  53. return self.all()[random_index]
  54. class QATest(models.Model):
  55. question = models.CharField(_("Question"),max_length=255)
  56. helptext = models.TextField(null=True,blank=True)
  57. answers = models.TextField()
  58. objects = QATestManager()
  59. def is_answer_correct(self, answer):
  60. return unicode(answer).lower() in (name.lower() for name in unicode(self.answers).splitlines())