From 8080e462155e9eff2aa29dff771672fb30ec6c4d Mon Sep 17 00:00:00 2001 From: Lubos Mjachky Date: Tue, 11 Apr 2023 14:47:54 +0200 Subject: [PATCH] Handle unauthorized exceptions in a custom handler closes #1254 --- CHANGES/1254.bugfix | 1 + pulp_container/app/exceptions.py | 17 ++++++++++++++++- pulp_container/app/registry_api.py | 1 - pulp_container/app/settings.py | 7 +++++++ 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 CHANGES/1254.bugfix diff --git a/CHANGES/1254.bugfix b/CHANGES/1254.bugfix new file mode 100644 index 000000000..00a6b61f1 --- /dev/null +++ b/CHANGES/1254.bugfix @@ -0,0 +1 @@ +Fixed a bug that disallowed users to configure custom authentication classes for the token server. diff --git a/pulp_container/app/exceptions.py b/pulp_container/app/exceptions.py index 8b2c998ed..634b610b6 100644 --- a/pulp_container/app/exceptions.py +++ b/pulp_container/app/exceptions.py @@ -1,4 +1,19 @@ -from rest_framework.exceptions import NotFound, ParseError +from rest_framework import status, views +from rest_framework.exceptions import ( + AuthenticationFailed, + NotAuthenticated, + NotFound, + ParseError, +) + + +def unauthorized_exception_handler(exc, context): + response = views.exception_handler(exc, context) + + if isinstance(exc, (AuthenticationFailed, NotAuthenticated)): + response.status_code = status.HTTP_401_UNAUTHORIZED + + return response class RepositoryNotFound(NotFound): diff --git a/pulp_container/app/registry_api.py b/pulp_container/app/registry_api.py index 8318a66eb..464497e15 100644 --- a/pulp_container/app/registry_api.py +++ b/pulp_container/app/registry_api.py @@ -357,7 +357,6 @@ class BearerTokenView(APIView): """ # Allow everyone to access but still value authenticated users. - authentication_classes = [BasicAuthentication] permission_classes = [] def get(self, request): diff --git a/pulp_container/app/settings.py b/pulp_container/app/settings.py index a1e413b24..63652514b 100644 --- a/pulp_container/app/settings.py +++ b/pulp_container/app/settings.py @@ -1,4 +1,11 @@ +from django.conf import settings + DRF_ACCESS_POLICY = { "dynaconf_merge_unique": True, "reusable_conditions": ["pulp_container.app.global_access_conditions"], } + +REST_FRAMEWORK = settings.REST_FRAMEWORK +REST_FRAMEWORK.update( + {"EXCEPTION_HANDLER": "pulp_container.app.exceptions.unauthorized_exception_handler"} +)