0

아래 코드는 내 service.js. 내 토큰이 만료되고 권한이없는 경우 로그 아웃하는 방법은 무엇입니까? 로컬 저장소를 설정해야합니까? 누군가가 내가 사전에 for.Thanks을 찾고 결과를 달성 할 수있는 방법 저를 도와하거나 제안 할 수있는 것은토큰이 만료되고 권한이없는 경우 로그 아웃하는 방법은 무엇입니까?

'use strict'; 

angular.module('Authentication') 

.factory('AuthenticationService', ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout', 
function (Base64, $http, $cookieStore, $rootScope, $timeout) { 
     var service = {}; 

     service.Login = function (callback) { 
      //authenticate data http 
      $http.post('http://117d8128.ngrok.io/api/authenticate') 
       .then(function (response) { 
        callback(response); 
       }); 

     }; 

     service.SetCredentials = function (username, password) { 
      var authdata = Base64.encode(username + ':' + password); 
      $rootScope.globals = { 
       currentUser: { 
        username: username, 
        authdata: authdata 
       } 
      }; 
      $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; 
      $cookieStore.put('globals', $rootScope.globals); 
     }; 

     service.ClearCredentials = function() { 
      $rootScope.globals = {}; 
      $cookieStore.remove('globals'); 
      $http.defaults.headers.common.Authorization = 'Basic '; 
     }; 

     return service; 


}]) 

.factory('TokenService', ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout', 
function (Base64, $http, $cookieStore, $rootScope, $timeout) { 
     var service = {}; 

     service.SetToken = function (token) { 

      $http.defaults.headers.common['auth-token'] = token; 
      $cookieStore.put('globals', $rootScope.globals); 
     }; 
     return service; 
}]) 

.factory('Base64', function() { 


    var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/='; 

    return { 
     encode: function (input) { 
      var output = ""; 
      var chr1, chr2, chr3 = ""; 
      var enc1, enc2, enc3, enc4 = ""; 
      var i = 0; 

      do { 
       chr1 = input.charCodeAt(i++); 
       chr2 = input.charCodeAt(i++); 
       chr3 = input.charCodeAt(i++); 

       enc1 = chr1 >> 2; 
       enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 
       enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 
       enc4 = chr3 & 63; 

       if (isNaN(chr2)) { 
        enc3 = enc4 = 64; 
       } else if (isNaN(chr3)) { 
        enc4 = 64; 
       } 

       output = output + 
        keyStr.charAt(enc1) + 
        keyStr.charAt(enc2) + 
        keyStr.charAt(enc3) + 
        keyStr.charAt(enc4); 
       chr1 = chr2 = chr3 = ""; 
       enc1 = enc2 = enc3 = enc4 = ""; 
      } while (i < input.length); 

      return output; 
     }, 

     decode: function (input) { 
      var output = ""; 
      var chr1, chr2, chr3 = ""; 
      var enc1, enc2, enc3, enc4 = ""; 
      var i = 0; 

      // remove all characters that are not A-Z, a-z, 0-9, +, /, or = 
      var base64test = /[^A-Za-z0-9\+\/\=]/g; 
      if (base64test.exec(input)) { 
       window.alert("There were invalid base64 characters in the input text.\n" + 
        "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + 
        "Expect errors in decoding."); 
      } 
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); 

      do { 
       enc1 = keyStr.indexOf(input.charAt(i++)); 
       enc2 = keyStr.indexOf(input.charAt(i++)); 
       enc3 = keyStr.indexOf(input.charAt(i++)); 
       enc4 = keyStr.indexOf(input.charAt(i++)); 

       chr1 = (enc1 << 2) | (enc2 >> 4); 
       chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); 
       chr3 = ((enc3 & 3) << 6) | enc4; 

       output = output + String.fromCharCode(chr1); 

       if (enc3 != 64) { 
        output = output + String.fromCharCode(chr2); 
       } 
       if (enc4 != 64) { 
        output = output + String.fromCharCode(chr3); 
       } 

       chr1 = chr2 = chr3 = ""; 
       enc1 = enc2 = enc3 = enc4 = ""; 

      } while (i < input.length); 

      return output; 
     } 
    }; 

}); 

