Check LocalStorage regularly

Is there any way to always check a client local resource using angularjs? The reason I want to do this is because I installed JSON Web Token in local storage when the user logs in. In addition, I use

$rootScope.$on('$routeChangeStart', function() {});

to check the token. After the expiration of its validity, the user will be logged out. However, with this method, the user must make an API request so that the check is reinitialized. Is there a way to observe the token that is stored inside localStorage and as soon as it expires and then log out the user without the need for an API request?

+4
source share
2 answers

@IAMDranged:

       setInterval(function() {

            var token = $window.localStorage.getItem('token');
            self.parseJwt = function(token) {
                var base64Url = token.split('.')[1];
                var base64 = base64Url.replace('-', '+').replace('_', '/');
                return JSON.parse($window.atob(base64));
            }
            var expireTime = self.parseJwt(token);
            var timeStamp = Math.floor(Date.now() / 1000);
            var timeCheck = expireTime.exp - timeStamp;


            //Set to expire after 15 seconds
            if (timeCheck < 86385) {
                console.log('time expired');
            } else {
                console.log('time not expired');
            }


        }, 3000);
0

/ , , ? , , / localStorage, ( ), setTimeout , .

( , ), , ( cookie localStorage), , , 403 http error, - $httpInterceptor, , 403 ( , , ).

: ( ). , .

angular.module('...')
    .run(['$timeout', function ($timeout) {
        var _timeout;
        function deleteTokenTimeout() {
            if (_timeout) {
                _timeout.cancel();
            }
            _timeout = $timeout(function () {
                // remove the token
            }, new Date(localStorage.getItem('expiration')) - new Date());
        }

        deleteTokenTimeout();
    }]);
-1

Source: https://habr.com/ru/post/1664354/


All Articles