简体   繁体   English

有角度的。 未验证身份

[英]Angular. Authentication is not checked

Authentication is not checked in my angular app. 我的角度应用程序未检查身份验证。 User should not have access to "car" & "profile" views without login but now i can get to it. 用户无需登录就无法访问“汽车”和“配置文件”视图,但现在我可以使用它。 I've added "secure" property to the pages that should be hidden from non-authenticated user. 我已将“安全”属性添加到应该对未经身份验证的用户隐藏的页面。 I've added check for apprun in app.js. 我在app.js中添加了apprun检查。 But it does not work. 但这行不通。

here's services.js 这是services.js

    'use strict';
angular.module('myApp')
.service('carsSrv', function () {
  var carList = [];

  var addUserCar = function (currObj, title, color, description, image) {
    currObj = {
        title: title,
        color: color,
        descriptiopn: description,
        image: image
      };
      /* console.log("Car Added:  " + currObj.id + "\n" + currObj.title + "\n" + currObj.color + "\n" + currObj.description + "\n" + currObj.image);*/
    carList.push(currObj);
    console.log(carList);
  };

  var getCars = function () {
    console.log("User cars");
    console.log(carList);
    return carList;

  };

  return {
    addUserCar: addUserCar,
    getCars: getCars
  }


})
.service('userSrv', userSrv)
.provider('storageSrv',storageSrv);
    function userSrv(storageSrv, carsSrv) {
      var user = {name: '', cars: carsSrv.carList };
      this.getUser = function() {
          return user;
      };

      this.getUserName = function () {
          return user.name;
      };
      this.login = function(){
        user.name = 'test name';
        user.cars = init();
        storageSrv.updateData(user);
                return true;

      }
      this.logout = function(){
        user.name = '';
        user.cars = [];
        alert('User logs out');
        storageSrv.updateData(user);
      }
      this.checkLoginUser = function(){
        return user.name !='';
      }
      this.getUserFeatures = function(){
        return user.features;
      }
      this.registration = function(){
        user.name = name;
        user.cars = init();
      }
      function init(){
        return storageSrv.getData();
      }

    }



  function storageSrv(){
    var storageName = 'cars';
    return {
      configStorageName : configStorageName,
      $get:$get
    };

    function configStorageName(name){
      if(name){
        storageName = name;
        return this;
      }
      else{
        return storageName;
      }
    }

    function $get(){
      function updateStorage(data){
        localStorage.setItem(storageName, data);
      }
      function getStorage(){
        return localStorage.getItem(storageName);
      }
      function updateData(data){
        console.log('storageName ' + storageName);
        updateStorage(JSON.stringify(data));
      }
      function getData(){
        console.log('storageName ' + storageName);
        var data = getStorage();
        return JSON.parse(data) || [];
      }
      return {
        updateData: updateData,
        getData:getData
      }
    }
  };

and here's app.js 这是app.js

    'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute'
])
    .constant('STORAGE_NAME', 'USER_CARS')
    .config(configStorage)
    .config(configRoutes)

.controller('carsCtrl', ['$scope', '$http', 'carsSrv',
    function($scope, $http, carsSrv) {
        $scope.view = "Cars";
        $http.get('cars/cars.json')
            .success(function(data) {

                $scope.cars = data;

                $scope.addCar = function(id, title, color, description, image) {
                    carsSrv.addUserCar(id, title, color, description, image);
                };

            })
            .error(function() {
                alert("can not get data from cars.json");
            });
    }
])

.controller('homeCtrl', ['$scope',

    function($scope) {
        $scope.view = "Home";
    }
])

.controller('loginCtrl', ['userSrv', '$scope',
    function(userSrv, $scope) {
        $scope.view = "Login";
        $scope.userLogin = function() {
            userSrv.login();

        }
        $scope.userLogout = function() {
            userSrv.logout();

        }

    }
])

.controller('profileCtrl', ['$scope', 'carsSrv',
    function($scope, carsSrv) {
        $scope.view = "Profile";
        $scope.userCars = carsSrv.getCars();


    }
]);

function configStorage(storageSrvProvider, STORAGE_NAME) {
    console.log(storageSrvProvider);
    storageSrvProvider.configStorageName(STORAGE_NAME);
}

function configRoutes($routeProvider) {
    $routeProvider

    .when('/cars', {
        templateUrl: 'views/cars.html',
        controller: 'carsCtrl',
        secure: true
    })

    .when('/profile', {
        templateUrl: 'views/profile.html',
        controller: 'profileCtrl',
        secure: true
    })

    .when('/home', {
        templateUrl: 'views/home.html',
        controller: 'homeCtrl',
        secure: false
    })

    .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'loginCtrl',
        secure: false
    })



    .otherwise({
        redirectTo: '/home'
    });
}

var appRun = function($rootScope, $location, $userSrv) {
    $rootScope.on('$routeChangeStart', function(event, next) {
        if (next.secure && !userSrv.checkLoginUser()) {
            $location.path('/login');
        }
    });
};

Your not really running the code appRun . 您没有真正运行代码appRun Try adding this last line to your module declaration: 尝试将最后一行添加到模块声明中:

angular.module('myApp', [
    'ngRoute'
])
    .constant('STORAGE_NAME', 'USER_CARS')
    .config(configStorage)
    .config(configRoutes)
    .run(appRun);

Also, because appRun is a variable containing an anonymous function, and not a function named appRun, by the time you call the run(appRun) (at the beginning of the file) the variable is defined but still undefined . 另外,由于appRun是一个包含匿名函数的变量,而不是名为appRun的函数,因此在您调用run(appRun) (在文件的开头)时,该变量已定义但仍未undefined That is why the function is not running. 这就是为什么该功能未运行的原因。

Also, when listening to the event, you're using a function $rootScope.on() , instead of the correct name $rootScope.$on() . 另外,在侦听事件时,您使用的是函数$rootScope.on() ,而不是正确的名称$rootScope.$on() Apart from that, I tested it on my computed and it seems to be working. 除此之外,我在计算机上对其进行了测试,并且似乎可以正常工作。

function checkRoute ( userSrv, $location, current ) {
    if (current.secure && !userSrv.checkLoginUser()) {
        $location.path('/login');
    }
}

function appRun ($rootScope, $route, $location, userSrv) {
    $rootScope.$on('$routeChangeStart', function(event, next) {
        checkRoute(userSrv, $location, next);
    });

    $rootScope.$on('sessionLogout', function () {
        checkRoute(userSrv, $location, $route.current);
    });
};

Update : For the logout to work, one strategy is to emit an event when logging out and then listen for that even and do the same check to see if the page is secure or not. 更新 :为了使注销正常工作,一种策略是在注销时发出一个事件,然后甚至监听该事件,并执行相同的检查以查看该页面是否安全。

function userSrv($rootScope, storageSrv, carsSrv) {
    //...
    this.logout = function(){
        user.name = '';
        user.cars = [];
        alert('User logs out');
        storageSrv.updateData(user);

        // Emit an event notifying the application that
        // the user has logged out
        $rootScope.$emit('sessionLogout');
    }
    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM