2016-08-08 14 views
0

私の角度のアプリケーションで状態を認証します。利用可能なリソースは複雑すぎるため、なぜ私は理解できません。角度jsの状態を認証する方法

私のシンプルなロジックは、変数

$rootScope.is_authenticated = true 

を設定し、状態変数が真であるかどうかを確認するためにロードされるたびにチェックすることです。

私はこれをどのように達成でき、なぜログインと認証が複雑になるのでしょうか。

私AuthCtrl

//login 
$scope.login = function(user){ 
    console.log(user); 
    $http({ 
     method : "POST", 
     url : "myapi.com/login", 
     data : user 
    }).then(function mySucces(response) { 
     $scope.data = response.data; 
     $rootScope.is_authenticated = true; 
     $state.go('dashbooard'); 
    }, function myError(response) { 
     $scope.error = response.statusText; 
     $rootScope.is_authenticated = false; 
    }); 
} 

ログアウト機能

$scope.logout = function(){ 
    $rootScope.is_authenticated = false; 
    $state.go('auth'); 
} 

の私のconfigファイル

.config(function($stateProvider,$urlRouterProvider) { 
$stateProvider 
    .state('auth', { 
     url: '/auth', 
     templateUrl: 'partials/auth.html', 
     controller: 'AuthCtrl' 
    }) 
    .state('dashboard', { 
     url: '/dashboard', 
     templateUrl: 'partials/dashboard.html', 
     controller: 'DashboardCtrl', 
     resolve:{ 
      check: function($rootScope, $state){ 
       if($rootScope.is_authenticated == true){ 
        return true; 
       } 
       else{ 
        $state.go('auth'); 
       } 
      } 
     } 
    }) 

    $urlRouterProvider 
    .otherwise("/auth"); 

ログイン機能私は解決、私の状態に別のプロパティを追加しました。今の状態は、ユーザーがログインしている場合は、これは正しい方法です。アクセスしていない場合は、何することができ、私はの角度の実行やサービスメソッドを作成することによって、ログイン、認証を達成している

答えて

1

、それに関連した問題

私のコードスニペット:

routes.js://キー認証を使用して、コードを更新

.config(function($stateProvider,$urlRouterProvider) { 
$stateProvider 
    .state('auth', { 
     url: '/auth', 
     templateUrl: 'partials/auth.html', 
     controller: 'AuthCtrl' 
    }) 
    .state('dashboard', { 
     url: '/dashboard', 
     templateUrl: 'partials/dashboard.html', 
     controller: 'DashboardCtrl', 
     authenticate: true // add this to the routes you want the users' should be authenticated 
    }) 

    $urlRouterProvider.otherwise("/auth"); 

run.js:

(function() { 
    'use strict'; 

    angular.module('app').run(runBlock); 

    runBlock.$inject = ['$rootScope', '$state', '$log', 'AuthService']; 

    function runBlock($rootScope, $state, $log, AuthService) { 
     // detects change of state started 
     var rootScopeOn = $rootScope.$on('$stateChangeStart', function (event, next, params) { 
      // next.authenticate - if states needs to be authenticated 
      if (next.authenticate && !$rootScope.currentUser) { 
       event.preventDefault(); 


       if (AuthService.isLoggedIn()) { 
        AuthService.getLoggedInUser().then(function (response, status) { 
         $log.debug('Run - runBlock() - status : ', status); 
         if (!response) { 
          $state.go('login'); 
         } else { 
          $state.go(next, params); 
         } 
        }, function() { 
         $log.error('Run - runBlock() : ERROR'); 
         $state.go('login'); 
        }); 
       } else { 
        $state.go('login'); 
       } 
      } 
     }); 
     $log.debug('Run - runBlock() - rootScopeOn : ', rootScopeOn); 
    } 
})(); 

auth.js:

(function() { 
    'use strict'; 

    angular.module('app').factory('AuthService', AuthService); 

    function AuthService($http, $q, $log, $rootScope, User) { 
     function login(email, password) { 
      // TODO : change the code here to consume your http post, I use ng-resource so code is according to that 
      return User.login({ username: email, password: password }).$promise.then(function(response) { 
       $rootScope.currentUser = { 
        id: response.user.id, 
        email: response.user.email, 
        userame: response.user.username, 
        emailVerified: response.user.emailVerified 
       }; 
      }); 
     } 

     function logout() { 
      return User.logout().$promise.then(function() { 
       $rootScope.currentUser = null; 
      }); 
     } 

     function isLoggedIn() { 
      return User.isAuthenticated(); 
     } 

     function getUserInfo() { 
      return $rootScope.currentUser; 
     } 

     function setUserInfo(data) { 
      $rootScope.currentUser = { 
       id: data.id, 
       role: data.role, 
       email: data.email, 
       userame: data.username, 
       emailVerified: data.emailVerified 
      }; 
     } 

     function getLoggedInUser() { 
      var deferred = $q.defer(); 
      User.getCurrent().$promise.then(function(response) { 
       if(angular.isDefined(response.error)) { 
        if(response.error.status === 401) { 
         deferred.resolve(false); 
        } 
        else { 
         setUserInfo(response); 
         deferred.resolve(getUserInfo()); 
        } 
       } 
       else { 
        setUserInfo(response); 
        deferred.resolve(getUserInfo()); 
       } 
      }); 
      return deferred.promise; 
     } 

     function register(email, password) { 
      return User.create({ 
       email: email, 
       password: password 
      }).$promise; 
     } 

     return { 
      login: login, 
      logout: logout, 
      register: register, 
      isLoggedIn : isLoggedIn, 
      getUserInfo: getUserInfo, 
      getLoggedInUser: getLoggedInUser 
     }; 
    } 
})(); 
+0

ページが更新される場合は、ユーザーまたは認証を保持するにはどうすればよいですか? –

+0

ページが更新される、またはURLをコピー&ペースト新しいタブにある: '場合(AuthService.isLoggedIn()){ AuthService.getLoggedInUser()、その後(機能(応答、状態){' このコード。 – Aks1357

+0

私はコードを更新しました。私のために働いています。正しい方法があるかどうかを確認できますか? –

関連する問題