[英]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.
日志代码应插入此https://github.com/django/django/blob/master/django/contrib/auth/ init .py#L183中(如果阻止)。
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
. 目前看来,我将需要覆盖整个
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: 为什么不复制get_user函数并将记录器放入您想要的位置:
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 并像您想要的那样在代码中使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.