I am a really new bird to python and using Django rest framework. I have followed the tutorial "http://www.django-rest-framework.org/tutorial/quickstart" and created a login logout page for admin. I wanted to track the session time or basically for how long the user has been logged in, I tried doing the same by following many tutorials like these 'https://github.com/GetBlimp/django-rest-framework-jwt' but I think I'm deviating from what I want, please suggest any tutorial or any help. Thanks
1
votes
Maybe just use user.last_login
- Alexandr Tatarinov
last_login will give when the user logged in but when he logged out is also needed.
- rosh
Ah, yes, missed that. So maybe just add another field for last_logout and populate it the same way as Django does for last_login? But the question is what is logout. If user clears cookies he is technically logged out, but you cannot track this
- Alexandr Tatarinov
didn't know it has last_logout too, I researched a bit but didn't find the same, can you provide some link for the same, it would be a great help.
- rosh
Use django sessions: docs.djangoproject.com/en/2.0/topics/http/sessions. Have a go, put some attempted code up and then let's look again
- HenryM
1 Answers
1
votes
It looks to me that this is not stored in the Sessions, but nothing prevents us from storing it ourselves.
We can for example construct a model UserSession:
# models.py
from django.conf import settings
from django.db import models
from django.contrib.sessions.models import Session
class UserSession(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
session = models.OneToOneField(Session, on_delete=models.CASCADE)
session_start = models.DateTimeField(auto_now_add=True)Of course now we still need to ensure that such object is constructed, but we can create a hook for the login procedure:
from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver
@receiver(user_logged_in)
def register_session(sender, user, request, **kwargs):
# save current session
request.session.save()
# create a link from the user to the current session (for later usage)
UserSession.objects.get_or_create(
user=user,
session=Session.objects.get(pk=request.session.session_key)
)We can then obtain the time the session started with:
from datetime import datetime
def some_view(request):
try:
session_started = request.session.usersession.session_start
except UserSession.DoesNotExist:
# ...
# handle the case when the UserSession is not present
pass
else:
session_duration = datetime.now() - session_started
# ...
pass