第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

AngularJS-每個路由和控制器中的登錄和身份驗證

AngularJS-每個路由和控制器中的登錄和身份驗證

冉冉說 2019-07-23 16:31:57
AngularJS-每個路由和控制器中的登錄和身份驗證我有一個使用yeoman,grunt和bower創(chuàng)建的AngularJS應(yīng)用程序。我有一個登錄頁面,其中包含一個檢查身份驗證的控制器。如果憑據(jù)正確,我將重新路由到主頁。app.js'use strict';//Define Routing for appangular.module('myApp', []).config(['$routeProvider', '$locationProvider',   function($routeProvider,$locationProvider) {     $routeProvider    .when('/login', {         templateUrl: 'login.html',         controller: 'LoginController'     })     .when('/register', {         templateUrl: 'register.html',         controller: 'RegisterController'       })     .when('/forgotPassword', {         templateUrl: 'forgotpassword.html',         controller: 'forgotController'       })    .when('/home', {        templateUrl: 'views/home.html',        controller: 'homeController'     })     .otherwise({        redirectTo: '/login'     });//    $locationProvider.html5Mode(true); //Remove the '#' from URL.}]);angular.module('myApp').factory("page", function($rootScope){     var page={};     var user={};     page.setPage=function(title,bodyClass){         $rootScope.pageTitle = title;         $rootScope.bodylayout=bodyClass;     };     page.setUser=function(user){         $rootScope.user=user;     }     return page;});LoginControler.js'use strict';angular.module('myApp').controller('LoginController', function($scope, $location, $window,page) {     page.setPage("Login","login-layout");     $scope.user = {};     $scope.loginUser=function()     {         var username=$scope.user.name;         var password=$scope.user.password;         if(username=="admin" && password=="admin123")         {             page.setUser($scope.user);             $location.path( "/home" );         }         else         {             $scope.message="Error";             $scope.messagecolor="alert alert-danger";         }     }});在loginController,我檢查登錄信息,如果成功,我在服務(wù)工廠設(shè)置用戶對象。我不知道這是否正確。我需要的是,當用戶登錄時,它在用戶對象中設(shè)置一些值,以便所有其他頁面都可以獲得該值。無論何時發(fā)生任何路由更改,控制器都應(yīng)檢查用戶是否已登錄。如果沒有,它應(yīng)該重新路由到登錄頁面。此外,如果用戶已登錄并返回頁面,則應(yīng)轉(zhuǎn)到主頁??刂破鬟€應(yīng)檢查所有路由上的憑據(jù)。我聽說過ng-cookies,但我不知道如何使用它們。我看到的許多例子都不是很清楚,他們使用某種訪問角色或其他東西。我不希望這樣。我只想要一個登錄過濾器。有人可以給我一些想法嗎?
查看完整描述

3 回答

?
慕運維8079593

TA貢獻1876條經(jīng)驗 獲得超5個贊

這是另一種可能的解決方案,使用或的resolve屬性。示例:$stateProvider$routeProvider$stateProvider

.config(["$stateProvider", function ($stateProvider) {

  $stateProvider  .state("forbidden", {
    /* ... */
  })

  .state("signIn", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAnonymous(); }],
    }
  })

  .state("home", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAuthenticated(); }],
    }
  })

  .state("admin", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.hasRole("ROLE_ADMIN"); }],
    }
  });}])

Access 根據(jù)當前用戶權(quán)限解析或拒絕承諾:

.factory("Access", ["$q", "UserProfile", function ($q, UserProfile) {

  var Access = {

    OK: 200,

    // "we don't know who you are, so we can't say if you're authorized to access
    // this resource or not yet, please sign in first"
    UNAUTHORIZED: 401,

    // "we know who you are, and your profile does not allow you to access this resource"
    FORBIDDEN: 403,

    hasRole: function (role) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasRole(role)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    hasAnyRole: function (roles) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasAnyRole(roles)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAnonymous: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAnonymous()) {
          return Access.OK;
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAuthenticated: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAuthenticated()) {
          return Access.OK;
        } else {
          return $q.reject(Access.UNAUTHORIZED);
        }
      });
    }

  };

  return Access;}])

UserProfile將當前用戶的屬性,并執(zhí)行$hasRole,$hasAnyRole,$isAnonymous$isAuthenticated方法的邏輯(加上一個$refresh方法,稍后解釋):

