Angularjs redirects login page if not authenticated with exceptions

EDIT: forgot to mention that I only worked with AngularJs for a week, so if you see something that you think you need to change for the better and is not related to the question itself, feel free to tell me about the comments section.


ok, so I have authentication controllers and providers that I won’t show because they are not related to the scope of the issue. Then I have an interceptor to check if the user is checked in the call. If so, I set the header Authenticationin the request to include the user token, if I do not redirect the user to the login page and even make a request to the server (obviously, if someone bypasses this file, also Authorizeto the API).

I want to add a few exceptions, that is, there are some pages that I want to allow, even if the user does not have Auth Token. I can do this if this is a specific path, but I want to allow access to my page 404, and in Routingwhich I point .otherwiseto go to page 404, how can I do so that my interceptor only redirects to login if it doesn’t go to this page.

Interceptor

.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;
}])

and in my routing

 $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

I tried adding '/page-not-found'to mine if, but it will not work as expected, because by the time the location is checked for the first time, it is still not redirected.

edit As charlietfl already said, I'm trying to use a solution, but without even passing my function.

I removed this code from my interceptor:

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

service :

.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;
}]);

:

.state('smo-dashboard', {
        url: '/dashboard',
        templateUrl: '/Content/partials/dashboard.html',
        resolve: authCheckServiceProvider.onlyLoggedIn
})

, authData var, , , , .

+2
2

- , , .

, , . .config resolve . , resolve $stateChangeError login 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");
});
+5

, , , :

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

Source: https://habr.com/ru/post/1667071/


All Articles