Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django log user IP for user_login_failed signal

I would like to log the user IP address in my Django application, specifically for login, logout and failed login events. I'm using Django builtin 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 issue is that I haven't found a way to get the IP for the user_login_failed signal since this function does not have the 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 only contains the username and password fields.

How could I get the IP address for this signal?

Many thanks in advance for your help.

like image 831
Sebastien Damaye Avatar asked Mar 02 '15 10:03

Sebastien Damaye


2 Answers

Unfortunately user_login_failed singal don't pass request as argument.

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

It uses a custom view decorator to track failed logins.

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

like image 81
mishbah Avatar answered Oct 20 '22 09:10

mishbah


I just found in newer Django version (I am using 2.1) has updated this and now it includes the request object in the user_login_failed signal:

https://docs.djangoproject.com/en/2.1/ref/contrib/auth/#django.contrib.auth.signals.user_login_failed

like image 41
Raymond Chen Avatar answered Oct 20 '22 07:10

Raymond Chen