User Permission - Angularjs

3

I have permission levels for users on my system: admin user and basic user.

I have a page that only admin users can access. I put an ng-if="isAdmin ()" in the hide menu if you are not an administrator.

It works correctly, but if by chance the user tries to access the page through the URL of the browser, he is able to access the page. How do I in AngularJS, not to let this page access if the user is not an administrator type?

I'm using ui-router and the version of Angular is 1.6:)

This is my code:

//Rotas
app.config(function($routeProvider) {
$routeProvider.when('/', {
    templateUrl : 'home.html',
})

$routeProvider.when('/appointments', {
    templateUrl : 'views/appointment/appointment.html',
    controller : 'AppointmentController'
})

$routeProvider.when('/patients', {
    templateUrl : 'views/patient/patient.html',
    controller : 'PatientController'
})

$routeProvider.when('/users', {
    templateUrl : 'views/user/user.html',
    controller : 'UserController',

})

$routeProvider.when('/services', {
    templateUrl : 'views/service/service.html',
    controller : 'ServiceController'
})
});

 /* Load para pegar as informações do usuário logado */
$scope.getUserData = function(){
    OdontoService.load('rest/user/getUserData').then(function (data) { 
        $scope.userAuthenticated = data.data;
        localStorage.setItem('permission', $scope.userAuthenticated.permission);
        $scope.isLoading = false;
    },function (error){
        console.log(error);
    });
}

$scope.isAdminUser = function(){
    return localStorage.getItem('permission') == 0;
}

Permission 0 means the user is an administrator.

    
asked by anonymous 23.08.2017 / 04:17

4 answers

5

Do not use angular to deny access to pages. The user can modify the Javascript loaded in the browser, even if it is overshadowed (i.e., minified) and access the page anyway.

The only secure way to authorize an access is on the server, with its preferred technology (PHP, Java, .NET, Javascript on Node.js etc.)

    
23.08.2017 / 07:44
0

It is important that your back end has a security module with permissions to enforce the security of your application. With the angular, using the ui-router, you can strengthen in the configuration of the "state" of the page to be called. See below:

.state('home', {
    url: '/home',
    templateUrl: 'home.html',
    controller: 'HomeController',
    resolve: {
        deps: function($q, $state) {

            var deferred = $q.defer();
            // Aqui verifica se o usuário é do tipo Administrador, caso sim, o state será resolvido e a página será carregada
            if(isAdmin())
                deferred.resolve();
            else{
                // Caso não, redireciona para a tela de login
                $state.go('login', { reload: true });
                deferred.reject()
            }

            return deferred.promise;
        }
    }
})

I hope I have helped.

    
23.08.2017 / 14:11
0

As you are using the ui-router this check can be done every time the state changes ($ state) you can add in the route if you need login or not, or if it needs to be admin to access some View feature ; You can retrieve the value in the controller, but then you will need to use $ state.current.data

(function () {
    'use strict';

    angular
        .module('app')
        .run(configRun)
    function configRun($rootScope, $state) {


        $rootScope.$on('$stateChangeStart', function (evt, to, toParams, from, fromParams) {


            if (to.data && to.data.requiresLogin && !$rootScope.user) {
                evt.preventDefault();
                $state.go('home');
            }

            if (toParams.codigo) {
                userService.getUserData()
                    .then(function (data) {
                        $rootScope.user = data;
                    });
            }

        });
    }
})();


(function () {
    'use strict';
    angular.module('app')

        .config(configRouter);
    /** @ngInject */
    function configRouter($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) {


        $ionicConfigProvider.views.maxCache(0);
        $httpProvider.interceptors.push('TokenInterceptor');
        $stateProvider

            .state('home', {
                url: "/",
                templateUrl: 'home/home.html',
                controller: 'HomeController',
                controllerAs: 'home',
            })
            .state('panic', {
                url: "/panic/:codigo",
                templateUrl: 'security/panic/panic.html',
                controller: 'PanicController',
                controllerAs: 'panic',
                params: {dataModal: null},

                data: {requiresLogin: true},
            })

            .state('login', {
                url: "/login",
                templateUrl: 'login/login.html',
                controller: 'LoginController',
                controllerAs: 'login',
                data: {teste: true},
            })

            .state('app', {
                url: "/app/:codigo",
                abstract: true,
                views: {

                    '': {
                        templateUrl: 'layout/layout.html',
                        controller: 'AppController'
                    },

                    'sidenav': {
                        templateUrl: 'layout/sidenav/sidenav.html',
                        controller: 'sidenavController',
                        controllerAs: 'sidenav',
                    },
                    'content': {
                        templateUrl: 'layout/content.html'
                    },
                    'footer': {
                        templateUrl: 'layout/footer/footer.html',
                        controller: 'footerController',
                        controllerAs: 'ft'

                    },
                    'security': {
                        templateUrl: 'security/security.html',
                        controller: 'SecurityController',
                        controllerAs: 'security'

                    },
                    'aside': {
                        templateUrl: 'layout/toolbar/toolbar.html',
                        controller: 'toolbarController',
                        controllerAs: 'toolbar',
                    },

                },

                data: {requiresLogin: true}

            })
        
        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/');
        $urlRouterProvider.when('', '/home');


    }

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
23.08.2017 / 14:54
0

Create an interceptor to execute the admin function whenever there is a request. It could look like this:

//interceptador
angular.module('seuapp').factory('authInterceptor', function($rootScope, $q){
  return{
    //O que colocar aqui será executado na requisição
    //Se fosse setar alguma coisa no header seria feito  no request.
    request: function(){
    //Verifica se tem permissão antes de envia-la
      if(localStorage.getItem('permission') != 0){
        //Se não tiver redireciona para login
        location.assign('/login')
      }
      return console.log("Acesso verificado.");
    },

    response: function(response){
      //Aqui você pode por alguma coisa que seja feita caso a pagina ou api 
      //que você esteja trabalhando retorne alguma coisa, tipo um token etc.
  }
});

//Depois você deve registrar o interceptor na sua aplicação.
angular.module('seuapp').config(function($httpProvider){
  //Aqui faz com que em toda as requições http seja executado o request/response.
  $httpProvider.interceptors.push('authInterceptor');
});

Just one highlight, this type of authentication is zero level. I created an application that gives of having a notion about other means of authentication. At a glance it may help. link

    
25.08.2017 / 10:07