Auto logout after certain amount of inactivity

747 0 0 0

Last Updated : 2024-07-16 15:17:41

If you wish you application to auto logout after a certain amount of time the user is inactive on it, here is a sample code that will work in laravel.

<script src="{{asset('js')}}/jquery.js"></script>

@if (Route::getFacadeRoot()->current()->uri() != 'login')
<script>
$("document").ready(function(){
console.log('Wonderful');

// const timeout = {{config('session.lifetime')*60*1000}}; // 900000 ms = 15 minutes
// const timeout = 30000; // 900000 ms = 15 minutes
const timeout = "{{config('session.lifetime')*60*1000+2}}"; // 900000 ms = 15 minutes
var url="{{url('/sessionExpired')}}";
var idleTimer = null;
$('*').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTimer);

idleTimer = setTimeout(function () {
//alert('logoutNOW');
//document.getElementById('logout-form').submit();
location.href= url;
}, timeout);
});
$("body").trigger("mousemove");

});
</script>
@endif

//Reference
https://laracasts.com/discuss/channels/laravel/auto-logout-if-no-activity-in-given-time

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .