AngularJS - 检查用户是否经过身份验证,然后将其路由到正确的页面

ago*_*024 20 javascript jquery json angularjs angular-routing

我想要做什么当用户访问index.html页面时,我需要登录模块做两件事:

  1. 我需要这个来检查用户是否经过身份验证(我认为我已经开始使用"function authService")如果用户有一个有效的令牌然后将ui-view更改为dashboard/dashboard.html并且密钥无效或者根本没有密钥然后将login/login.html加载到ui-view中.

  2. 一旦他们成功登录,我希望他们被路由到"dashboard/dashboard.html"

这是我的登录脚本:

function authInterceptor(API) {
  return {
    request: function(config) {
      if(config.url.indexOf(API) === 0) {
        request.headers = request.headers || {};
        request.headers['X-PCC-API-TOKEN'] = localStorage.getItem('token');
      }
      return config;
    }
  } 
}

function authService(auth) {
  var self = this;
  self.isAuthed = function() {
    localStorage.getItem('token');
  }
}

function userService($http, API) {

  $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;';
  $http.defaults.transformRequest = [function(data) {
      return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];

  var self = this;

  self.login = function(username, pwd, ctrl) {
    ctrl.requestdata = API + '/winauth' + '; with ' + username;
    return $http.post(API + '/winauth', {
        username: username,
        pwd: pwd
      })
  };

  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

}

function LoginCtrl(user) {
  var self = this;

  function handleRequest(res) {
    self.responsedata = res;
    self.message = res.data.message;

    var authToken = res.data.auth_token;
    localStorage.setItem('token', authToken);
  }

  self.login = function() {
    this.requestdata = 'Starting request...';
    user.login(self.username, self.pwd, self)
      .then(handleRequest, handleRequest)
  }
}

// Login Module
var login = angular.module('login', ["ui.router"])

login.factory('authInterceptor', authInterceptor)
login.service('user', userService)
login.service('auth', authService)
login.constant('API', 'http://myserver.com/api')
Run Code Online (Sandbox Code Playgroud)

编辑 -我将此添加到我的登录控制器中以提供登录路由

login.config(function($httpProvider, $stateProvider, $urlRouterProvider) {

  $httpProvider.interceptors.push('authInterceptor');

  $urlRouterProvider.otherwise('/login');

  $stateProvider
  // HOME STATES AND NESTED VIEWS ========================================
  .state('login', {
    url: '/login',
    templateUrl: 'login/login.html',
    controller: "mainLogin",
    controllerAs: "log"
  })           
  // nested list with just some random string data
  .state('dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard/dashboard.html',
  })

})

login.controller('mainLogin', LoginCtrl)
Run Code Online (Sandbox Code Playgroud)

这是我的index.html:

编辑 -我删除了"ng-include"并添加了"ng-view"来控制路线.

<body ng-app="login" ng-controller="mainLogin as log" class="loginPage">

  <div class="main" ui-view></div>

</body>
Run Code Online (Sandbox Code Playgroud)

如您所见,我有一个函数正在检查用户本地存储中的令牌:

function authService(auth) {
  var self = this;
  self.isAuthed = function() {
    localStorage.getItem('token');
  }
}
Run Code Online (Sandbox Code Playgroud)

我将它作为服务加载到模块中:

login.service('auth', authService)
Run Code Online (Sandbox Code Playgroud)

这是我被困的地方.我不知道从哪里开始.我甚至不知道我是否正在使用我的authService功能.我还在学习很多关于AngularJS的知识,所以我很容易陷入困境.:)

你会注意到的另一件事是在我的index.html文件中,我只是将"login/login.html"部分加载为默认值.我需要它来加载login.html或dashboard.html,具体取决于它们是否已登录.然后在成功登录后将它们路由到dashboard.html.

该脚本在访问auth API,验证用户身份以及在本地存储上存储有效的身份验证密钥方面效果很好.

谁知道我怎么能做到这一点?

Gar*_*uuk 1

您将在此处专门处理登录控制器内的逻辑:

 self.login = function() {
    this.requestdata = 'Starting request...';
    user.login(self.username, self.pwd, self)
      .then(handleRequest, handleRequest)
  }
Run Code Online (Sandbox Code Playgroud)

在登录成功的回调中,您可以简单地进行状态更改以将用户发送到正确的状态。