Block pages with login in AngularJS with asynchronous call

2

In an application made with AngularJS, some pages are protected by login.

I configured the module as follows:

var app = angular.module('App', ['ngRoute', 'ngTouch', 'mobile-angular-ui']);

app.config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider.
        //...
        .when('/dashboard', {
            title: 'Dashboard',
            templateUrl: 'view/dashboard.html',
            controller: 'authCtrl',
            requireLogin: true
        })
        //...
    $locationProvider.html5Mode(true);
}])
.run(function ($rootScope, $route, $location, Data, Session) {        
    $rootScope.$on('$locationChangeStart', function (event) {
        var nextPath = $location.path();
        var nextRoute = $route.routes[nextPath];
        if (nextRoute.requireLogin && !Session.getUserAuthenticated()) {
           $location.path("/login");
        }
    });
});

Notice that at the end of the code above, I have a service (Session.getUserAuthenticated ()) that checks if the user is logged in before changing the route, see the code:

app.service('Session', function($http) {
    this.getUserAuthenticated = function() {
        var auth = false;
        $http.post('api/v1/session').then(function (results) {
            if(results.data.uid) auth = true;
        });
        return auth;
    };
});

The problem is that the above service always returns false, since it returns before the $ http.post response, how do I resolve the problem? Is it possible to wait for the POST response or is the logic I'm using is incorrect?

    
asked by anonymous 30.10.2014 / 17:52

1 answer

1

I did not test, but it would be something close to that (it gives you a good start):

app.service('Session', function($http) {
    this.getUserAuthenticated = function() {
        return $http.post('api/v1/session');
    };
});

And checking something like this:

.run(function ($rootScope, $route, $location, Data, Session) {
    $rootScope.$on('$locationChangeStart', function (event) {
        var nextPath = $location.path();
        var nextRoute = $route.routes[nextPath];
        if (nextRoute.requireLogin) {
            Session.getUserAuthenticated().success(function(results) {
                if (results.data.uid) console.log('autorizado!');
                else $location.path("/login");
            });
        }
    });
});
    
31.10.2014 / 14:57