Reputation: 109
I used built-in login logout functionality by Django using Django authentication, this is the following url pattern for logging in urls.py:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('',views.home),
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/', include('django.contrib.auth.urls')),
path('dashboard/', include('dashboard.urls')),
]
And i added following in my setting.py settings.py:
LOGIN_REDIRECT_URL = 'dashboard:home'
LOGOUT_REDIRECT_URL = 'dashboard:home'
Now how do I check whether user closed his browser and he should be logged out? PS:I made my own logging in and sign-up HTML pages and made my own customuser derived from AbstractUser
Upvotes: 2
Views: 7493
Reputation: 89
To logout the session whenever you close the browser
you need to input the following lines in your setting.py
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
Upvotes: 1
Reputation: 31404
Just set the SESSION_EXPIRE_AT_BROWSER_CLOSE
setting to true, so that Django's session cookies are only valid for the length of the browser session.
If
SESSION_EXPIRE_AT_BROWSER_CLOSE
is set to True, Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.
Upvotes: 6
Reputation: 2159
You can listen for the window or tab close event like this. This approach needs jQuery and JavaScript.
$(document).ready(function(){
$(window).on("beforeunload", function(e) {
$.ajax({
url: logout_url,
method: 'GET',
})
});
});
Upvotes: 3