Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Django user is still logged in from the client side only?

Security is not an issue here.

I need to display 'You are logged in as username' on the page, but don't want to remove the view from the cache just for this so I'm hoping to be able to do it in javascript.

I don't want to make anything critical with this process, just check if the cookie is still valid, and if it is, display the welcome message, overwise, display the login link.

The whole point is to not hit the database and spare the server, as we got 120000 users a day on this single machine, so I need:

  • the name of the django.contrib.auth cookie so I can read it;
  • the data I'm supposed to read from it to decide the user is still logged in
  • a way to extract the username from it

If I can't find a way to do this, I will fall back to create an authentification backend that set an additional cookie at sign in and deleting it at when logging out.

like image 619
e-satis Avatar asked Aug 08 '11 14:08

e-satis


People also ask

How do you check if the user is logged in or not in Django?

Check the Logged in User in Views in Django We can use request. user. is_authenticated to check if the user is logged in or not. If the user is logged in, it will return True .


1 Answers

Have code like the following in your template.

{% block top %}<script async="async" defer="defer" type="text/javascript" src="{% static 'users/js/geo.js' %}"

{% if user.is_authenticated %} data-authenticated="true" {% endif %}

></script
>{% endblock %}

And check if your authenticated with code like:

unsafe_authenticated = 'true' === document.currentScript.dataset.authenticated;
like image 118
Molossus Spondee Avatar answered Oct 12 '22 12:10

Molossus Spondee