如何验证角度js中的状态

时间:2016-08-08 10:35:32

标签: javascript angularjs authentication angular-ui-router

我想在我的角度应用程序中验证状态。可用的资源太复杂了,我不明白为什么。

我的简单逻辑是设置变量

$rootScope.is_authenticated = true

并检查何时加载状态以查看变量是否为真。

我如何实现这一目标,为什么登录和身份验证的角度非常复杂。

我的配置文件

.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");

我的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');
}

我已经向我的州添加了另一个属性,解决。现在只有在用户登录时才能访问状态。这是正确的方式,如果没有,与之相关的问题是什么

1 个答案:

答案 0 :(得分:1)

我通过创建angular的运行和服务方法来实现登录,身份验证

我的代码段:

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
        };
    }
})();