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.

security.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import re
  2. from django.conf import settings
  3. from django.http import HttpResponsePermanentRedirect
  4. from django.utils.deprecation import MiddlewareMixin
  5. class SecurityMiddleware(MiddlewareMixin):
  6. def __init__(self, get_response=None):
  7. self.sts_seconds = settings.SECURE_HSTS_SECONDS
  8. self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS
  9. self.sts_preload = settings.SECURE_HSTS_PRELOAD
  10. self.content_type_nosniff = settings.SECURE_CONTENT_TYPE_NOSNIFF
  11. self.xss_filter = settings.SECURE_BROWSER_XSS_FILTER
  12. self.redirect = settings.SECURE_SSL_REDIRECT
  13. self.redirect_host = settings.SECURE_SSL_HOST
  14. self.redirect_exempt = [re.compile(r) for r in settings.SECURE_REDIRECT_EXEMPT]
  15. self.get_response = get_response
  16. def process_request(self, request):
  17. path = request.path.lstrip("/")
  18. if (self.redirect and not request.is_secure() and
  19. not any(pattern.search(path)
  20. for pattern in self.redirect_exempt)):
  21. host = self.redirect_host or request.get_host()
  22. return HttpResponsePermanentRedirect(
  23. "https://%s%s" % (host, request.get_full_path())
  24. )
  25. def process_response(self, request, response):
  26. if (self.sts_seconds and request.is_secure() and
  27. 'Strict-Transport-Security' not in response):
  28. sts_header = "max-age=%s" % self.sts_seconds
  29. if self.sts_include_subdomains:
  30. sts_header = sts_header + "; includeSubDomains"
  31. if self.sts_preload:
  32. sts_header = sts_header + "; preload"
  33. response['Strict-Transport-Security'] = sts_header
  34. if self.content_type_nosniff:
  35. response.setdefault('X-Content-Type-Options', 'nosniff')
  36. if self.xss_filter:
  37. response.setdefault('X-XSS-Protection', '1; mode=block')
  38. return response