Django logs user IP for user_login_failed signal

I would like to register the IP address of the user in my Django application, especially for logging in, logging out, and failed login events. I use Django's built-in functions as follows:

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) 

The problem is that I did not find a way to get the IP for the user_login_failed signal, since this function does not have request in the parameters ( https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#module-django. contrib.auth.signals ). The credentials parameter is a dictionary that contains only the username and password fields.

How can I get the IP address for this signal?

Many thanks for your help.

+6
source share
2 answers

Unfortunately user_login_failed singal does not pass the request as an argument.

Checkout django-axes - https://github.com/django-pci/django-axes/

It uses a custom decoder to track failed inputs.

https://github.com/django-pci/django-axes/blob/master/axes/decorators.py#L273

+3
source

You can override the login form and intercept it there. At this point he has a request.

 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 

To install it on the site, you need to attach it to django.contrib.admin.site.login_form

I would suggest doing this in your App Store () application as follows:

 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 
0
source

Source: https://habr.com/ru/post/983210/


All Articles