Reputation: 4760
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?
Upvotes: 1
Views: 2933
Reputation: 5597
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
Upvotes: 1