0

i have a AngularJS project with Asp Web API as backend. I have a login controller in angularjs that make a signin request to web api to request a token and if the user correctly logged in i set a variable in angularjs.

Now how can i prevent to load a route if the user isn't logged in? How, in the routeProvider can i prevent to load a route based on the setted variable?

gestionale.config(
  function ($routeProvider, $locationProvider) {
     $routeProvider.
        when('/personale', {
           templateUrl: 'View/people.html',
           controller: 'mainController',
           !!What to put here????!!!
    })
 });

Thanks

3 Answers 3

1

You will want to listen for the $locationChangeStart event and prevent the default behavior if the user is not authenticated.

$rootScope.$on('$locationChangeStart', function (event) {
    if (!vm.loggedIn()) {
        event.preventDefault();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You could use the 'resolve' property.

gestionale.config(
  function ($routeProvider, $locationProvider) {
     $routeProvider.
        when('/personale', {
           templateUrl: 'View/people.html',
           controller: 'mainController',
           resolve: userLoggedIn()
    })
 });

The userLoggedIn function would then handle the authentication promise and only resolve to the location when the promise is returned. This would also allow you to bounce them back to the login if the promise was rejected.

Comments

0

You usually see patterns like:

gestionale.config(
  function ($routeProvider, $locationProvider) {
     $routeProvider.
        when('/personale', {
           templateUrl: 'View/people.html',
           controller: 'mainController',
           options: {
               accessRole: 'admin'
           }
    })
 });

where control flows for 'userRole' will be handled by a User or Auth Service and then you can use Ben Felda's method above to desist access as the routes change.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.