Protecting routes in AngularJS

angularjs logo
If you have some routes in AngularJS that you want to protect from non-authenticated users, just create a function that will redirect to your login route if user is not authenticated

var loginRequired = function($location, $q) {  
    var deferred = $q.defer();

    if(! userIsAuthenticated()) {
        deferred.reject()
        $location.path('/login');
    } else {
        deferred.resolve()
    }

    return deferred.promise;
}

And just attach this function to the routes that requires authentication

app.config(['$locationProvider', '$routeProvider',  
    function($location, $routeProvider) {
        $routeProvider.
            when('/todos', {
                templateUrl: '/js/templates/todos/index.html',
                controller: 'TodoCtrl',
                resolve: { loginRequired: loginRequired }
            });
    }
]);

If you need the user to be automatically redirected to the members area if user is authenticated and the user visits the login page, just do something like the below snippet:

var redirectIfAuthenticated = function(route) {  
    return function($location, $q) {

        var deferred = $q.defer();

        if (userIsAuthenticated()) {
            deferred.reject()
            $location.path(route);
        } else {
            deferred.resolve()
        }

        return deferred.promise;
    }
}

app.config(['$locationProvider', '$routeProvider',  
    function($location, $routeProvider) {
        $routeProvider.
            when('/login', {
                templateUrl: '/js/templates/login.html',
                controller: 'UserCtrl',
                resolve: { redirectIfAuthenticated: redirectIfAuthenticated('/todos') }
            }).
            when('/todos', {
                templateUrl: '/js/templates/todos/index.html',
                controller: 'TodoCtrl',
                resolve: { loginRequired: loginRequired }
            });
    }
]);

Recommended tool for startup entrepreneurs