简体   繁体   中英

Additional logging for django.contrib.auth

I want to log when session hash verification fails. The logging code should be inserted inside this https://github.com/django/django/blob/master/django/contrib/auth/ init .py#L183 if block.

I am trying to figure out what would be the best way to implement this. Currently it looks like I will need to override the whole django.contrib.auth.middleware.AuthenticationMiddleware .

Do you have any tips for me?

Why don't you copy get_user function and put the logger like you want to:

from django.contrib.auth import *    

def your_get_user(request):
    """
    Returns the user model instance associated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    from django.contrib.auth.models import User, AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
                    in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    log = logging.getLogger("YourLog")
                    log.debug(session_hash)
                    request.session.flush()
                    user = None

    return user or AnonymousUser()

And use this like you want to in your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM