Validate that the user is logged in when changing view - AngularJS

1

I am developing a web application with AngularJS , and I need to perform a validation in each of the views in which the user has previously logged in. I have already created a service for authentication and in this there is a method that validates if you have already logged in, but I do not know how to implement it with the views.

I have done this that I found there but it does not work, my biggest concern is that it can be accessed directly from the URL .

angular.module("myapp").run([
    "$rootScope",
    "$location",
    "$AuthService",
    function($rootScope, $location ,$AuthService){
        $rootScope.$on('$routeChangeStart', function (event, next) {
             if($AuthService.isAuth()){
                console.log("entra");
            }
            else{
                $location.path("/login");
            }
        });
    }
]);
    
asked by Brayanochz 17.01.2017 в 18:22
source

1 answer

1

I would do it in the following way using ui.router to manage the routes:

.state('register-event', { //ok
        url: '/register-event/:eventId',
        templateUrl: 'views/register-event.html',
        controller: 'RegisterEventCtrl as vm',
        onEnter: function($AuthService,$location){   
          if(!$AuthService.isAuth()){

              $location.path("/login");

          }

        }
    })

You could also use the following library, although some time ago I stopped using it for a bug I had but surely it was already fixed link

This would be used in the following way within run (), (this code may have changed since it is the one I used a while ago):

PermRoleStore
      .defineRole('anonymous', function (stateParams) {

          if (!$AuthService.isAuth()) {
            return true; // Is anonymous
          }
          return false;
      });
      PermRoleStore
      .defineRole('isloggedin', function (stateParams) {
          if ($AuthService.isAuth()) {
            return true; // Is loggedin
          }
            return false;
      });

In your routes you must add the following to verify that the user is logged in, if it is not logged in, it will be redirected to the login:

.state('tabs.comercios', {
          url: "/comercios/:comercioID",
          data: {
           permissions: {
            except: ['anonymous'],
            redirectTo: 'login'
           }
          }

        })

In case you want to redirect the user directly to the panel because it is already logged in, it would be like this:

.state('login', {
        url: '/login',
        data: {
          permissions: {
            except: ['isloggedin'],
            redirectTo: 'tabs.categorias'
          }
        },
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl'
    })
    
answered by 24.03.2017 / 06:26
source