如果未通过异常

时间:2015-09-23 16:13:40

标签: angularjs authentication redirect routing

编辑:忘了提到我一直在和AngularJs一起工作一周,所以如果你看到一些你认为应该改善的东西并且与问题无关,请随时告诉我评论部分。

好的,所以我有我的身份验证控制器和提供程序,我不会显示,因为它们与问题的范围无关。 然后我有一个拦截器来检查用户是否在进行呼叫时进行了身份验证。如果是这样的话,我在请求上设置Authentication标头以包含用户的令牌,如果不是我将用户重定向到登录页面,甚至不向服务器发出请求(显然,如果有人绕过这个,那么也是{关于API的{1}}。

我想要的是添加一些例外,这意味着即使用户没有Auth Token,也有一些我想要允许的页面。如果它是一个特定的路径,我能够这样做,但是我想允许访问我的404页面,并且它在我指定Authorize的{​​{1}}中转到404页面,如何我可以这样做,以便我的拦截器只有在没有进入此页面时才会重定向到登录。

拦截器

Routing

并在我的路由

.otherwise

我尝试将.factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) { var authInterceptorServiceFactory = {}; var authData = localStorageService.get('authorizationData'); var _request = function (config) { config.headers = config.headers || {}; if (authData) { config.headers.Authorization = 'Bearer ' + authData.token; } else if ($location.path != '/accounts/login' && $location.path != '/accounts/register') { $location.path('/accounts/login'); } return config; } var _responseError = function (rejection) { if (rejection.status === 401) { $location.path('/accounts/login'); } return $q.reject(rejection); } authInterceptorServiceFactory.request = _request; authInterceptorServiceFactory.responseError = _responseError; return authInterceptorServiceFactory; }]) 添加到我的 $urlRouterProvider.otherwise('/page-not-found'); $stateProvider (...)//rest of the states .state('page-not-found', { url: '/page-not-found', templateUrl: '/Content/partials/error/404.html', data: { displayName: false } }) (...)//rest of the states ,但它无法按预期工作,因为在第一次检查位置时,它仍未被重定向。

修改 由于charlietfl的消化我现在正试图使用​​决心,但它甚至没有通过我的功能。

我从拦截器中删除了这段代码:

'/page-not-found'

并向身份验证模块添加新的if

else if ($location.path != '/accounts/login' && $location.path != '/accounts/register') {
    $location.path('/accounts/login');
}

我想把它称为:

service

请注意我正在尝试记录authData .service('authCheckService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) { var self = { 'onlyLoggedIn': function ($state, $q) { var deferred = $q.defer(); var authData = localStorageService.get('authorizationData'); console.log(authData); if (authData) { deferred.resolve(); } else { deferred.reject(); $state.go('login'); } return deferred.promise; } } return self; }]); 以检查它是否正常工作但它不是,并且控制台上也没有错误。

2 个答案:

答案 0 :(得分:6)

最后想出了如何使用resolve解决它。

首先,我完全删除了之前使用过的拦截器。 然后我在路由.config中创建了一个函数,用于每个resolve进行身份验证。最后处理我的resolve我正在使用$stateChangeError重定向到登录state

路由配置

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

    // function to check the authentication //
    var Auth = ["$q", "authService", function ($q, authService) {
        authService.fillAuthData;
        if (authService.authentication.isAuth) {
            return $q.when(authService.authentication);
        } else {
            return $q.reject({ authenticated: false });
        }
    }];

    /* if the state does not exist */
    $urlRouterProvider
        .otherwise('/page-not-found'); 

    $stateProvider

        // state that allows non authenticated users //
        .state('home', {
            url: '/',
            templateUrl: '/Content/partials/home.html',
        })

        // state that needs authentication //
        .state('smo-dashboard', {
            url: '/dashboard',
            templateUrl: '/Content/partials/dashboard.html',
            resolve: {
                auth: Auth
            }
        })

        // errors //
         .state('page-not-found', {
             url: '/page-not-found',
             templateUrl: '/Content/partials/error/404.html'
         })

        // accounts //
        .state('login', {
            url: '/accounts/login',
            templateUrl: '/Content/partials/account/login.html'
        })

        // OTHER STATES //
    }
);
MainController中的

$scope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    $state.go("login");
});

答案 1 :(得分:0)

像这样的错误服务可以帮助根据响应中的状态来处理:

'use strict';

/**
 * Error Service
 */

angular.module('app.errorService', [])
        .factory("errorService", function ($route, $location) {        
                return {   
                    checkAndReturnError: function(a,b,c) {
                        if (a.status === 401){
                            (function(){
                                return $location.path("/accounts/login");
                            }());
                            return;
                        }
                        if (a.status === 404)
                            return;

                           alert("Error \n *" + a.data.message);

                    }
                };
        });

然后当您在响应状态为401时进行呼叫时,它将重定向。 vbad事情就是你需要将它添加到所有调用中:

            $scope.pageChanged = function() {
                $scope.Promise = Resource.get({}, function(response) {
                }, errorService.checkAndReturnError);
            };
相关问题