Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log both successful and failed login and logout attempts in Django?

I want to record all user login and logout attempts in Django. This record should show a history of all users who logged in/out, IP address and time of login/logout.

The django_admin_log table seems to only record ADD/DELETE/CHANGE activities of other models, not a history of user access. I've also already checked the user_logged_in, user_logged_out signals. It seems that if I will use these signals, I need to create a new table to record history of all user login/logout. Is there a built-in method in Django to do this? Or available packages? I've checked other packages, and those that are related to login attempts only limit failed attempts, but do not record successful logins/logouts.

like image 498
ryan_2016 Avatar asked Jun 03 '16 15:06

ryan_2016


People also ask

How does Django track user activity?

Go to the Django Admin by changing the URL in your browser to "http://localhost:8000/admin". The Django Admin login page will appear. Enter the username and password of the superuser you just created with the manage.py command to log in. Next, you will see the Django admin dashboard.

How does logout work in Django?

logout() Django docs here. – C.B. Even if you don't log the users off immediately, they get logged off as soon as they try to access any view or the views in which the check is performed and invalid users are logout() .

How can I see the username as logged in Django?

get_username() will return a string of the users email. request. user. username will return a method.


1 Answers

You could hook up to the provided signals: django.contrib.auth.signals

Recording to log

import logging from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed from django.dispatch import receiver  log = logging.getLogger(__name__)  @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs):         # 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')      log.debug('login user: {user} via ip: {ip}'.format(         user=user,         ip=ip     ))  @receiver(user_logged_out) def user_logged_out_callback(sender, request, user, **kwargs):      ip = request.META.get('REMOTE_ADDR')      log.debug('logout user: {user} via ip: {ip}'.format(         user=user,         ip=ip     ))  @receiver(user_login_failed) def user_login_failed_callback(sender, credentials, **kwargs):     log.warning('login failed for: {credentials}'.format(         credentials=credentials,     )) 

Recording to model/database

So as this answer has not been accepted so far - here an example that sores the actions in a model instead of logging:

Model

# <your_app>/models.py  from django.db import models from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed from django.dispatch import receiver   class AuditEntry(models.Model):     action = models.CharField(max_length=64)     ip = models.GenericIPAddressField(null=True)     username = models.CharField(max_length=256, null=True)      def __unicode__(self):         return '{0} - {1} - {2}'.format(self.action, self.username, self.ip)      def __str__(self):         return '{0} - {1} - {2}'.format(self.action, self.username, self.ip)   @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs):       ip = request.META.get('REMOTE_ADDR')     AuditEntry.objects.create(action='user_logged_in', ip=ip, username=user.username)   @receiver(user_logged_out) def user_logged_out_callback(sender, request, user, **kwargs):       ip = request.META.get('REMOTE_ADDR')     AuditEntry.objects.create(action='user_logged_out', ip=ip, username=user.username)   @receiver(user_login_failed) def user_login_failed_callback(sender, credentials, **kwargs):     AuditEntry.objects.create(action='user_login_failed', username=credentials.get('username', None)) 

Admin

# <your_app>/admin.py from django.contrib import admin from models import AuditEntry  @admin.register(AuditEntry) class AuditEntryAdmin(admin.ModelAdmin):     list_display = ['action', 'username', 'ip',]     list_filter = ['action',] 
like image 97
ohrstrom Avatar answered Oct 05 '22 07:10

ohrstrom