Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 97 additions & 29 deletions apps/common/middleware/doc_headers_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,43 +9,102 @@
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

from common.auth import handles, TokenDetails

content = """
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
/* 弹框内容样式 */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% 从顶部和自动水平居中 */
padding: 20px;
border: 1px solid #888;
width: 80%; /* 宽度 */
}
</style>
<body>
<div class="modal-content">
<input type="text" id="auth-input" />
<button id="auth">认证</button>
<button id="goLogin">去登录</button>
</div>
<script>
window.onload = () => {
var xhr = new XMLHttpRequest()
xhr.open('GET', '/api/user', true)

xhr.setRequestHeader('Content-Type', 'application/json')
const token = localStorage.getItem('token')
const pathname = window.location.pathname
if (token) {
xhr.setRequestHeader('Authorization', token)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
window.location.href = pathname
}
if (xhr.status === 401) {
window.location.href = '/ui/login'
}
const setCookie = (name, value, days) => {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 2);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
};
const authToken = (token) => {
return new Promise((resolve, reject) => {
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/api/user", true);
xhr.setRequestHeader("Content-Type", "application/json");
const pathname = window.location.pathname;
if (token) {
xhr.setRequestHeader("Authorization", token);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(true);
} else {
reject(true);
}
}
};

xhr.send();
}
} catch (e) {
reject(false);
}
});
};
window.onload = () => {
const token = localStorage.getItem("token");
authToken(token)
.then(() => {
setCookie("Authorization", token);
window.location.href = window.location.pathname;
})
.catch((e) => {});
};
// 获取元素
const auth = document.getElementById("auth");
const goLogin = document.getElementById("goLogin");

xhr.send()
} else {
window.location.href = '/ui/login'
}
}
// 打开弹框函数
auth.onclick = ()=> {
const authInput = document.getElementById("auth-input");
const token = authInput.value
authToken(token)
.then(() => {
setCookie("Authorization", token);
window.location.href = window.location.pathname;
})
.catch((e) => {
alert("令牌错误");
});
};

// 去系统的登录页面
goLogin.onclick = ()=> {
window.location.href = "/ui/login";
};
</script>
</head>
<body></body>
</body>
</html>

"""
Expand All @@ -54,9 +113,18 @@
class DocHeadersMiddleware(MiddlewareMixin):
def process_response(self, request, response):
if request.path.startswith('/doc/') or request.path.startswith('/doc/chat/'):
HTTP_REFERER = request.META.get('HTTP_REFERER')
if HTTP_REFERER is None:
auth = request.COOKIES.get('Authorization')
if auth is None:
return HttpResponse(content)
if HTTP_REFERER == request._current_scheme_host + request.path:
return response
else:
try:
token = auth
token_details = TokenDetails(token)
for handle in handles:
if handle.support(request, token, token_details.get_token_details):
handle.handle(request, token, token_details.get_token_details)
return response
return HttpResponse(content)
except Exception as e:
return HttpResponse(content)
return response
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided Django middleware introduces several potential issues and improvements:

  1. Security Issues:

    • The TokenDetails class does not appear to properly validate tokens or decode them securely. This could lead to security vulnerabilities such as data leakage if not implemented correctly.
  2. Handling Redirects Without Authentication Checks:

    • The DocHeadersMiddleware checks for specific paths (/doc/ and /doc/chat/) but only performs a check against the Referer header before allowing access through another redirect loop if it matches. For these paths, it should enforce authentication instead of using an incorrect redirection method.
  3. Improper Error Handling and User Feedback:

    • When handling errors during token checking, there is no user feedback mechanism. In practice, users need clear instructions on what went wrong rather than being redirected without notice.

Suggested Improvements

Token Validation

Ensure that TokenDetails has methods to safely validate and parse tokens. This might involve integrating with a JWT library or another secure method to ensure integrity and authenticity.

class TokenDetails:
    def __init__(self, token):
        self.token = token

    def get_token_details(self):
        # Implement logic to unpack and verify the token
        raise NotImplementedError  # Placeholder for actual implementation

Middleware Logic

Update the process_response method to perform proper authentication and authorization checks for those paths where access depends on authentication. Here's an example that incorporates some basic logic:

def authenticate_request(request):
    auth_token = request.COOKIES.get('Authorization')
    
    if auth_token:
        try:
            token_details = TokenDetails(auth_token)
        
            # Use token_details object to determine which handles support the current request
            handles_for_request = list(filter(lambda h: h.support(request, request.user.id), handles))
            
            # If at least one handler supports this request...
            if handles_for_request:
                return True
    
        except Exception as e:
            pass
    
    return False

class DocHeadersMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        paths_to_authenticate = ["/doc/", "/doc/chat/"]
        
        if any(request.path.endswith(part) for part in paths_to_authenticate):
            if not authenticate_request(request):
                return HttpResponse(content)
            else:
                cookie = "Authorization"
                value = f"{request.user.username}:{request.user.password}"  # Example values for demo purposes
                
                # Set cookies securely and persistently across browser sessions
                set_cookie(cookie, value, days=7)
                
                return response
        
        return response

In summary, while some optimizations have been made regarding style (refactoring the style section out of comments and cleaning up HTML tags), critical areas involving security and correctness remain. Ensuring proper validation of tokens and implementing more robust error handling will enhance the overall functionality and reliability of the application.

Loading