Restrict multiple login for same user.

Can anyone help with implementing a middleware to restrict the user for multiple login on different browsers.

Are you talking about preventing two people from being logged in at the same time on different machines? What about two different browsers on the same machine? (e.g. Chrome & Firefox)

Are you looking to prevent the second person from logging in? Or are you looking to have the second person log in and disconnect the first login?

How are you going to tell when someone disconnects but doesn’t log off? (They just close their browser, or their network connection is lost, or any of a number of other situations?)

I’m not saying it can’t be done - just be prepared to handle all the problems associated with doing this. (In general, this is a really bad idea.)

I mean i want to restrict a user for login multiple times.

If a user1 is login in machine1 and the same user1 is login again on machine2 then in that case i want to logout the user1 from the 1st machine.

In that case user1 should only have one session that i want to handle in django using middleware.

It’s super easy. U just need to remove last known user session from Session model.

Use a Model to store user session keys.

  1. whenever user trying to login you need to fetch last stored session key from database.
  2. Based on last known session key remove session from Session Table with matching session key.
  3. Finally login user and then store the new session key to your database.

It working for me. It’s easy to implement.

1 Like

Django Session provides three fields expiry, session_data and session_key

And session is different on every login request

Then how can i fetch the last Session that user is login

You just need to store session key in separate Model. The model will store session key everytime a user Login.
Ex
class Visitor(models.Model):
user = models.OnetoOne(User)
sessionKey = models.charfield(max_lenghth=)

def loginView(request):

 # validate user credentials with authentication 
 # if valid fetch session key from visitor model
 # delete session with sessionkey from visitor model
#login user
# store new session key to visitor

Note: if user logs out manually. Then session is removed from session backend. Just make sure session key exists in session backend.

2 Likes

Please don’t tag individuals requesting assistance. People answer questions here based on their time, knowledge and energy. (As for me, I’m not sure I can help you here, I don’t use or work with DRF.)

Hello! tayfunka I acknowledge your mail. I am ready to help you. Let me know how you want me to connect.

I am not from DRF family. But this is how I handled it for my use case and it works.

# Hello Tayfunka

""" 
I am gonna explain how this works. in order to restrict multiple logins or to Allow only one Login,
you should have a very basic idea on how Django session works.

Whenever you Login() a user, Django Creates a session for that User.
Now this Session Holds Details of Authentication for a User/ClientBrowser.
  
if I delete the Session Record from Database the Authentication Details are gone. Therefore it requires user to login again to gain access.
Which means if we are able to Delete any previous sessions from Database whenever User is trying to Login from a new device/Brower,
The last Login Device/Browser is no longer treated as Authenticated for that user account.

"""

# models.py --------------------------------------------------------------------------

class Visitor(models.Model):
    TargetUser = models.OneToOneField(MyCustomUserModel, on_delete=models.CASCADE)
    SessionKey = models.CharField(max_length=50, null=True, blank=True)

"""
    -> I have my Custom User Model. if you don't have one use,
       from django.contrib.auth.models import User in place of MyCustomUserModel
    
    -> Creating new Custom User Model may not be possible until you Empty the Database.
       so better to use django default User model.
    
    -> make migrations and migrate
"""

# end of models.py ------------------------------------------------------------------



# admin.py ---------------------------------------------------------
class SessionAdmin(admin.ModelAdmin):
    list_display = ['session_key', 'expire_date', 'session_data']

"""
    -> This step is optional.
       This simply allows you to play with session backend.

"""
# end of admin.py -------------------------------------------------



# view.py ---------------------------------------------------------
from django.contrib.auth import authenticate, login
from django.contrib.sessions.models import Session

# view which logins user with passed credentials through HTML form
def user_authentication(request):
    
    # checking for user account in Database,
    # returns User object if credentials match, else None
    user_credentials_validation = authenticate(username="paste_userinput", password="paste_userinput")

    if user_credentials_validation:
        login(request, user_credentials_validation) # logging-in User


        # Important! Delete previous session from Django Session Backend
        # Finally Store newly generated session-key into Visitor Model
        if hasattr(request.user, 'visitor'):

            if Session.objects.filter(session_key=request.user.visitor.SessionKey).exists():
                # Discarding previous session
                old_session = Session.objects.get(session_key=request.user.visitor.SessionKey)
                old_session.delete()

            # Discard Visitor object
            request.user.visitor.delete()

        new_session_key = request.session.session_key

        query = Visitor(TargetUser=request.user, SessionKey=new_session_key)
        query.save()
        
        return "redirect to Homepage as user succesfully logged in"
    else:
        return "You know what to do when Credentials are wrong"
        

# end of view.py -------------------------------------------------------

# You can contact me whyemail.mohankrishna@gmail.com

Let me know if you run into issues, sir. Also, I am looking for an Opportunity to Learn and earn.