chat_headers_middleware.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # coding=utf-8
  2. """
  3. @project: maxkb
  4. @Author:虎
  5. @file: static_headers_middleware.py
  6. @date:2024/3/13 18:26
  7. @desc:
  8. """
  9. from django.utils.deprecation import MiddlewareMixin
  10. from common.cache_data.application_access_token_cache import get_application_access_token
  11. from maxkb.const import CONFIG
  12. from html import escape
  13. class ChatHeadersMiddleware(MiddlewareMixin):
  14. def process_response(self, request, response):
  15. if request.path.startswith(CONFIG.get_chat_path()) and not request.path.startswith(
  16. CONFIG.get_chat_path() + '/api'):
  17. access_token = request.path.replace(CONFIG.get_chat_path() + '/', '')
  18. if access_token.__contains__('/') or access_token == 'undefined':
  19. return response
  20. application_access_token = get_application_access_token(access_token, True)
  21. if application_access_token is not None:
  22. white_active = application_access_token.get('white_active', False)
  23. white_list = application_access_token.get('white_list', [])
  24. application_icon = escape(application_access_token.get('application_icon') or '')
  25. application_name = escape(application_access_token.get('application_name') or '')
  26. if white_active:
  27. # 添加自定义的响应头
  28. response[
  29. 'Content-Security-Policy'] = f'frame-ancestors {" ".join(white_list)}'
  30. response.content = (response.content.decode('utf-8').replace(
  31. '<link rel="icon" href="./favicon.ico"/>',
  32. f'<link rel="icon" href="{application_icon}" />')
  33. .replace('<title>MaxKB</title>', f'<title>{application_name}</title>').encode(
  34. "utf-8"))
  35. return response