Django User Sessions’s Documentation

Django includes excellent built-in sessions, however all the data is hidden away into base64 encoded data. This makes it very difficult to run a query on all active sessions for a particular user. django-user-sessions fixes this and makes session objects a first class citizen like other ORM objects.

Contents:

Installation

  1. pip install django-user-sessions
  2. In INSTALLED_APPS replace 'django.contrib.sessions' with 'user_sessions'.
  3. In MIDDLEWARE or MIDDLEWARE_CLASSES replace 'django.contrib.sessions.middleware.SessionMiddleware' with 'user_sessions.middleware.SessionMiddleware'.
  4. Add SESSION_ENGINE = 'user_sessions.backends.db'.
  5. Add url(r'', include('user_sessions.urls', 'user_sessions')), to your urls.py.
  6. Make sure LOGOUT_REDIRECT_URL is set to some page to redirect users after logging out.
  7. Run python manage.py syncdb (or migrate) and browse to /account/sessions/.

System check framework

Django warns you about common configuration errors. When replacing the session middleware with the one provided by this library, it’ll start warning about admin.E410. You can silence this warning by adding the following line in your settings file:

SILENCED_SYSTEM_CHECKS = [‘admin.E410’]

GeoIP

You need to setup GeoIP for the location detection to work. See the Django documentation on installing GeoIP.

IP when behind a proxy

If you’re running Django behind a proxy like nginx, you will have to set the REMOTE_ADDR META header manually using a middleware, to stop it from always returning the ip of the proxy (e.g. 127.0.0.1 in many cases).

An example middleware to fix this issue is django-xforwardedfor-middleware which simply does this for each request:

request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()

Your particular configuration may vary, X-Forwarded-For must be set by a proxy that you have control over, otherwise it might be spoofed by the client.

Usage

Current session

The current session is available on the request, just like the normal session middleware makes the session available:

def my_view(request):
    request.session

All sessions

To get the list of a user’s sessions:

sessions = user.session_set.filter(expire_date__gt=now())

You could logout the user everywhere:

user.session_set.all().delete()

Generic views

There are two views included with this application, SessionListView and SessionDeleteView. Using this views you have a simple, but effective, user session management that even looks great out of the box:

_images/custom-view.png

Template tags

Two template tags are included device() and location(). These can be used for respectively humanizing the user agent string and showing an approximate location of the IP address:

{% load user_sessions %}
{{ session.user_agent|device }} -> Safari on OS X
{{ session.ip|location }}       -> Zwolle, The Netherlands

Admin views

The user’s IP address and user agent are also stored on the session. This allows to show a list of active sessions to the user in the admin:

_images/admin-view.png

Reference

Middleware

class user_sessions.middleware.SessionMiddleware(get_response=None)

Middleware that provides ip and user_agent to the session store.

Models

Session Backends

Template Tags

user_sessions.templatetags.user_sessions.device(value)

Transform a User Agent into human readable text.

Example output:

  • Safari on iPhone
  • Chrome on Windows 8.1
  • Safari on OS X
  • Firefox
  • Linux
  • None
user_sessions.templatetags.user_sessions.location(value)

Transform an IP address into an approximate location.

Example output:

  • Zwolle, The Netherlands
  • The Netherlands
  • None

Views

class user_sessions.views.SessionListView(**kwargs)

View for listing a user’s own sessions.

This view shows list of a user’s currently active sessions. You can override the template by providing your own template at user_sessions/session_list.html.

class user_sessions.views.SessionDeleteView(**kwargs)

View for deleting a user’s own session.

This view allows a user to delete an active session. For example log out a session from a computer at the local library or a friend’s place.

Unit tests

Release Notes

1.7.0

  • new: Support for Django 2.2+.
  • Dropped Django <2.2 support.

1.6.0

  • New: Support for Django 2.0.
  • Dropped Django <1.11 support.
  • Command for migrating existing sessions to the new session store (#33).

1.5.3

  • Fixed issue with incorrect location being displayed.

1.5.2

  • Also work with GeoIP2 country database.

1.5.1

  • Updated documentation for GeoIP2 library.
  • Correctly detect macOS version on Firefox.

1.5.0

  • Added Django 1.11 support.
  • Added support for GeoIP2 library.
  • Added detection of Windows 10 and macOS from user-agent.
  • Fixed #73 – Error when deleting individual session from list view.
  • Fixed #74 – user agent not being shown in list view.
  • Resolved Django’s deprecation warnings (preliminary Django 2.0 support).
  • Make templatetags return None instead of ‘unknown’, provide your own fallback value with default_if_none:.
  • Allow translation of fallback values.

1.4.0

  • Added Django Channels support.
  • Fixed #62 – Provide request.user in signals.
  • Ending current session will logout instead, make sure LOGOUT_REDIRECT_URL is set.

1.3.1

  • Added Django 1.10 support.

1.3.0

  • Added Django 1.9 support.
  • Dropped support for Django 1.7 and below.

1.2.0

  • New feature: delete all-but-current sessions.
  • Added clearsessions command.

1.1.1

  • Added Django 1.8 support.

1.1.0

  • Fixed #14 – Truncate long user agents strings.
  • Fixed #23 – Cannot use admin view search.
  • Added Django 1.7 migrations.

1.0.0

  • #8 – Consistent URL patterns.
  • #11 – Support Django 1.6’s ATOMIC_REQUESTS.
  • German translation added.

0.1.4

  • Python 3.4 support.
  • Django 1.7 (beta) support.
  • Italian translation added.
  • Chinese translation added.
  • Arabic translation updated.

0.1.3

  • Documentation.
  • Hebrew translation added.
  • Arabic translation added.
  • Fixed #3 – Reset user_id on logout.
  • Fixed #4 – Add explicit license text.

0.1.2

  • Ship with default templates.
  • Added Dutch translation.

0.1.1

  • Added South migrations.

0.1.0

  • Initial release.

Indices and tables