1

I want to be able to automatically log users out when they leave my Django site. Not just when they close the browser, but whenever they navigate away to a different site. Is this possible?

I'm displaying sensitive data to the user, and if they were to go to a new URL, and then hit the back button, I don't want the sensitive data displayed. I want them to be forced to log back in.

Is this possible? Or is this something I would have to do on the front end?

deef
  • 4,410
  • 2
  • 17
  • 21

1 Answers1

1

Check out this answer on how to detect when a visitor moves away from the page.

Documentation: Page Visibility API

Logout user via Ajax:

from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth import logout


class LogoutView(View):
"""
The logout view class. This will log the user out and invalidate the session.
"""

    def post(self, *args, **kwargs):
        logout(self.request)
        return JsonResponse({'success': True}, **kwargs)

If you only want to 'logout' user if they leave the page, try hooking into onbeforeunload event.

$(window).unload(function () {
    /* login for ajax call goes here */
});

WindowEventHandlers.onbeforeunload

mishbah
  • 5,487
  • 5
  • 25
  • 35
  • thanks for the thorough answer. going to accept because this is technically an answer for what I asked, but this ended up being a complex issue due to browser caching. i ended up having to configure django to set the headers so the browser didn't cache the page: http://stackoverflow.com/questions/2095520/fighting-client-side-caching-in-django – deef Feb 27 '15 at 22:27
  • The proposed solution is fragile because the `unload` event is triggered in many situations, including when a user hits the back button on your current site without having navigated away from the page, or even when the page is reloaded. With the proposed solution in place, JavaScript calls that reload a page may unexpectedly log out a user. – Joshua Pokotilow May 19 '17 at 15:58