Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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):
  7. super().__init__(get_response)
  8. self.sts_seconds = settings.SECURE_HSTS_SECONDS
  9. self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS
  10. self.sts_preload = settings.SECURE_HSTS_PRELOAD
  11. self.content_type_nosniff = settings.SECURE_CONTENT_TYPE_NOSNIFF
  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.referrer_policy = settings.SECURE_REFERRER_POLICY
  16. self.cross_origin_opener_policy = settings.SECURE_CROSS_ORIGIN_OPENER_POLICY
  17. def process_request(self, request):
  18. path = request.path.lstrip("/")
  19. if (
  20. self.redirect
  21. and not request.is_secure()
  22. and not any(pattern.search(path) for pattern in self.redirect_exempt)
  23. ):
  24. host = self.redirect_host or request.get_host()
  25. return HttpResponsePermanentRedirect(
  26. "https://%s%s" % (host, request.get_full_path())
  27. )
  28. def process_response(self, request, response):
  29. if (
  30. self.sts_seconds
  31. and request.is_secure()
  32. and "Strict-Transport-Security" not in response
  33. ):
  34. sts_header = "max-age=%s" % self.sts_seconds
  35. if self.sts_include_subdomains:
  36. sts_header = sts_header + "; includeSubDomains"
  37. if self.sts_preload:
  38. sts_header = sts_header + "; preload"
  39. response.headers["Strict-Transport-Security"] = sts_header
  40. if self.content_type_nosniff:
  41. response.headers.setdefault("X-Content-Type-Options", "nosniff")
  42. if self.referrer_policy:
  43. # Support a comma-separated string or iterable of values to allow
  44. # fallback.
  45. response.headers.setdefault(
  46. "Referrer-Policy",
  47. ",".join(
  48. [v.strip() for v in self.referrer_policy.split(",")]
  49. if isinstance(self.referrer_policy, str)
  50. else self.referrer_policy
  51. ),
  52. )
  53. if self.cross_origin_opener_policy:
  54. response.setdefault(
  55. "Cross-Origin-Opener-Policy",
  56. self.cross_origin_opener_policy,
  57. )
  58. return response