2016-06-13 11 views
0

私は新生児です。ユーザーが認証されているかどうかを確認するAuthenticationServiceの作成方法を知りたいと思います。私はそれらを見ることができるようにユーザを認証させたいルートを持っており、認証されていなければログインページにリダイレクトされます。トークンベースの認証にはsatellizerを使用しています。提案されているよう角度認証サービス

私はapp.jsを変更した

angular.module('coop.controllers', []) 

.controller('FrontPageController', function($scope, ArticleService, $state) { 
    ArticleService.all().then(function(data){ 
    $scope.articles = data; 
    $scope.like = function(article){ 
     article.like = article.like == 0 ? 1 : 0; 
     ArticleService.like(article.id, article.like) 
    }; 
    }) 
}) 

.controller('ArticleController', function($scope, ArticleService, $stateParams, $ionicSlideBoxDelegate, $auth) { 
    ArticleService.get($stateParams.id).then(function(response) { 
    $scope.article = response; 
    $scope.commentsCount = response.comments.length; 
    $scope.articleText = response.text; 

    $scope.like = function(){ 
     $scope.article.like = $scope.article.like == 0 ? 1 : 0; 
     ArticleService.like($scope.article.id, $scope.article.like) 
    }; 

    $ionicSlideBoxDelegate.update(); 
    }) 

}) 

.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) { 
    $scope.loginData = {} 
    $scope.loginError = false; 
    $scope.loginErrorText; 

    $scope.login = function() { 
     var credentials = { 
      email: $scope.loginData.email, 
      password: $scope.loginData.password 
     } 

     $auth.login(credentials).then(function(response) { 
      var token = JSON.stringify(); 
      localStorage.setItem('token', response.data.token); 

      $ionicHistory.nextViewOptions({ 
       disableBack: true 
      }); 

      $state.go('main.front'); 
     }, function(){ 
      $scope.loginError = true; 
      $scope.loginErrorText = error.data.error; 
     }); 
    } 
}); 

更新コード:

は、これは私のapp.js

angular.module('coop', ['ionic', 'coop.controllers', 'coop.services', 'satellizer']) 

.constant('ApiEndpoint', { 
    url: 'http://coop.app/api' 
}) 

.run(function($ionicPlatform, $rootScope, $auth, $state, $location) { 

    // Check for login status when changing page URL 
    $rootScope.$on('$routeChangeStart', function (event, next) { 
     var currentRoute = next.$$route; 

     if (!currentRoute || currentRoute.requiresAuth && !AuthenticationService.authenticated) { 
     $location.path('/auth'); 
     } 
     else if (!currentRoute || !currentRoute.requiresAuth && AuthenticationService.authenticated) { 
     $location.path('/front'); 
     } 
    }); 

    $rootScope.logout = function() { 

     $auth.logout().then(function() { 

      // Remove the authenticated user from local storage 
      localStorage.removeItem('user'); 

      // Remove the current user info from rootscope 
      $rootScope.currentUser = null; 
      $state.go('main.auth'); 
     }); 
    } 

    $rootScope.token = localStorage.getItem('token'); 

    $ionicPlatform.ready(function() { 
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard 
    // for form inputs) 
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) { 
     cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
     cordova.plugins.Keyboard.disableScroll(true); 

    } 
    if (window.StatusBar) { 
     // org.apache.cordova.statusbar required 
     // StatusBar.styleDefault(); 
     StatusBar.show(); 
     StatusBar.overlaysWebView(false); 
     StatusBar.styleLightContent(); 
     StatusBar.backgroundColorByHexString("#2a2e34"); 
    } 
    }); 
}) 

