Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid direct URL access in AngularJS

I have a web app which uses ui-router for routing. There is a user management module where there are certain roles given to a user (role x, y and z). When a user with role x logs in he will be restricted to certain states of the ui-router e.g. 'dashboard'.

When a user logs in I have saved the user's role in a cookie variable (using $cookie). I also used ng-hide to hide the Dashboard navigation sidebar when user with role x is logged in like this:

HTML:

<li ui-sref-active="active">
   <a ui-sref="dashboard" ng-hide="roleIsX()">
       <i class="fa fa-laptop"></i> <span class="nav-label">Dashboard</span>
   </a>
</li>

Controller:

$scope.roleIsX = function() {

  if ($cookies.get('loggedInUserRole') === "x")
    return true;
  else
    return false;

}

This works okay for now but the problem is when any user logs in he is able to directly navigate to a URL by writing it in the address bar. Is there an easy way I could solve this issue keeping in view my situation?

like image 684
Sibtain Avatar asked May 27 '26 09:05

Sibtain


2 Answers

I eventually used resolve of ui-router as @Shivi suggested. Following is the code if anyone is still looking up:

    app.config(['$urlRouterProvider', '$stateProvider', '$locationProvider',
        function($urlRouterProvider, $stateProvider, $locationProvider){
         ...

        .state('user-management', {
          ...
          ...
          resolve: { 
            roleAuthenticate: function($q, UserService, $state, $timeout) {
              if (UserService.roleIsX()) {
                // Resolve the promise successfully
                return $q.when()
              } else {

                $timeout(function() {
                  // This code runs after the authentication promise has been rejected.
                  // Go to the dashboard page
                  $state.go('dashboard')
                })
                // Reject the authentication promise to prevent the state from loading
                return $q.reject()
              }
            }


          }
        })

This code checks if the roleIsX then continue to the state else open dashboard state.

Helpful Reference: angular ui-router login authentication - Answer by @MK Safi

like image 187
Sibtain Avatar answered May 30 '26 05:05

Sibtain


listen to the $locationChangeStart event, and prevent it if needed:

$scope.$on("$locationChangeStart", function(event, next, current) {
    if (!$scope.roleIsX()) {
        event.preventDefault();
    }
});
like image 38
MoLow Avatar answered May 30 '26 06:05

MoLow