tags:

views:

286

answers:

3

is it possible to allow only one concurrent login per user in django application? if yes, how do you approach?

A: 

I'm going to assume that you mean logged in at once, and not one "login" at the same time.

I've never written a Django application before. But one method I've used in other languages, is to store the session ID of the logged in user in their user row in the database.

For example, if you have a users table in your database, add a field "session_id" and then when the user logs in, set that to their current session_id. On every page load check to see if their current session matches the session_id in the users table. Remember whenever you regenerate their session_id in your application, you'll need to update the database so they don't get logged out.

Some people when a user logs in, just store all the users details into a session and never re-call the database on a new page load. So for some this "extra" SQL query might seem wrong. For me, I always do a new query on each page load to re-authenticate the user and make sure their account wasn't removed/suspended and to make sure their username/password combo is still the same. (What if someone from another location changed the password, or an administrator?)

William
+4  A: 

This question is mostly answered here (stackoverflow.com).

SapphireSun
A: 

You need to create some model that save session_key for each user And create middleware that checks session key in that model for each user - if it does not equal to request.session_key - than remove that session(=logout user, allowing only current to stay)

#models.py
class Visitor(model.model):
    user = models.OneToOneField(User)
    session_key = models.CharField(null=True, blank=True)

#and you need to setup signal catching from User model - so for each User Visitor is created

#middleware.py
class OnlyOneUserMiddleware(object):
    def process_request(self, request):
         cur_session_key = request.user.visitor.session_key
         if cur_session_key and cur_session_key != request.session.session_key:
             Session.objects.get(session_key=cur_session_key).delete()
         #the following can be optimized(do not save each time if value not changed)
         request.user.visitor.session_key = request.session.session_key
         request.user.visitor.save()
Pydev UA