Block pages with Angularjs login with asynchronous call

Asked

Viewed 721 times

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");
        }
    });
});

Note that at the end of the above code, I have a service (Session.getUserAuthenticated()) that checks if the user 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 does Return before the $http.post response, how do I fix the problem? It is possible to wait for the POST response or the logic I am using is incorrect?

  • Pass a callback to the service. But the most recommended I believe is not to send the parts that should only be accessed when authenticated.

  • In fact you are returning auth false because it is returned before the POST occurs. The post is asynchronous. In this case you must work with Callback or Promisses to only return if it is authorized within the POST result

  • @Caputo how would that be? Would you have to remove that service or change it? Thank you.

  • @Viníciusgobboa.de Live these blocking is only in frontend, on the server I also do the checking, this would only be to avoid unnecessary requests. But how would it be recommended? Thanks.

  • 1

    I’m a little busy here, I don’t know how your English is, but take a look at this answer and its link http://stackoverflow.com/a/16627409/3590714

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 the check something like that:

.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");
            });
        }
    });
});
  • I solved this using "Resolve", but I still haven’t been able to solve some problems to post a complete answer, but thank you.

  • At least the answer is useful?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.