.config(function($stateProvider, $urlRouterProvider, $authProvider, ApiEndpoint) { 

    $authProvider.loginUrl = ApiEndpoint.url + '/authenticate'; 

    $stateProvider 
    .state('main', { 
    url: '/main', 
    abstract: true, 
    templateUrl: 'templates/main.html', 
    requiresAuth: true 
    }) 

    .state('main.auth', { 
    url: '/auth', 
    views: { 
     'content': { 
     templateUrl: 'templates/login.html', 
     controller: 'AuthController', 
     requiresAuth: false 
     } 
    } 
    }) 

    .state('main.front', { 
    url: '/front', 
    views: { 
     'content': { 
     templateUrl: 'templates/main-front.html', 
     controller: 'FrontPageController', 
     requiresAuth: true 
     } 
    } 
    }) 

    .state('main.article', { 
    url: '/article/{id}', 
    views: { 
     'content': { 
     templateUrl: 'templates/main-article.html', 
     controller: 'ArticleController', 
     requiresAuth: true 
     } 
    } 
    }); 

    // if none of the above states are matched, use this as the fallback 
    $urlRouterProvider.otherwise('/main/front'); 
}); 

そして、私のコントローラである

// Check for login status when changing page URL 
    $rootScope.$on('$routeChangeStart', function (event, next) { 
    var currentRoute = next.$$route; 

    if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) { 
     $location.path('/main/login'); 
    } 
    else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) { 
     $location.path('/main/front'); 
    } 
    }); 

そしてユーザーを削除してのlocalStorageからトークンにログアウトコントローラを追加したが、私はまだログインページにリダイレクトされていない午前:

私のコントローラを:

.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) { 
    $scope.loginData = {} 
    $scope.loginError = false; 
    $scope.loginErrorText; 

    $scope.login = function() { 
    var credentials = { 
     email: $scope.loginData.email, 
     password: $scope.loginData.password 
    } 

    $auth.login(credentials).then(function(response) { 
     var token = JSON.stringify(); 
     localStorage.setItem('token', response.data.token); 

     $ionicHistory.nextViewOptions({ 
      disableBack: true 
     }); 

     $state.go('main.front'); 
    }, function(){ 
     $scope.loginError = true; 
     $scope.loginErrorText = error.data.error; 
    }); 
    } 

    $scope.logout = function() { 
    $auth.logout().then(function() { 
     // Remove the authenticated user from local storage 
     localStorage.removeItem('user'); 
     localStorage.removeItem('token'); 

     // Remove the current user info from rootscope 
     $rootScope.currentUser = null; 
     $state.go('main.login'); 
    }); 
    } 
}); 

答えて

1

あなたがsatellizerを使用している場合、それはすでに世話をしますあなたのためにこれの。

利用にisAuthenticated()satelizerの$認証サービスの方法の代わりの定義独自の

$rootScope.$on('$routeChangeStart', function (event, next) { 
    var currentRoute = next.$$route; 

    if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) { 
    $location.path('/auth'); 
    } 
    else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) { 
    $location.path('/front'); 
    } 

});

基本的に$ auth.isAuthenticated()は、ユーザーにvaild jwtが保存されているかどうかをチェックし、trueまたはfalseを返します。

$ routeChangeStartハンドラは、すべてのルート変更で起動し、ルートにrequiresAuthが設定されているかどうかをチェックし、isAuthenticatedがtrueまたはfalseを返してそれに応じて動作するかどうかを確認します。

自分でそれをしたい場合は、ここではそれが有効かどうトークンをデコードし、チェックする方法についての良いチュートリアルです: https://thinkster.io/angularjs-jwt-auth

+0

私はあなたが完璧になる示唆していると私は次のようにやっていることだと思いますあなたが言った、しかし、私は私のメイン/フロントページに行くとき私はまだログインページにリダイレクトされていません。 – Marco

+0

以前にログインしてログアウトしていない場合は、手動でlocalstorageからトークンを削除する必要があります。 satellizerの代わりにlocalStorage.setItemのごAuthControllerでも – marton

+0

、あなたは$ auth.setTokenを(使用し、手動でトークンを設定する必要がある場合)()、私が正しくリコール場合$ログインがあなたのためにそれを自動的に設定します。 – marton