简体   繁体   中英

Django auto logout and page redirection

I have an application whose backend is written using django and python. I want to implement auto logout feature in my applcation. For this , I used following django built-in features :

SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 40
SESSION_SAVE_EVERY_REQUEST = True

I have also used LOGOUT_REDIRECT_URL to redirect the page after logout.

But this doesn't help.

  1. After 40 seconds, logout happens but it is not visible in frontend, login page comes only if the user refreshes the tab or makes any request in the tab.

  2. If I close the browser and open it again , the home page appears with no data as the data are user specific . and if refresh is done of tab is done , the tab is redirected to login page.

I want to achieve 2 scenarios:

  1. If the auto log happens the user should be automatically redirected to login page.

  2. If the user closes the browser window and opens it again then user should be displayed the login page of the application.

Any suggestions on how to achieve these scenarios ?

Any help would be appreciated. Thank you.

  1. After 40 seconds, logout happens but it is not visible in frontend, login page comes only if the user refreshes the tab or makes any request in the tab.

Yes, that is how it works. Your browser won't do anything automatically. You'll have to write necessary Javascript code to monitor the age of the session cookie. And when it expires, your Javascript code will load the login page.

  1. If I close the browser and open it again , the home page appears with no data as the data are user specific . and if refresh is done of tab is done , the tab is redirected to login page.

That doesn't sound right. If you re-open your browser and visit your app's homepage, it should take you to login page. But are you trying to restore your browser's session after re-opening it ( Ctrl + Shift + T )?

Auto logout.

Add the below two values in settings.py file:

1. SESSION_COOKIE_AGE = TIME #//change expired session

Example: SESSION_COOKIE_AGE = 240*60   #//four hours  or your time
  1. SESSION_SAVE_EVERY_REQUEST = True

############################################################

And then add the below jquery code in your base.html file:

    function autorefresh() {

            // auto refresh page after 1 second

            setInterval('refreshPage()', 6*1000);

    }


    function refreshPage() {

            $.ajax({

            url: window.location.pathname,

            success: function(data) {

                window.location = "."

            // $('#console').html(data);

            }

        });

    }

</script>

<script>autorefresh()</script>

<div id="console" ></div>

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