gyc
gyc

Reputation: 4360

Routing logic with authentification and otherwise

I've been working on an authentification system for my angular application. I managed to make some states 'secure' with a redirection to a login page with the following config code.

.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/home");
    $stateProvider
    .state('home',
    {
        url : '/home',
        templateUrl : 'views/home.html',
        resolve : {
            authenticate: authenticate
        }
     }
}

authenticate is the function that resolves or rejects the promise.

function authenticate($q, $location, $timeout) {

    //simplified version
    var authed = false;

    if (authed == true) {
        return $q.when();
    }
    else {
        $timeout(function() { $location.path('/login'); })
        return $q.reject();
    }
}

This works beautifully for every url inside my application:

http:myproject.com/#/privatepage redirects to http:myproject.com/#/login
http:myproject.com/#/ redirects to http:myproject.com/#/login

But http:myproject.com/ enters the otherwise method of $urlRouterProvider, redirects to #/home then redirects to #/login several times and I get an angular error:

Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.8/$rootScope/infdig?p0=10&p1=%5B%5D

I believe this happens around the line return $q.reject(); of the authenticate function.

Upvotes: 0

Views: 88

Answers (1)

Moid
Moid

Reputation: 1447

You should rather make a check that if a user is not logged in then point the otherwise state to login else to home.

Something like this...

if (loggedIn) {

     $urlRouterProvider.otherwise('/home');

    } else {
        $urlRouterProvider.otherwise('/login');
    }

loggedIn can be set to be equal to a boolean value depending upon if the user is logged in.

Upvotes: 1

Related Questions