이것은 아래 내 집 내 인증

에 대한 controller.js
'use strict'; 

angular.module('Authentication') 
.controller('LoginController', ['$scope', '$rootScope', '$location', 
'AuthenticationService', 'TokenService', '$http', 
function ($scope, $rootScope, 
$location,AuthenticationService,TokenService,$http) { 
    // login status 
    AuthenticationService.ClearCredentials(); 
    $scope.login = function() { 
     $scope.dataLoading = true; 
     AuthenticationService.SetCredentials($scope.username, $scope.password); 
     AuthenticationService.Login(function (response) { 
      if (response.data.success) { 

       TokenService.SetToken(response.data.token); 
       $http.post('http://117d8128.ngrok.io/api/users') 
       .then(function(response){ 
        console.log(response); 
        $location.path('/'); 
       }); 


      } else { 
       $scope.error = response.message; 
       $scope.dataLoading = false; 
      } 
     }); 
    }; 
}]); 

입니다 제어 장치. 여기 토큰이 unauth 일 때 로그 아웃해야합니다. 그러나 로그 아웃하지 않습니다. 누군가 나를 도와 줄 수 있습니까?

'use strict'; 

    angular.module('Home') 

    .controller('HomeController', 
['$scope', 
function ($scope,$http) { 
    $http.post('http://117d8128.ngrok.io/api/users') 
       .then(function(response){ 
        console.log(response); 
        $location.path('/'); 
       }); 

}]); 

메인 컨트롤러

'use strict'; 

    // modules 
    angular.module('Authentication', []); 
    angular.module('Home', []); 

angular.module('HttpAuth', [ 
'Authentication', 
'Home', 
'ngRoute', 
'ngCookies' 
]) 

.config(['$routeProvider', function ($routeProvider) { 

$routeProvider 
    .when('/login', { 
     controller: 'LoginController', 
     templateUrl: 'modules/authentication/views/login.html' 
    }) 

    .when('/', { 
     controller: 'HomeController', 
     templateUrl: 'modules/home/views/home.html' 
    }) 

    .otherwise({ redirectTo: '/login' }); 
}]) 

.run(['$rootScope', '$location', '$cookieStore', '$http', 
function ($rootScope, $location, $cookieStore, $http) { 
    // keep user logged in after page refreshed 
    $rootScope.globals = $cookieStore.get('globals') || {}; 
    if ($rootScope.globals.currentUser) { 
     $http.defaults.headers.common['Authorization'] = 'Basic ' + 
$rootScope.globals.currentUser.authdata; 
    } 

    $rootScope.$on('$locationChangeStart', function (event, next, current) { 
     // redirect to login page if not logged in 
     if ($location.path() !== '/login' && !$rootScope.globals.currentUser) { 
      $location.path('/login'); 
     } 
    }); 
}]); 

답변

0

사용자 일단 성공적으로 당신은 로컬 스토리지에 토큰을 저장할 수에 기록됩니다. 모든에 메인 컨트롤러에서

//Storing token in local Storage 
    service.setToken(token){ 
    $window.localStorage.setItem('token', token); 
} 



, 당신은 토큰이 만료/존재 여부를 확인할 수 요청합니다.



//Getting token from local Storage 
service.getToken(token){ 
return $window.localStorage.getItem(token); 
} 
if(service.getToken()){ 
    //Proceed in the application 
}else{ 
//logout & redirect to homepage/login page 
} 
그것의 JIST, 당신은 당신의 요구 사항에 따라 위의 코드를 수정할 수 있습니다.

+0

고마워요, mayank.Will 시도해보십시오 :) – Manoj

+0

확실한, 더 이상의 의심에 나를 핑 해달라고 느낀다 :) –

+0

mayank 나는 로컬 스토리지 대신 쿠키 스토리지를 사용했다. $ cookieStore.get ('전역')을 사용하고 있습니다. 이게 효과가 있니? 위에서 편집 한 코드에서 주 컨트롤러를 확인하십시오. 감사합니다. – Manoj

관련 문제