CORS fixes: (#6310)

* CORS fixes:

- Update CORS headers in settings.py

* Remove dead code
This commit is contained in:
Oliver 2024-01-22 15:48:58 +11:00 committed by GitHub
parent 917a88c6f4
commit edad000d8e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 46 additions and 29 deletions

View File

@ -25,6 +25,41 @@ class AuthRequiredMiddleware(object):
"""Save response object.""" """Save response object."""
self.get_response = get_response self.get_response = get_response
def get_auth_headers(self, request):
"""Extract authorization headers from request."""
keys = ['Authorization', 'authorization']
for k in keys:
if k in request.headers.keys():
return request.headers[k]
return None
def check_token(self, request) -> bool:
"""Check if the user is authenticated via token."""
auth = self.get_auth_headers(request)
if not auth:
return False
auth = auth.strip().lower().split()
if len(auth) > 1 and auth[0].startswith('token'):
token = auth[1]
# Does the provided token match a valid user?
try:
token = ApiToken.objects.get(key=token)
if token.active and token.user:
# Provide the user information to the request
request.user = token.user
return True
except ApiToken.DoesNotExist:
logger.warning('Access denied for unknown token %s', token)
return False
def __call__(self, request): def __call__(self, request):
"""Check if user needs to be authenticated and is. """Check if user needs to be authenticated and is.
@ -70,28 +105,8 @@ class AuthRequiredMiddleware(object):
): ):
authorized = True authorized = True
elif ( elif self.check_token(request):
'Authorization' in request.headers.keys() authorized = True
or 'authorization' in request.headers.keys()
):
auth = request.headers.get(
'Authorization', request.headers.get('authorization')
).strip()
if auth.lower().startswith('token') and len(auth.split()) == 2:
token_key = auth.split()[1]
# Does the provided token match a valid user?
try:
token = ApiToken.objects.get(key=token_key)
if token.active and token.user:
# Provide the user information to the request
request.user = token.user
authorized = True
except ApiToken.DoesNotExist:
logger.warning('Access denied for unknown token %s', token_key)
# No authorization was found for the request # No authorization was found for the request
if not authorized: if not authorized:

View File

@ -131,15 +131,17 @@ ALLOWED_HOSTS = get_setting(
# Cross Origin Resource Sharing (CORS) options # Cross Origin Resource Sharing (CORS) options
# Extract CORS options from configuration file
CORS_ALLOW_ALL_ORIGINS = get_boolean_setting(
'INVENTREE_CORS_ORIGIN_ALLOW_ALL', config_key='cors.allow_all', default_value=DEBUG
)
CORS_ALLOW_CREDENTIALS = True
# Only allow CORS access to API and media endpoints # Only allow CORS access to API and media endpoints
CORS_URLS_REGEX = r'^/(api|media|static)/.*$' CORS_URLS_REGEX = r'^/(api|media|static)/.*$'
# Extract CORS options from configuration file CORS_ALLOWED_ORIGINS = get_setting(
CORS_ORIGIN_ALLOW_ALL = get_boolean_setting(
'INVENTREE_CORS_ORIGIN_ALLOW_ALL', config_key='cors.allow_all', default_value=False
)
CORS_ORIGIN_WHITELIST = get_setting(
'INVENTREE_CORS_ORIGIN_WHITELIST', 'INVENTREE_CORS_ORIGIN_WHITELIST',
config_key='cors.whitelist', config_key='cors.whitelist',
default_value=[], default_value=[],
@ -263,9 +265,9 @@ MIDDLEWARE = CONFIG.get(
'x_forwarded_for.middleware.XForwardedForMiddleware', 'x_forwarded_for.middleware.XForwardedForMiddleware',
'user_sessions.middleware.SessionMiddleware', # db user sessions 'user_sessions.middleware.SessionMiddleware', # db user sessions
'django.middleware.locale.LocaleMiddleware', 'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsMiddleware', 'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'InvenTree.middleware.InvenTreeRemoteUserMiddleware', # Remote / proxy auth 'InvenTree.middleware.InvenTreeRemoteUserMiddleware', # Remote / proxy auth
'django_otp.middleware.OTPMiddleware', # MFA support 'django_otp.middleware.OTPMiddleware', # MFA support