Skip to content

Commit 224fe26

Browse files
committed
feat: add DocHeadersMiddleware to handle document access and redirect unauthorized users
1 parent 178064f commit 224fe26

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
12+
content = """
13+
<!doctype html>
14+
<html lang="en">
15+
<head>
16+
<meta charset="UTF-8" />
17+
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
18+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
19+
<title>Document</title>
20+
<script>
21+
window.onload = () => {
22+
var xhr = new XMLHttpRequest()
23+
xhr.open('GET', '/api/user', true)
24+
25+
xhr.setRequestHeader('Content-Type', 'application/json')
26+
const token = localStorage.getItem('token')
27+
const pathname = window.location.pathname
28+
if (token) {
29+
xhr.setRequestHeader('Authorization', token)
30+
xhr.onreadystatechange = function () {
31+
if (xhr.readyState === 4) {
32+
if (xhr.status === 200) {
33+
window.location.href = pathname
34+
}
35+
if (xhr.status === 401) {
36+
window.location.href = '/admin/login'
37+
}
38+
}
39+
}
40+
41+
xhr.send()
42+
} else {
43+
window.location.href = '/admin/login'
44+
}
45+
}
46+
</script>
47+
</head>
48+
<body></body>
49+
</html>
50+
51+
"""
52+
53+
54+
class DocHeadersMiddleware(MiddlewareMixin):
55+
def process_response(self, request, response):
56+
if request.path.startswith('/doc/') or request.path.startswith('/doc/chat/'):
57+
HTTP_REFERER = request.META.get('HTTP_REFERER')
58+
if HTTP_REFERER is None:
59+
return HttpResponse(content)
60+
if HTTP_REFERER == request._current_scheme_host + request.path:
61+
return response
62+
return response

0 commit comments

Comments
 (0)