AngularJS ui-router login authentication

前端 未结 10 2438
[愿得一人]
[愿得一人] 2020-11-22 11:13

I am new to AngularJS, and I am a little confused of how I can use angular-\"ui-router\" in the following scenario:

I am building a web application which consists of

10条回答
  •  天涯浪人
    2020-11-22 11:23

    First you'll need a service that you can inject into your controllers that has some idea of app authentication state. Persisting auth details with local storage is a decent way to approach it.

    Next, you'll need to check the state of auth right before state changes. Since your app has some pages that need to be authenticated and others that don't, create a parent route that checks auth, and make all other pages that require the same be a child of that parent.

    Finally, you'll need some way to tell if your currently logged in user can perform certain operations. This can be achieved by adding a 'can' function to your auth service. Can takes two parameters: - action - required - (ie 'manage_dashboards' or 'create_new_dashboard') - object - optional - object being operated on. For example, if you had a dashboard object, you may want to check to see if dashboard.ownerId === loggedInUser.id. (Of course, information passed from the client should never be trusted and you should always verify this on the server before writing it to your database).

    angular.module('myApp', ['ngStorage']).config([
       '$stateProvider',
    function(
       $stateProvider
    ) {
       $stateProvider
         .state('home', {...}) //not authed
         .state('sign-up', {...}) //not authed
         .state('login', {...}) //not authed
         .state('authed', {...}) //authed, make all authed states children
         .state('authed.dashboard', {...})
    }])
    .service('context', [
       '$localStorage',
    function(
       $localStorage
    ) {
       var _user = $localStorage.get('user');
       return {
          getUser: function() {
             return _user;
          },
          authed: function() {
             return (_user !== null);
          },
          // server should return some kind of token so the app 
          // can continue to load authenticated content without having to
          // re-authenticate each time
          login: function() {
             return $http.post('/login.json').then(function(reply) {
                if (reply.authenticated === true) {
                   $localStorage.set(_userKey, reply.user);
                }
             });
          },
          // this request should expire that token, rendering it useless
          // for requests outside of this session
          logout: function() {
             return $http.post('logout.json').then(function(reply) {
                if (reply.authenticated === true) {
                   $localStorage.set(_userKey, reply.user);
                }
             });
          },
          can: function(action, object) {
             if (!this.authed()) {
                return false;
             }
    
             var user = this.getUser();
    
             if (user && user.type === 'admin') {
                 return true;
             }
    
             switch(action) {
                case 'manage_dashboards':
                   return (user.type === 'manager');
             }
    
             return false;
    
    
          }
       }
    }])
    .controller('AuthCtrl', [
       'context', 
       '$scope', 
    function(
       context, 
       $scope
    ) {
       $scope.$root.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
          //only require auth if we're moving to another authed page
          if (toState && toState.name.indexOf('authed') > -1) {
             requireAuth();
          }
       });
    
       function requireAuth() {
          if (!context.authed()) {
             $state.go('login');
          }
       }
    }]
    

    ** DISCLAIMER: The above code is pseudo-code and comes with no guarantees **

提交回复
热议问题