models.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. reason_user = models.TextField(null=True,blank=True)
  13. reason_admin = models.TextField(null=True,blank=True)
  14. expires = models.DateTimeField(null=True,blank=True,db_index=True)
  15. def check_ban(ip=False, username=False, email=False):
  16. bans_model = Ban.objects.filter(Q(expires=None) | Q(expires__gt=timezone.now()))
  17. if not (ip and username and email):
  18. if ip:
  19. bans_model.filter(type=BAN_IP)
  20. if username:
  21. bans_model.filter(type=BAN_NAME_EMAIL)
  22. bans_model.filter(type=BAN_NAME)
  23. if email:
  24. bans_model.filter(type=BAN_NAME_EMAIL)
  25. bans_model.filter(type=BAN_EMAIL)
  26. for ban in bans_model.order_by('-expires').iterator():
  27. if (
  28. # Check user name
  29. ((username and (ban.type == BAN_NAME_EMAIL or ban.type == BAN_NAME))
  30. and re.search('^'+re.escape(ban.ban).replace('\*', '(.*?)')+'$', username, flags=re.IGNORECASE))
  31. or # Check user email
  32. ((email and (ban.type == BAN_NAME_EMAIL or ban.type == BAN_EMAIL))
  33. and re.search('^'+re.escape(ban.ban).replace('\*', '(.*?)')+'$', email, flags=re.IGNORECASE))
  34. or # Check IP address
  35. (ip and ban.type == BAN_IP
  36. and re.search('^'+re.escape(ban.ban).replace('\*', '(.*?)')+'$', ip, flags=re.IGNORECASE))):
  37. return ban
  38. return False
  39. class BanCache(object):
  40. def __init__(self):
  41. self.banned = False
  42. self.type = None
  43. self.expires = None
  44. self.reason = None
  45. self.version = 0
  46. def check_for_updates(self, request):
  47. if (self.version < request.monitor['bans_version']
  48. or (self.expires != None and self.expires < timezone.now())):
  49. self.version = request.monitor['bans_version']
  50. ban = check_ban(ip=request.session.get_ip(request))
  51. if ban:
  52. self.banned = True
  53. self.reason = ban.reason_user
  54. self.expires = ban.expires
  55. self.type = ban.type
  56. else:
  57. self.banned = False
  58. self.reason = None
  59. self.expires = None
  60. self.type = None
  61. return True
  62. return False
  63. def is_banned(self):
  64. return self.banned