.factory("UserProfile", ["Auth", function (Auth) {

  var userProfile = {};

  var clearUserProfile = function () {
    for (var prop in userProfile) {
      if (userProfile.hasOwnProperty(prop)) {
        delete userProfile[prop];
      }
    }
  };

  var fetchUserProfile = function () {
    return Auth.getProfile().then(function (response) {
      clearUserProfile();
      return angular.extend(userProfile, response.data, {

        $refresh: fetchUserProfile,

        $hasRole: function (role) {
          return userProfile.roles.indexOf(role) >= 0;
        },

        $hasAnyRole: function (roles) {
          return !!userProfile.roles.filter(function (role) {
            return roles.indexOf(role) >= 0;
          }).length;
        },

        $isAnonymous: function () {
          return userProfile.anonymous;
        },

        $isAuthenticated: function () {
          return !userProfile.anonymous;
        }

      });
    });
  };

  return fetchUserProfile();}])

Auth 負責(zé)請求服務(wù)器,知道用戶配置文件(例如鏈接到附加到請求的訪問令牌):

.service("Auth", ["$http", function ($http) {

  this.getProfile = function () {
    return $http.get("api/auth");
  };}])

在請求時,服務(wù)器應(yīng)返回此類JSON對象GET api/auth

{
  "name": "John Doe", // plus any other user information
  "roles": ["ROLE_ADMIN", "ROLE_USER"], // or any other role (or no role at all, i.e. an empty array)
  "anonymous": false // or true}

最后,當Access拒絕承諾時,如果使用ui.router$stateChangeError則會觸發(fā)該事件:

.run(["$rootScope", "Access", "$state", "$log", function ($rootScope, Access, $state, $log) {

  $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    switch (error) {

    case Access.UNAUTHORIZED:
      $state.go("signIn");
      break;

    case Access.FORBIDDEN:
      $state.go("forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });}])

如果使用ngRoute,$routeChangeError將觸發(fā)該事件:

.run(["$rootScope", "Access", "$location", "$log", function ($rootScope, Access, $location, $log) {

  $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
    switch (rejection) {

    case Access.UNAUTHORIZED:
      $location.path("/signin");
      break;

    case Access.FORBIDDEN:
      $location.path("/forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });}])

也可以在控制器中訪問用戶配置文件:

.state("home", {
  /* ... */
  controller: "HomeController",
  resolve: {
    userProfile: "UserProfile"
  }})

UserProfile然后包含服務(wù)器在請求時返回的屬性GET api/auth

.controller("HomeController", ["$scope", "userProfile", function ($scope, userProfile) {

  $scope.title = "Hello " + userProfile.name; // "Hello John Doe" in the example}])

UserProfile需要在用戶登錄或注銷時刷新,以便Access可以使用新的用戶配置文件處理路由。您可以重新加載整個頁面,也可以調(diào)用UserProfile.$refresh()。登錄時的示例:

.service("Auth", ["$http", function ($http) {

  /* ... */

  this.signIn = function (credentials) {
    return $http.post("api/auth", credentials).then(function (response) {
      // authentication succeeded, store the response access token somewhere (if any)
    });
  };}])
.state("signIn", {
  /* ... */
  controller: "SignInController",
  resolve: {
    /* ... */
    userProfile: "UserProfile"
  }})
.controller("SignInController", ["$scope", "$state", "Auth", "userProfile", function ($scope, $state, Auth, userProfile) {

  $scope.signIn = function () {
    Auth.signIn($scope.credentials).then(function () {
      // user successfully authenticated, refresh UserProfile
      return userProfile.$refresh();
    }).then(function () {
      // UserProfile is refreshed, redirect user somewhere
      $state.go("home");
    });
  };}])


查看完整回答
反對 回復(fù) 2019-07-23
?
慕桂英3389331

TA貢獻2036條經(jīng)驗 獲得超8個贊

為各個路由定義自定義行為的最簡單方法相當簡單:

1)routes.jsrequireAuth為任何所需的路線創(chuàng)建一個新屬性(如)

angular.module('yourApp').config(function($routeProvider) {
    $routeProvider        .when('/home', {
            templateUrl: 'templates/home.html',
            requireAuth: true // our custom property
        })
        .when('/login', {
            templateUrl: 'templates/login.html',
        })
        .otherwise({
            redirectTo: '/home'
        });})

2)在未綁定到內(nèi)部元素的頂層控制器中ng-view(為避免與角度沖突$routeProvider),檢查是否newUrl具有requireAuth屬性并相應(yīng)地采取相應(yīng)措施

 angular.module('YourApp').controller('YourController', function ($scope, $location, session) {

     // intercept the route change event
     $scope.$on('$routeChangeStart', function (angularEvent, newUrl) {

         // check if the custom property exist
         if (newUrl.requireAuth && !session.user) {

             // user isn’t authenticated
             $location.path("/login");
         }
     });
 });


查看完整回答
反對 回復(fù) 2019-07-23
  • 3 回答
  • 0 關(guān)注
  • 890 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號