doc_headers_middleware.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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.http import HttpResponse
  10. from django.utils.deprecation import MiddlewareMixin
  11. from common.auth import TokenDetails, handles
  12. from maxkb.const import CONFIG
  13. content = """
  14. <!DOCTYPE html>
  15. <html lang="en">
  16. <head>
  17. <meta charset="UTF-8" />
  18. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  19. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  20. <title>Document</title>
  21. </head>
  22. <style>
  23. /* 弹框内容样式 */
  24. .modal-content {
  25. background-color: #fefefe;
  26. margin: 15% auto; /* 15% 从顶部和自动水平居中 */
  27. padding: 20px;
  28. border: 1px solid #888;
  29. width: 80%; /* 宽度 */
  30. }
  31. </style>
  32. <body>
  33. <div class="modal-content">
  34. <input type="text" id="auth-input" />
  35. <button id="auth">认证</button>
  36. <button id="goLogin">去登录</button>
  37. </div>
  38. <script>
  39. const setCookie = (name, value, days) => {
  40. var expires = "";
  41. if (days) {
  42. var date = new Date();
  43. date.setTime(date.getTime() + days * 2);
  44. expires = "; expires=" + date.toUTCString();
  45. }
  46. document.cookie = name + "=" + (value || "") + expires + "; path=/";
  47. };
  48. const authToken = (token) => {
  49. return new Promise((resolve, reject) => {
  50. try {
  51. var xhr = new XMLHttpRequest();
  52. xhr.open("GET", "/api/user/profile", true);
  53. xhr.setRequestHeader("Content-Type", "application/json");
  54. const pathname = window.location.pathname;
  55. if (token) {
  56. xhr.setRequestHeader("Authorization", "Bearer " + token);
  57. xhr.onreadystatechange = function () {
  58. if (xhr.readyState === 4) {
  59. if (xhr.status === 200) {
  60. resolve(true);
  61. } else {
  62. reject(true);
  63. }
  64. }
  65. };
  66. xhr.send();
  67. }
  68. } catch (e) {
  69. reject(false);
  70. }
  71. });
  72. };
  73. window.onload = () => {
  74. const token = localStorage.getItem("token");
  75. authToken(token)
  76. .then(() => {
  77. setCookie("Authorization", "Bearer " + token);
  78. window.location.href = window.location.pathname;
  79. })
  80. .catch((e) => {});
  81. };
  82. // 获取元素
  83. const auth = document.getElementById("auth");
  84. const goLogin = document.getElementById("goLogin");
  85. // 打开弹框函数
  86. auth.onclick = ()=> {
  87. const authInput = document.getElementById("auth-input");
  88. const token = authInput.value
  89. authToken(token)
  90. .then(() => {
  91. setCookie("Authorization", "Bearer " + token);
  92. window.location.href = window.location.pathname;
  93. })
  94. .catch((e) => {
  95. alert("令牌错误");
  96. });
  97. };
  98. // 去系统的登录页面
  99. goLogin.onclick = ()=> {
  100. window.location.href = "/admin/login";
  101. };
  102. </script>
  103. </body>
  104. </html>
  105. """.replace("/api/user/profile", CONFIG.get_admin_path() + '/api/user/profile').replace('/admin/login',
  106. CONFIG.get_admin_path() + '/login')
  107. class DocHeadersMiddleware(MiddlewareMixin):
  108. def process_response(self, request, response):
  109. if request.path.startswith(CONFIG.get_admin_path() + '/api-doc/') or request.path.startswith(
  110. CONFIG.get_chat_path() + '/api-doc/'):
  111. auth = request.COOKIES.get('Authorization')
  112. if auth is None:
  113. return HttpResponse(content)
  114. else:
  115. if not auth.startswith("Bearer "):
  116. return HttpResponse(content)
  117. try:
  118. token = auth[7:]
  119. token_details = TokenDetails(token)
  120. for handle in handles:
  121. if handle.support(request, token, token_details.get_token_details):
  122. handle.handle(request, token, token_details.get_token_details)
  123. return response
  124. return HttpResponse(content)
  125. except Exception as e:
  126. return HttpResponse(content)
  127. return response