2014-10-12

Django user login & logout signals

I would like to do something when a user logs in and out from my Django 1.7 project. The best way to do it is to take advantage of the Django Authentication System Login and Logout signals.

First I need to define the signal handlers in a signals submodule in one of Django application. (Note 1) In this case, I just write a log entry whenever a user logs in or logs out.
=== myapp/signals.py ===

from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.dispatch import receiver
from django.conf import settings

@receiver(user_logged_in)
def sig_user_logged_in(sender, user, request, **kwargs):
    logger = logging.getLogger(__name__)
    logger.info("user logged in: %s at %s" % (user, request.META['REMOTE_ADDR']))

@receiver(user_logged_out)
def sig_user_logged_out(sender, user, request, **kwargs):
    logger = logging.getLogger(__name__)
    logger.info("user logged out: %s at %s" % (user, request.META['REMOTE_ADDR']))
Then I create an application config in an apps submodule and override the Ready() method to register the signals. (Note 2)
=== myapp/apps.py ===

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'MyApp'
    verbose_name = "My Application"

    def ready(self):
        import myapp.signals # register the signals
Finally I put 'myapp.apps.MyAppConfig' in the INSTALLED_APPS setting. (Note 3)
=== myproject/settings.py ===

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp.apps.MyAppConfig',
)
The log will look like something similar to the following.
=== app.log === 

[2014-10-09 05:08:28,372] INFO [myapp.signals:10] user logged in: david at 127.0.0.1
[2014-10-09 05:08:29,791] INFO [myapp.signals:15] user logged out: david at 127.0.0.1

3 comments:

Anonymous said...

I was searching for something like this, I am implementing multi tenancy using django Sites framework and i used this login signal example to compare the user site with the request site and force user logout if mismatched.

Gopi R said...

where can i find app.log??

Александр Веклич said...

Nowhere, you must configure your logger