cross_domain_middleware.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # coding=utf-8
  2. """
  3. @project: MaxKB
  4. @Author:虎虎
  5. @file: cross_domain_middleware.py
  6. @date:2024/5/8 13:36
  7. @desc:
  8. """
  9. from django.http import HttpResponse
  10. from django.utils.deprecation import MiddlewareMixin
  11. from common.cache_data.application_api_key_cache import get_application_api_key
  12. class CrossDomainMiddleware(MiddlewareMixin):
  13. def process_request(self, request):
  14. if request.method == 'OPTIONS':
  15. return HttpResponse(status=200,
  16. headers={
  17. "Access-Control-Allow-Origin": "*",
  18. "Access-Control-Allow-Methods": "GET,POST,DELETE,PUT",
  19. "Access-Control-Allow-Headers": "Origin,X-Requested-With,Content-Type,Accept,Authorization,token"})
  20. def process_response(self, request, response):
  21. auth = request.META.get('HTTP_AUTHORIZATION')
  22. origin = request.META.get('HTTP_ORIGIN')
  23. if auth is not None and any([str(auth).startswith(prefix) for prefix in
  24. ['Bearer application-', 'Bearer agent-']]) and origin is not None:
  25. application_api_key = get_application_api_key(str(auth), True)
  26. cross_domain_list = application_api_key.get('cross_domain_list', [])
  27. allow_cross_domain = application_api_key.get('allow_cross_domain', False)
  28. if allow_cross_domain:
  29. response['Access-Control-Allow-Methods'] = 'GET,POST,DELETE,PUT'
  30. response[
  31. 'Access-Control-Allow-Headers'] = "Origin,X-Requested-With,Content-Type,Accept,Authorization,token"
  32. if cross_domain_list is None or len(cross_domain_list) == 0:
  33. response['Access-Control-Allow-Origin'] = "*"
  34. elif cross_domain_list.__contains__(origin):
  35. response['Access-Control-Allow-Origin'] = origin
  36. return response