From edad000d8e5adfb272b4f197414aaecb6c183b6e Mon Sep 17 00:00:00 2001 From: Oliver Date: Mon, 22 Jan 2024 15:48:58 +1100 Subject: [PATCH] CORS fixes: (#6310) * CORS fixes: - Update CORS headers in settings.py * Remove dead code --- InvenTree/InvenTree/middleware.py | 59 +++++++++++++++++++------------ InvenTree/InvenTree/settings.py | 16 +++++---- 2 files changed, 46 insertions(+), 29 deletions(-) diff --git a/InvenTree/InvenTree/middleware.py b/InvenTree/InvenTree/middleware.py index 79f51b7914..1691b2225b 100644 --- a/InvenTree/InvenTree/middleware.py +++ b/InvenTree/InvenTree/middleware.py @@ -25,6 +25,41 @@ class AuthRequiredMiddleware(object): """Save response object.""" 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): """Check if user needs to be authenticated and is. @@ -70,28 +105,8 @@ class AuthRequiredMiddleware(object): ): authorized = True - elif ( - 'Authorization' in request.headers.keys() - 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) + elif self.check_token(request): + authorized = True # No authorization was found for the request if not authorized: diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index f16ebaf6de..127a68afae 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -131,15 +131,17 @@ ALLOWED_HOSTS = get_setting( # 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 CORS_URLS_REGEX = r'^/(api|media|static)/.*$' -# Extract CORS options from configuration file -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( +CORS_ALLOWED_ORIGINS = get_setting( 'INVENTREE_CORS_ORIGIN_WHITELIST', config_key='cors.whitelist', default_value=[], @@ -263,9 +265,9 @@ MIDDLEWARE = CONFIG.get( 'x_forwarded_for.middleware.XForwardedForMiddleware', 'user_sessions.middleware.SessionMiddleware', # db user sessions 'django.middleware.locale.LocaleMiddleware', - 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', + 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'InvenTree.middleware.InvenTreeRemoteUserMiddleware', # Remote / proxy auth 'django_otp.middleware.OTPMiddleware', # MFA support