Don't allow concurrent login from a user

41 views
Skip to first unread message

Saurabh Pandey

unread,
Mar 14, 2021, 10:02:04 AM3/14/21
to Django users
Hi,

Need suggestion on how i can implement the below 

a user U1 is logged into my website.
he opens incognito mode and again tries to login, expecatation is that his login will be denied saying you are already logged in.

i tried below but seems not working. ( on stack overflow there are answers but it's so complex) 

```
def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if request.user.is_authenticated: msg="User already logged in, multiple log in not allowed " return redirect("/") if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg})
```

Thanks 

Kunal Solanke

unread,
Mar 14, 2021, 4:13:20 PM3/14/21
to Django users
I am intrigued by the need to keep users logged in only one session.No one keeps track of when I logged into an app and from which tab and all, this will probably result in bad ux, but anyways, 

user.is_authenticated() won't work, it keeps track of session of users.

What you can do is either implement a jwt flow by which you can keep track if there is a active jwt token, you can stop person from logging in, or if you want to stck with same default auth by djnago ,
then you can add some fileds like is_logged in user model and when the user tries to login you can check if curr_time-last_login>session age and is_logged in is true,then users won't be allowed to login again. 

You can set is logged in false, when user hits logout. 
Both ways are tricky. 




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8ccc8131-4a35-450d-9f6c-8d769a0b890cn%40googlegroups.com.

Kunal Solanke

unread,
Mar 14, 2021, 4:16:29 PM3/14/21
to Django users
Reply all
Reply to author
Forward
0 new messages