• Stars
    star
    151
  • Rank 246,057 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extended session backends for Django (Sessions store IP, User Agent, and foreign key to User)

Django QSessions

pypi tests ci coverage MIT black

django-qsessions offers two extended session backends for Django. They extend Django's db and cached_db backends (and Session model) with following extra features:

  • Sessions have a foreign key to User
  • Sessions store IP and User Agent

These features help you implement "Session Management" and show a list of active sessions to the user. You can display IP, location and user agent for each session and add an option to revoke sessions.

Comparison

Here is a brief comparison between Django's session backends (db, cache, cached_db), and django-qsessions.

django qsessions
cache db cached_db db cached_db
Performance βœ”βœ” βœ” βœ”
Persistence βœ” βœ” βœ” βœ”
Foreign Key to User βœ” βœ”
Store IP and User Agent βœ” βœ”

Compatibility

  • Python: 3.7, 3.8, 3.9, 3.10
  • Django: 3.2, 4.0, 4.1

Installation

If your system is in production and there are active sessions using another session backend, you need to migrate them manually. We have no migration script.

  1. If you want to use the cached_db backend, make sure you've configured your cache. If you have multiple caches defined in CACHES, Django will use the default cache. To use another cache, set SESSION_CACHE_ALIAS to the name of that cache.

  2. Install the latest version from PyPI:

    pip install django-qsessions
  3. In settings:

    • In INSTALLED_APPS replace 'django.contrib.sessions' with 'qsessions'.
    • In MIDDLEWARE or MIDDLEWARE_CLASSES replace 'django.contrib.sessions.middleware.SessionMiddleware' with 'qsessions.middleware.SessionMiddleware'.
    • Set SESSION_ENGINE to:
      • 'qsessions.backends.cached_db' if you want to use cached_db backend.
      • 'qsessions.backends.db' if you want to use db backend.
  4. Run migrations to create qsessions.models.Session model.

    python manage.py migrate qsessions

To enable location detection using GeoIP2 (optional):

  1. Install geoip2 package:

    pip install geoip2
  2. Set GEOIP_PATH to a directory for storing GeoIP2 database.

  3. Run the following command to download latest GeoIP2 database. You can add this command to a cron job to update GeoIP2 DB automatically. Due to Maxmind license changes you will need to acquire and use a license key for downloading the databases. You can pass the key on the command line, or in the MAXMIND_LICENSE_KEY environment variable.

    python manage.py download_geoip_db -k mykey

Usage

django-qsessions has a custom Session model with following extra fields: user, user_agent, created_at, updated_at, ip.

Getting a user's sessions:

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

Deleting a session:

# Deletes session from both DB and cache
session.delete()

Logout a user:

user.session_set.all().delete()

Session creation time (user login time):

>>> session.created_at
datetime.datetime(2018, 6, 12, 17, 9, 17, 443909, tzinfo=<UTC>)

IP and user agent:

>>> session.ip
'127.0.0.1'
>>> session.user_agent
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'

And if you have configured GeoIP2, you can call .location(), .location_info():

>>> session.location()
'Tehran, Iran'

>>> session.location_info()
{'city': 'Tehran', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'IR', 'country_name': 'Iran', 'time_zone': 'Asia/Tehran', ...}

Admin page:

image

Caveats

  • session.updated_at is not the session's last activity. It's updated each time the session object in DB is saved. (e.g. when user logs in, or when ip, user agent, or session data changes)

Why not django-user-sessions?

django-user-sessions has the same functionality, but only extends the db backend. Using a cache can improve performance.

We got ideas and some codes from django-user-sessions. Many thanks to Bouke Haarsma for writing django-user-sessions.

Development

  • Create and activate a python virtualenv.
  • Install development dependencies in your virtualenv with pip install -e '.[dev]'
  • Install pre-commit hooks with pre-commit install
  • Run tests with coverage:
    • py.test --cov

TODO

  • Write better documentation.
    • Explain how it works (in summary)
    • Add more details to existing documentation.
  • Write more tests
  • Performance benchmark (and compare with Django's cached_db)

Contributions are welcome!

License

MIT

More Repositories

1

django-nextjs

Next.js integration for Django projects
Python
344
star
2

mattermost-rtl

Adds RTL support to Mattermost
Go
67
star
3

talks

Topics Presented in Our L&D Sessions
CSS
64
star
4

data-contests

Solutions of Quera Data Contests
Jupyter Notebook
50
star
5

git-ninjas

This repo is about our Practical Git course, and contains a list of users that successfully finished the course.
48
star
6

qbuild

A build system for Quera technology challenges
Perl
40
star
7

django-pwned

A collection of django password validators
Python
24
star
8

jquery-duration-picker

A simple library for picking time durations in javascript (uses jQuery and Semantic UI)
HTML
22
star
9

metabase

Docker Compose for Metabase with PostgreSQL as Application Database
19
star
10

mattermost-chat-ui

Customizes UI for better readability
Go
18
star
11

django-visit-count

Count visits using cache for Django models.
Python
15
star
12

quera-core-ui

Quera's component library based on Chakra-UI
TypeScript
12
star
13

dataanalysis_bootcamp_crawler

Web scraper implementations for a variety of websites.
HTML
9
star
14

ansible-github

Ansible module to download and install assets from Github releases page.
Python
9
star
15

mattermost-vazirmatn

Change Mattermost font to Vazirmatn
Go
7
star
16

qcalc

Python
5
star
17

qaes

An AES Cipher Encryption/Decryption Package
Python
5
star
18

recorder

Record screen easily
Python
5
star
19

docker-ssh

Docker images for setting up an SSH tunnel or sync files between two containers on different servers.
Shell
5
star
20

sql-judge-utils

Python
4
star
21

college-ml

3
star
22

dataanalysis_bootcamp_ML_sessions

Jupyter Notebook
3
star
23

qprogress

Quera Progress Bar - A decoupled progress bar to show the progress of your loops!
Python
3
star
24

sysbench

Shell
3
star
25

qinux

Qinux
Python
2
star
26

test-repository

1
star
27

qbuild-jupyter

Python
1
star
28

django-college-frontend

JavaScript
1
star
29

git-aliases

Python
1
star