我想在我的Django应用程序中记录用户IP地址,特别是登录,注销和失败的登录事件。我正在使用Django内置函数,如下所示:
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from ipware.ip import get_ip
import logging
logger = logging.getLogger(__name__)
def log_logged_in(sender, user, request, **kwargs):
logger.info("%s User %s successfully logged in" % (get_ip(request), user))
def log_logged_out(sender, user, request, **kwargs):
logger.info("%s User %s successfully logged out" % (get_ip(request), user))
def log_login_failed(sender, credentials, **kwargs):
logger.warning("%s Authentication failure for user %s" % ("...IP...", credentials['username']))
user_logged_in.connect(log_logged_in)
user_logged_out.connect(log_logged_out)
user_login_failed.connect(log_login_failed)
问题在于我没有找到获取user_login_failed
信号的IP的方法,因为此函数在参数(https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#module-django.contrib.auth.signals)中没有request
。 credentials
参数是仅包含username
和password
字段的字典。
我怎样才能获得此信号的IP地址?
非常感谢您的帮助。
答案 0 :(得分:3)
不幸的是,user_login_failed
不能将请求作为参数传递。
结帐django-axes
- https://github.com/django-pci/django-axes/
它使用自定义视图装饰器来跟踪失败的登录信息。
https://github.com/django-pci/django-axes/blob/master/axes/decorators.py#L273
答案 1 :(得分:0)
您可以覆盖登录表单并在那里拦截它。 它在那个阶段有要求。
import logging
from django.contrib.admin.forms import AdminAuthenticationForm
from django import forms
log = logging.getLogger(__name__)
class AuthenticationForm(AdminAuthenticationForm):
def clean(self):
# to cover more complex cases:
# http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
ip = request.META.get('REMOTE_ADDR')
try:
data = super(AuthenticationForm, self).clean()
except forms.ValidationError:
log.info('Login Failed (%s) from (%s)', self.cleaned_data.get('username'), ip)
raise
if bool(self.user_cache):
log.info('Login Success (%s) from (%s)', self.cleaned_data.get('username'), ip)
else:
log.info('Login Failed (%s) from (%s)', self.cleaned_data.get('username'), ip)
return data
要将其安装到网站中,您需要将其附加到django.contrib.admin.site.login_form
我建议你在App的ready()方法中这样做:
from django.contrib.admin import site as admin_site
class Config(AppConfig):
...
def ready(self):
# Attach the logging hook to the login form
from .forms import AuthenticationForm
admin_site.login_form = AuthenticationForm
答案 2 :(得分:0)
我刚刚发现在较新的Django版本(我正在使用2.1)中对此进行了更新,现在它在user_login_failed信号中包括了请求对象: