0

I have a django backed angular app that uses angular-route to resolve the urls

I have a login system that users a factory to verify the authorisation of a user, as mentioned here.

Here is a part of my app.js file

.factory('Auth', function (){
var user;
return {
    setUser : function (u)
    {
        user = u;
    },
    isLoggedIn : function()
    {
        var User = false;
        return User;
    }
}
}
)


.config(
function($routeProvider)
{
    $routeProvider
        .when('/login', {
        templateUrl : '/login',
        controller:'LoginCtrl'
        })
        .otherwise('/')
}
)

.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {


    if (!Auth.isLoggedIn()) {
        console.log('DENY');
        event.preventDefault();
        $location.path('/login');
    }
    else {
        console.log('ALLOW');
        $location.path('/home');
    }
});
}])

I also have a watch set in my MainCtrl.

        $scope.$watch(Auth.isLoggedIn,
            function(value)
            {
                if(!value)
                {
                    $location.path('/login')
                }
                else
                {
                    $location.path('/home')
                }
            })

My issue is that, the /login template is never requested, even if I manually try /#/login, no errors in console as well.

Also, the location.$path('/login') is also not executed, as page stays right at requested URL. However, DENY gets printed in the console log.

I suspect that it is due to the app.run attribute , as the template gets rendered if I remove the run attribute.

Community
  • 1
  • 1
rjv
  • 6,058
  • 5
  • 27
  • 49

1 Answers1

1

It is simple : "login" is a state, and you forbid access to any state if the user is not logged in !

You could just change this for example :

.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event, toState, fromState) {
    if (!Auth.isLoggedIn() && toState == 'login' ){
        console.log('ALLOW');
    }
    else if (!Auth.isLoggedIn() && toState != 'login') {
        console.log('DENY');
        event.preventDefault();
        location.path('/login');
    }
    else {
        console.log('ALLOW');
        $location.path('/home');
    }
});

Also if you want to see a very complete auth system in angular.js, have a glance at this : https://github.com/angular-app/angular-app/tree/master/client/src/common/security

AlexHv
  • 1,694
  • 14
  • 21