-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat: doc auth #2752
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: doc auth #2752
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| # coding=utf-8 | ||
| """ | ||
| @project: maxkb | ||
| @Author:虎 | ||
| @file: static_headers_middleware.py | ||
| @date:2024/3/13 18:26 | ||
| @desc: | ||
| """ | ||
| from django.http import HttpResponse | ||
| from django.utils.deprecation import MiddlewareMixin | ||
|
|
||
| content = """ | ||
| <!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> | ||
| <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' | ||
| } | ||
| } | ||
| } | ||
|
|
||
| xhr.send() | ||
| } else { | ||
| window.location.href = '/ui/login' | ||
| } | ||
| } | ||
| </script> | ||
| </head> | ||
| <body></body> | ||
| </html> | ||
|
|
||
| """ | ||
|
|
||
|
|
||
| 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: | ||
| return HttpResponse(content) | ||
| if HTTP_REFERER == request._current_scheme_host + request.path: | ||
| return response | ||
| return response | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -57,8 +57,8 @@ | |
| 'django.contrib.messages.middleware.MessageMiddleware', | ||
| 'common.middleware.gzip.GZipMiddleware', | ||
| 'common.middleware.static_headers_middleware.StaticHeadersMiddleware', | ||
| 'common.middleware.cross_domain_middleware.CrossDomainMiddleware' | ||
|
|
||
| 'common.middleware.cross_domain_middleware.CrossDomainMiddleware', | ||
| 'common.middleware.doc_headers_middleware.DocHeadersMiddleware' | ||
| ] | ||
|
|
||
| JWT_AUTH = { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The provided code snippet looks mostly correct with the exception of a minor issue in the whitespace formatting around commas inside dictionaries. Here is an optimized version of the file: # common/middleware.py
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'common.middleware.gzip.GZipMiddleware',
'common.middleware.static_headers_middleware.StaticHeadersMiddleware',
'common.middleware.cross_domain_middleware.CrossDomainMiddleware',
'common.middleware.doc_headers_middleware.DocHeadersMiddleware',
]
JWT_AUTH = {
}Optimization Suggestions:
This should resolve any syntax errors related to the extra trailing comma before the closing brace |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,13 +9,23 @@ const envDir = './env' | |
| // https://vitejs.dev/config/ | ||
| export default defineConfig(({ mode }) => { | ||
| const ENV = loadEnv(mode, envDir) | ||
| const prefix = process.env.VITE_DYNAMIC_PREFIX || ENV.VITE_BASE_PATH; | ||
| const prefix = process.env.VITE_DYNAMIC_PREFIX || ENV.VITE_BASE_PATH | ||
| const proxyConf: Record<string, string | ProxyOptions> = {} | ||
| proxyConf['/api'] = { | ||
| target: 'http://127.0.0.1:8080', | ||
| changeOrigin: true, | ||
| rewrite: (path) => path.replace(ENV.VITE_BASE_PATH, '/') | ||
| } | ||
| proxyConf['/doc'] = { | ||
| target: 'http://127.0.0.1:8080', | ||
| changeOrigin: true, | ||
| rewrite: (path) => path.replace(ENV.VITE_BASE_PATH, '/') | ||
| } | ||
| proxyConf['/static'] = { | ||
| target: 'http://127.0.0.1:8080', | ||
| changeOrigin: true, | ||
| rewrite: (path) => path.replace(ENV.VITE_BASE_PATH, '/') | ||
| } | ||
| return { | ||
| preflight: false, | ||
| lintOnSave: false, | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This code looks mostly correct and should work as intended. However, here are a few minor considerations:
Here's an updated version of your config with these points considered: const dotenv = require('dotenv');
const { defineConfig } = require('vite');
const envDir = './env';
const ENV = dotenv.config({ path: `${envDir}/.env.${process.env.NODE_ENV}` }).parsed;
function getPrefix() {
return (ENV.VITE_DYNAMIC_PREFIX && process.env.VITE_DYNAMIC_PREFIX) || ENV.VITE_BASE_PATH;
}
module.exports = defineConfig(({ mode }) => {
const prefix = getPrefix();
const proxyConf: Record<string, string | ProxyOptions> = {};
proxyConf['/api'] = {
target: 'http://127.0.0.1:8080',
changeOrigin: true,
pathRewrite: (_path) => `/`,
redirect: {
permanent: false
},
rewrite(path) {
return path.replace(prefix, `/`);
}
};
proxyConf['/doc'] = {
target: 'http://127.0.0.1:8080',
changeOrigin: true,
pathRewrite: (_path) => `/api/docs`,
redirect: {
permanent: false
},
rewrite(path) {
return path.replace(prefix, `/api/docs`);
}
};
proxyConf['/static'] = {
target: 'http://127.0.0.1:8080/static/',
changeOrigin: true,
pathRewrite: (_path) => `/static/`,
redirect: {
permanent: false
},
rewrite(path) {
return path.replace(prefix, `/static/`);
}
};
return {
base: prefix,
preflight: false,
lintOnSave: false,
// Other configurations...
};
});Key Changes:
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided code appears to be implementing a Django middleware that serves static HTML pages with specific conditions. Here's a review of the code for irregularities, potential issues, and optimizations:
Irregularities/Issues
Imports: Ensure that
django.utils.deprecationis imported correctly. Since Middlewares were moved fromutils.deprecationtocore.middleware.common, it should befrom django.core.middleware.common import MiddlewareMixin.Variable Name Conflicts: The variable name
contentcould conflict with other variables in the same file or module, which might lead to unintended behavior.Docstring Format: While not strictly an issue, following PEP 8 guidelines would suggest using triple double quotation marks (
""") for docstrings instead of triple single quotation marks (''').Code Duplication: The
onloadscript is duplicated within the<head>section. If this behavior is intentional, consider consolidating it into a separate JavaScript file or template.Security Considerations:
window.location.hrefdirectly without proper validation can make your code vulnerable to cross-site scripting (XSS) attacks. Validate incoming data before processing headers likeAuthorization./api/userand/ui/loginmay become problematic if these endpoints change.Versioning: Make sure the code supports Python 3, as mentioned in the comment at the top of the file.
Testing: It’s beneficial to test this middleware thoroughly, especially considering edge cases such as different hostnames and referers.
Optimization Suggestions
Template Injection Prevention: Use parameterized queries or templating engines to prevent XSS vulnerabilities when generating dynamic content.
Caching: For static pages served via this middleware, consider caching mechanisms depending on how frequently they change.
Consolidate Code: Consolidate redundant logic, possibly moving parts of the script outside of the HTML to improve readability and maintainability.
Here's a revised version incorporating some of these suggestions:
This version includes helper functions for dynamically generating the document content based on additional metadata passed through the header. The use of inline styles makes it easier to manage CSS rules.