Angular session timeout and management [duplicate]
Asked Answered
H

3

44

Is there any way to manage user session using Angularjs?, I mean::

  • Session timeout - when system is idle.
  • Alerts when session is near to expire with option to resume session.
  • Redirect (or any other action) when trying to make a request if session has expired.

Could be Interceptors one good option to solve this problem? Can you provide an example?

Henkel answered 22/5, 2013 at 16:25 Comment(1)
@georgeawg This question is older tha referenced one which must be the duplicatedHenkel
M
58

Try ng-idle. It's simple component where you can set the timeout and warning time before the timeout is reached. Then you can query server for user logout or something similar.

myApp.config(function(IdleProvider, KeepaliveProvider) {
  IdleProvider.idle(900); // 15 min
  IdleProvider.timeout(60);
  KeepaliveProvider.interval(600); // heartbeat every 10 min
  KeepaliveProvider.http('/api/heartbeat'); // URL that makes sure session is alive
});

myApp.run(function($rootScope, Idle) {
  Idle.watch();
  $rootScope.$on('IdleStart', function() { /* Display modal warning or sth */ });
  $rootScope.$on('IdleTimeout', function() { /* Logout user */ });
});

In the above configuration, when user is idle for 900s (does not move mouse, press any key or button etc), warning is being displayed. It will then wait 60s and log out user (send request to a server that possibly destroys server session).

In order to make sure server session does not expire (even if everything user is doing is moving mouse) the Keepalive service will send a request to the server every 10 minutes. This time has to less than server session expiration time.

Checkout the demo.

Monagan answered 19/3, 2015 at 20:17 Comment(4)
+1 for giving a good explanation and using the current syntax - edited to add a call to Idle.watch() in the run() function as otherwise the timer won't start and the Idle events won't fire.Eleventh
@Boris, thank you. Your edit has been rejected so I have added it myself.Monagan
thanks for adding the edit. Any idea why it got rejected? it definitely didn't work for me without watch() and others seem to be having this problem too.Eleventh
Users that decide whether to accept or reject an edit often are not familiar with the technology/problem that is concerned. Therefore, they often reject edits that modify somehting in source with "trying to answer" reason. It's better to leave a comment for the OP in such cases that the answer/question needs to be improved.Monagan
A
5

Here are some implementations:

https://github.com/witoldsz/angular-http-auth

https://github.com/angular-app/angular-app/tree/master/client/src/common/security

Alumna answered 22/5, 2013 at 18:23 Comment(1)
Please don't just post links as answers.Deviant
M
1

I have been using ng-idle for some time now for below requirement.

Our requirement was when the user is idle for 60 mins. After 55 mins show pop up with the confirmation box saying do you want to continue your session or not(I have used sweet alert). If the user click on continue then reset the idle time else log out forcefully by calling broadcast method.

Configuration has to be done in app.js when the users log-in inside app.config like below

app.config(['KeepaliveProvider', 'IdleProvider', function (KeepaliveProvider, IdleProvider) {
IdleProvider.idle(TimeOut.firstAPiCall);--It will call Idle On method
IdleProvider.timeout(TimeOut.SessionTimeOut);--It will be called when the total time is (TimeOut.firstAPiCall +TimeOut.SessionTimeOut)
KeepaliveProvider.interval(TimeOut.interval);}]) --It will be called like a heart beat for mentioned timeout until the idle start has not occured.

Below is the code for showing pop-up

   $scope.$on('IdleStart', function () {   
    $scope.$broadcast('SessionIdleUpdate', 'IdleStart', TimeOut.FirstApicall);
    $rootScope.idleTimerSession = setTimeout(function () {
        console.log("pop up appeared on : " + new Date())
        $scope.timedout = SweetAlert.swal({
            title: "Alert",
            text: "Your session is about to expire in 5 minutes, Do you want to continue?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DDDDD",
            confirmButtonText: "CONTINUE",
            cancelButtonText: "No"
        }, function (isConfirm) {
            if (isConfirm) {
                clearTimeout(idleTimer);
            }
            else {
                console.log("pop up closed from confirm on  : " + new Date())
                $scope.$broadcast('SessionTimeOutLogOut', null);
                Idle.unwatch();
                $scope.started = false;
            }
        });

        //This check is to handle idle pop up if it appears and user doesnt perform any action it will simply logout.
        var idleTimer = setTimeout(function () {

            swal.close();            
            $scope.$broadcast('SessionTimeOutLogOut', null);
            Idle.unwatch();
            $scope.timedout = null;
        }, (TimeOut.sessionTimeOut) * 1000);
    }, (TimeOut.idleTimeOut - TimeOut.idleCheckDuration) * 1000);-- Time out is added to hold the pop up for that much duration . Because once the idle start is occured you wont be able to call the API 

});

Below is the code for handling idle end event:

  $scope.$on('IdleEnd', function () {
        $scope.$broadcast('SessionIdleUpdate', 'IdleEnd', 0));    
    clearTimeout($rootScope.idleTimerSession);
    closeModals();
});

Below is the code for Time Out it will be called after ---(TimeOut.firstAPiCall +TimeOut.SessionTimeOut)

  $scope.$on('IdleTimeout', function (forceLogout) {


        swal.close();
        $scope.$broadcast('SessionTimeOutLogOut', null);
        Idle.unwatch();

});
Mapes answered 24/4, 2017 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.