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.