CCrypto VPN public website https://vpn.ccrypto.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

89 lines
2.5 KiB

  1. from datetime import datetime, timedelta
  2. import re
  3. from django.utils.deprecation import MiddlewareMixin
  4. from django.conf import settings
  5. from .models import User
  6. class ReferrerMiddleware(MiddlewareMixin):
  7. def process_request(self, request):
  8. if "ref" in request.GET:
  9. id = request.GET["ref"]
  10. elif "referrer" in request.COOKIES:
  11. id = request.COOKIES["referrer"]
  12. else:
  13. return
  14. try:
  15. id = int(id.strip())
  16. except (ValueError, TypeError):
  17. return
  18. try:
  19. u = User.objects.get(id=id)
  20. except User.DoesNotExist:
  21. return
  22. request.session["referrer"] = u.id
  23. def process_response(self, request, response):
  24. id = request.session.get("referrer")
  25. if not id:
  26. return response
  27. max_age = 365 * 24 * 60 * 60
  28. expires = datetime.utcnow() + timedelta(seconds=max_age)
  29. expires = expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
  30. response.set_cookie(
  31. "referrer",
  32. id,
  33. max_age=max_age,
  34. expires=expires,
  35. domain=settings.SESSION_COOKIE_DOMAIN,
  36. secure=settings.SESSION_COOKIE_SECURE or None,
  37. )
  38. return response
  39. class CampaignMiddleware(MiddlewareMixin):
  40. GET_FIELDS = ["pk_campaign", "utm_campaign", "utm_medium", "utm_source"]
  41. def _get_name(self, request):
  42. for f in self.GET_FIELDS:
  43. if f in request.GET and request.GET[f]:
  44. return request.GET[f]
  45. if "campaign" in request.COOKIES:
  46. return request.COOKIES["campaign"]
  47. return None
  48. def process_request(self, request):
  49. name = self._get_name(request)
  50. if not name:
  51. return
  52. name = name.strip()
  53. if len(name) >= 64 or not re.match("^[a-zA-Z0-9_.:-]+$", name):
  54. return
  55. request.session["campaign"] = name
  56. def process_response(self, request, response):
  57. name = request.session.get("campaign")
  58. if not name:
  59. return response
  60. max_age = 365 * 24 * 60 * 60
  61. expires = datetime.utcnow() + timedelta(seconds=max_age)
  62. expires = expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
  63. response.set_cookie(
  64. "campaign",
  65. name,
  66. max_age=max_age,
  67. expires=expires,
  68. domain=settings.SESSION_COOKIE_DOMAIN,
  69. secure=settings.SESSION_COOKIE_SECURE or None,
  70. )
  71. return response