HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/unlimited-leads/Unlimited-Leads-Be/utils/swagger/ui_protection.py
from django.http import HttpResponse
from django.conf import settings
import base64

class SWAGGER_UI_Protection:
    def __init__(self):
        self.swagger_ui_username = settings.SWAGGER_UI_PROTECTION_USERNAME
        self.swagger_ui_password = settings.SWAGGER_UI_PROTECTION_PASSWORD

    def basic_auth_required(self, view_func):
        """Protect the Swagger UI endpoint with basic authentication."""

        def _wrapped_view(request, *args, **kwargs):
            # Check if the Authorization header is present
            auth_header = request.headers.get('Authorization')

            if auth_header and auth_header.startswith('Basic '):
                try:
                    # Decode the Base64 encoded credentials
                    encoded_credentials = auth_header.split(' ')[1]
                    decoded_credentials = base64.b64decode(encoded_credentials).decode('utf-8')
                    username, password = decoded_credentials.split(':', 1)

                    # Validate the credentials
                    if username == self.swagger_ui_username and password == self.swagger_ui_password:
                        print("Inside ")
                        return view_func(request, *args, **kwargs)
                    else:
                        print("Inside My Else Condition !")
                        response = HttpResponse('Unauthorized', status=401)
                        # response['WWW-Authenticate'] = 'Basic realm="Swagger UI"'
                        return response
                except (ValueError, base64.binascii.Error):
                    # Invalid Base64 or credentials
                    return HttpResponse('Unauthorized', status=401)
                    # pass

            # If credentials are invalid or missing, prompt for Basic Auth
            response = HttpResponse('Unauthorized', status=401)
            response['WWW-Authenticate'] = 'Basic realm="Swagger UI"'
            return response

        return _wrapped_view

# # Example usage:
# # protection = SWAGGER_UI_Protection()
# # @protection.basic_auth_required
# # def your_view(request):
# #     return HttpResponse("Swagger UI is protected.")