简体   繁体   中英

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.

The sessionid cookie exists and has an expiry date. You could check to see if that is still valid which would suggest they are logged it. You can't get the username this way though, you'll have to add a custom cookie.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM