Thursday, February 25, 2021

Re: Log out all sessions for current user logged in

On Wed, Feb 17, 2021 at 08:23:08AM +0530, Salima Begum wrote:
> Logout all sessions based on current user id and clear django sessions
> table based on user id. It is logging off all sessions.
>
> ```
> # Logout all devices in account security page.
> def logoff_all(request):
> try:
>
> # Filtering all session objects.
> session_query = Session.objects.all()
>
> # Iterating session_query and fetching session key.
> for s in session_query:
> # Decoding session key and getting id from that.
> var_id = s.get_decoded().get('id')
> # Converting string to int data type.
> var_id_user = int(var_id)
> # Id from decode and logged in session id is same then
> # delete that session key from Session table from database.
> if var_id_user == request.session.get('id'):
> s.delete()
> messages.success(request, "All sessions are logged off
> successfully.")
> return HttpResponseRedirect("/home")
> except Exception as e:
> logging.error(e)
> print(e)
> return HttpResponseRedirect("/home")
> ```

I would call s.flush() instead of s.delete(). That's what Django's
normal logout function does[1].

[1] https://github.com/django/django/blob/a948d9df394aafded78d72b1daa785a0abfeab48/django/contrib/auth/__init__.py#L149

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20210225232524.GG19963%40fattuba.com.

No comments:

Post a Comment