92 lines
3.3 KiB
Python
92 lines
3.3 KiB
Python
import re
|
|
import logging
|
|
from gvsds.app_config import getlist as _app_getlist, get as _app_get
|
|
from gvsdsdk.auth.cookie import ELT_COOKIE_NAME
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class DomainMiddleware:
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
self.known_domains = set(_app_getlist('domain', 'KNOWN_DOMAINS', fallback=[
|
|
'gvsds.com', 'gvsds.dev', 'yc8z.org', 'ycbz.org', 'gvsds.org', 'gvsds.studio',
|
|
]))
|
|
self._ip_pattern = re.compile(r'^\d{1,3}(\.\d{1,3}){3}$')
|
|
|
|
def __call__(self, request):
|
|
host = request.get_host().split(':')[0]
|
|
request.subdomain = 'www'
|
|
|
|
if self._ip_pattern.match(host):
|
|
pass
|
|
elif host.startswith('[') or ':' in host:
|
|
pass
|
|
else:
|
|
domain_parts = host.split('.')
|
|
if len(domain_parts) >= 3:
|
|
request.subdomain = domain_parts[0]
|
|
elif len(domain_parts) == 2:
|
|
if domain_parts[1] in ('localhost', '127.0.0.1'):
|
|
request.subdomain = domain_parts[0]
|
|
elif domain_parts[0] in self.known_domains or domain_parts[1] in self.known_domains:
|
|
request.subdomain = 'www'
|
|
|
|
response = self.get_response(request)
|
|
|
|
# CORS 由 django-cors-headers (CorsMiddleware) 统一处理,此处不再手动设置
|
|
|
|
csp_domain = _app_get('domain', 'CSP_DOMAIN', fallback='gvsds.com')
|
|
allowed_frame_ancestors = f"'self' https://www.{csp_domain} https://gerp.{csp_domain} https://ugm.{csp_domain}"
|
|
response['Content-Security-Policy'] = f"frame-ancestors {allowed_frame_ancestors}"
|
|
|
|
return response
|
|
|
|
def process_exception(self, request, exception):
|
|
return None
|
|
|
|
|
|
from gvsdsdk.auth.middleware import ELTAuthMiddleware, CurrentRoleMiddleware
|
|
|
|
|
|
class ErrorLoggingMiddleware:
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
|
|
def __call__(self, request):
|
|
response = self.get_response(request)
|
|
if getattr(response, 'status_code', 0) >= 500:
|
|
exc = getattr(request, '_caught_exception', None)
|
|
if exc:
|
|
logger.error(
|
|
'[%s] [%d] [%s] [%s] %s',
|
|
request.META.get('HTTP_HOST', 'unknown'),
|
|
response.status_code,
|
|
request.method,
|
|
request.META.get('REMOTE_ADDR', '-'),
|
|
request.get_full_path(),
|
|
exc_info=(type(exc), exc, exc.__traceback__),
|
|
)
|
|
else:
|
|
logger.error(
|
|
'[%s] [%d] [%s] [%s] %s',
|
|
request.META.get('HTTP_HOST', 'unknown'),
|
|
response.status_code,
|
|
request.method,
|
|
request.META.get('REMOTE_ADDR', '-'),
|
|
request.get_full_path(),
|
|
)
|
|
return response
|
|
|
|
def process_exception(self, request, exception):
|
|
request._caught_exception = exception
|
|
logger.error(
|
|
'[%s] [500] [%s] [%s] %s',
|
|
request.META.get('HTTP_HOST', 'unknown'),
|
|
request.method,
|
|
request.META.get('REMOTE_ADDR', '-'),
|
|
request.get_full_path(),
|
|
exc_info=(type(exception), exception, exception.__traceback__),
|
|
)
|
|
return None
|