Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

theUnforgiven's avatar

Session, Logout/Login question, countdown to log back in

Hi all,

Hope everyone is safe from the virus & managing to keep busy.

I want to have a script ideally in VueJS that checks the current session (currently set to 45 mins in the env) that alerts the user when at 44 mins, with a countdown, then two buttons to stay logged in, or logout.

Obviously stay logged in will increase their session by another 45 mins., logout, well logs out and ends session.

So question is how would achieve this?

0 likes
16 replies
bobbybouwmann's avatar

Well, you already know the session time right? This is et to two hours by default. You can start a countdown in javascript until you hit this 45 minutes.

After the user presses the button you simply do a ping request to the backend, which will refresh the session for you. After that, you restart the countdown.

You can do this with setTimeout in JS.

theUnforgiven's avatar

@bobbybouwmann - Thanks dude, I'm using Vue so just thinking (help appreciated) on how I can get this to run. I presume just pass the current session to a Vue component and then within that have the timeout and button to go the action(s)?

bobbybouwmann's avatar

You don't actually need to have the session in the frontend. You only need to know how long a session will stay active in your frontend. By default, this is 2 hours.

var timeout;

function refresh() {
	clearTimeout(timeout)
  
	timeout = setTimeout(() => {
		// Display countdown after 1h and 15 minutes
	}, 75 * 1000)
};

refresh();

// Move this logic to your button action
document.addEventListener('click', refresh);
1 like
theUnforgiven's avatar

Yes, that's kinda what I thought so just been playing with a new component which I should be able to add to the main layout file in order to trigger it.

<template>
	<div>
		Session: {{ timerCount }}
	</div>
</template>

<script>
    export default {
        data() {
            return {
                timerCount: 30
            }
        },
        watch: {
            timerCount: {
                handler(value) {
                    if (value > 0) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 1000);
                    }
                    if(value == 1) {
                    	swal({
                            title: 'Your session is about to expire',
                            text: 'You can click continue to keep your session alive for another 45 mins',
                            icon: 'error',
                            button: 'Continue',
                        });
                    }
                },
                immediate: true
            }
        }
    }

</script>
theUnforgiven's avatar

Ok, so got the Vue component working and Sweet Alert showing, How do I update the session for that user, if they click "leave signed in" button.

I've got a route setup and an axios post request setup. Just unsure on how to reset their session

theUnforgiven's avatar

Not perfect by any means, but does the job:

<template>
	
</template>

<script>
    export default {
        data() {
            return {
                timerCount: 45
            }
        },
        watch: {
            timerCount: {
                handler(value) {
                    if (value > 0) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 45 * 1300);
                    }
                    if(value == 5) {
                    	swal({
                            title: 'Your session is about to expire!',
                            text: 'Your session will expire in 5 minutes, you can carry on or end your session.',
                            icon: 'error',
                            buttons: {
                            	cancel: {
							    text: "No, logout!",
							    value: null,
							    visible: true,
							    className: "",
							    closeModal: true,
							  },
							  confirm: {
							    text: "Keep me signed in.",
							    value: true,
							    visible: true,
							    className: "",
							    closeModal: true
							  }
                            }
                        }).then(okay => {
                            if(okay) {
                                axios.post('session');
                                this.timerCount = '';
                                this.timerCount = 45;
                            } else {
                                console.log('Logout');
                                axios.post('session/logout');
                                window.location = '/login';
                            }
                        	
                    	});
                   	}
                },
                immediate: true
            }
        }
    }

</script>
theUnforgiven's avatar

I have the above code, which seems to work, but on every page it's reset to 45 mins...

Anyone have any better suggestions on this.

Snapey's avatar

Thats the way it works. The session is reset on every request.

The session is stale and invalid when you contact the server and it has been longer than the session duration since your last request.

This is why Bobby said

you simply do a ping request to the backend, which will refresh the session for you

Better to hide the timer until it reaches the last few minutes. Likely, the tab is buried or the user has gone away, so they won't see your reminder anyway.

theUnforgiven's avatar

I do ping the backend like so:

$user = User::where('id', user()->id)->first();
	    $session = \DB::table('sessions')
	        ->select('last_activity')
	        ->where('user_id', $user->id)
	        ->first();
	    if($session->last_activity < now()->addMinutes(45)) {
	        $session->last_activity = \Carbon\Carbon::now()->getTimestamp();
	        $session->update();
	        Auth::login($user);
	    } else {
	        $session->delete();
	    }
	    return $session;

its more the timer i need sorting i think to show at 43 mins from the session, been made

Snapey's avatar

everytime you hit the back-end (for whatever reason) reset the timer back to 45 minutes, and of course when the page is reloaded.

I don't understand why you are showing server code. You cannot do anything at the server to get the session duration because as I said, it will always be reset to 45 minutes in response to a request.

The only way you can push anything different from the server is to have a websocket based presence channel and a backend job that checks for users approaching session end and sends them a notification.

theUnforgiven's avatar

Ah, I see now.

So I just need an endpoint to get the session from, then have a timeout function within the Vue component to calculate when it should it that end point, is that my understanding?

I also have a sweet alert within the code to show to the user whether to stay logged in or log out.

bobbybouwmann's avatar

Yeah, that's it. So you show it after 45 minutes, but if you refresh the page the session is refreshed and the counter starts from scratch since the javascript restarts from scratch as well.

Snapey's avatar

Sorry to complicate things, but this breaks when the user has two tabs open. One they are working in, with 45 minutes of session left, and another tab which is saying that their session is/has expired. The timers in your pages are not linked in any way so one can be counting down and the other reset with each interaction.

theUnforgiven's avatar

No, it seems like the frontend is working as expected with the countdown but the two don't marry up, so having to re-think how to do it.

Please or to participate in this conversation.