Redirect to route if user is not authenticated

Viewed 10190

I'm trying to cleanly implement a way to redirect the user to a login route if they're not logged in. I'm basing my solution off of another SO answer here that doesn't work out of the box. Here's my solution.

angular.module('myApp', ['ngResource', 'ngRoute'])
  .config(['$routeProvider', function ($routeProvider) {
    var requireAuthentication = function () {
        return {
            load: function ($q) {
                console.log('Can user access route?');
                if (g_isloggedIn === true) { // fire $routeChangeSuccess
                    var deferred = $q.defer();
                    deferred.resolve();
                    console.log('Yes they can!');
                    return deferred.promise;
                } else { // fire $routeChangeError
                    console.log('No they cant!');
                    return $q.reject("'/login'");
                }
            }
        };
    };

    $routeProvider
        .when('/some_page_that_requires_authentication', {
            templateUrl: '/views/secret.html',
            controller: 'secretCtrl',
            resolve: requireAuthentication()
        })
        .when('/anybody_can_see_me', {
            templateUrl: '/views/public.html',
            controller: 'publicCtrl',
        });
}]);

My question is, where can I listen on the $routeChangeError event so that I can redirect the route? I tried doing it in a directive, but could never get the event to fire. I can't put it into a controller, because it won't load if the promise is rejected. Any thoughts?

3 Answers
Related