models.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import re
  2. from django.utils import timezone
  3. from django.db import models
  4. from django.db.models import Q
  5. BAN_NAME_EMAIL = 0
  6. BAN_NAME = 1
  7. BAN_EMAIL = 2
  8. BAN_IP = 3
  9. class Ban(models.Model):
  10. type = models.PositiveIntegerField(default=BAN_NAME_EMAIL)
  11. ban = models.CharField(max_length=255)
  12. expires = models.DateTimeField(null=True,blank=True,db_index=True)
  13. def check_ban(ip=False, username=False, email=False):
  14. bans_model = Ban.objects.filter(Q(expires=None) | Q(expires__gt=timezone.now()))
  15. if not (ip and username and email):
  16. if ip:
  17. bans_model.filter(type=BAN_IP)
  18. if username:
  19. bans_model.filter(type=BAN_NAME_EMAIL)
  20. bans_model.filter(type=BAN_NAME)
  21. if email:
  22. bans_model.filter(type=BAN_NAME_EMAIL)
  23. bans_model.filter(type=BAN_EMAIL)
  24. for ban in bans_model.order_by('-expires').iterator():
  25. if (
  26. # Check user name
  27. ((username and (ban.type == BAN_NAME_EMAIL or ban.type == BAN_NAME))
  28. and re.search('^'+re.escape(ban.ban).replace('\*', '(.*?)')+'$', username, flags=re.IGNORECASE))
  29. or # Check user email
  30. ((email and (ban.type == BAN_NAME_EMAIL or ban.type == BAN_EMAIL))
  31. and re.search('^'+re.escape(ban.ban).replace('\*', '(.*?)')+'$', email, flags=re.IGNORECASE))
  32. or # Check IP address
  33. (ip and ban.type == BAN_IP
  34. and re.search('^'+re.escape(ban.ban).replace('\*', '(.*?)')+'$', ip, flags=re.IGNORECASE))):
  35. return ban
  36. return False
  37. class BanCache(object):
  38. banned = False
  39. type = None
  40. expires = None
  41. version = 0
  42. def check_for_updates(self, request):
  43. if (self.version < request.monitor['bans_version']
  44. or (self.expires != None and self.expires < timezone.now())):
  45. self.version = request.monitor['bans_version']
  46. ban = check_ban(
  47. ip=request.session.get_ip(request),
  48. )
  49. if ban:
  50. self.banned = True
  51. self.expires = ban.expires
  52. self.type = ban.type
  53. else:
  54. self.banned = False
  55. self.expires = None
  56. self.type = None
  57. return True
  58. return False
  59. def is_banned(self):
  60. return self.banned