Skip to content

Commit

Permalink
Merge pull request #1 from fretscha/feature/add-minimal-logging
Browse files Browse the repository at this point in the history
add logging to middleware
  • Loading branch information
fretscha authored Aug 18, 2024
2 parents c4a2565 + f55bd2c commit 7e3a2be
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions mtls_auth/middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from django.contrib.auth import authenticate, get_user_model, login
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
Expand All @@ -6,46 +8,47 @@
from .utils import get_user_data_extractor_class

User = get_user_model()
logger = logging.getLogger(__name__)


class MTLSAuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request):
# Skip middleware if the user is already authenticated
if request.user.is_authenticated:
logger.debug("User already authenticated, skipping MTLS authentication")
return None

# Check for authentication headers
user_dn = request.headers.get(USER_DN_HEADER)
issuer_dn = request.headers.get(ISSUER_DN_HEADER)
success = request.headers.get(SUCCESS_HEADER)
userdata_extractor = get_user_data_extractor_class()()

if user_dn and success == "SUCCESS":
# Authenticate the user based on the headers
logger.info(f"Attempting MTLS authentication for user_dn: {user_dn}")
if self.verify_valid(user_dn, issuer_dn):
user_data = userdata_extractor.get_userdata(user_dn)
if AUTOCREATE_USER:
# Check if the user exists, create if it doesn't
user, created = User.objects.get_or_create(username=user_data.get("username"), defaults=user_data)

if created:
# Optionally set additional fields or defaults
user.set_unusable_password() # If no password is needed
logger.info(f"Created new user: {user.username}")
user.set_unusable_password()
user.save()
else:
# Authenticate user
user = authenticate(request, username=user_data["username"])

if user is not None:
login(request, user)
logger.info(f"Successfully authenticated user: {user.username}")
return None
else:
logger.warning(f"Invalid user for user_dn: {user_dn}")
return JsonResponse({"error": "Invalid user"}, status=401)
else:
logger.error(f"Invalid MTLS certificate for user_dn: {user_dn}")
return JsonResponse({"error": "invalid MTLS certificate"}, status=401)
else:
# Fallback to traditional username/password authentication
logger.debug("MTLS authentication headers not present, falling back to traditional authentication")
return None

def verify_valid(self, user_dn, issuer_dn):
print(f"Verifying user {user_dn} with issuer {issuer_dn}")
logger.debug(f"Verifying user {user_dn} with issuer {issuer_dn}")
return True

0 comments on commit 7e3a2be

Please sign in to comment.