2017-05-09 108 views
9

我正在創建一個小項目,其中如果用戶角色是銷售然後登錄後,它會將用戶重定向到銷售表單頁面。 現在,如果用戶試圖通過在URL中輸入路徑訪問Sales form頁面,並且用戶還沒有登錄,那麼我如何將用戶重定向到登錄頁面。這是我的角度部分。重定向登錄,當用戶沒有登錄或用戶嘗試訪問頁面直接從URL使用angularjs

app.controller('LoginCtrl',function($scope,$http,$window){ 

    $scope.login = function(){    
      data={ 
       email:$scope.email, 
       pwd:$scope.pwd 
      } 
      $http.post("widget/login.php",data).success(function(data){ 
       console.log(data); 
      if(!data.success){      
        $scope.errorMsg="username or password is incorrect"; 
      } 
      else{             
       $scope.role=data.role; 
       $scope.id=data.id; 
       if(data.role == "admin"){ 
        $window.location.href="AdminPage.html"; 
       } 
       else if(data.role == "Sales"){ 
        $window.location.href="sales_form.html"; 
       } 
       else if(data.role == "Account"){ 
        $window.location.href="account_form.html"; 
       } 
       else if(data.role == "Technical"){ 
        $window.location.href="Technical_Form.html"; 
       } 
       else{ 
        $scope.errorMsg="username or password is incorrect"; 
       } 
      } 

     }); 
    } 

}); 

從此我如何將用戶重定向到登錄頁面,如果用戶未登錄或嘗試直接從URL訪問頁面。 還有一件事我使用PHP作爲後端,因爲你可以在$http.post部分看到它,所以給你的答案相應。讚賞的幫助,並提前謝謝。

+0

或U可以試試這個插件[角權限(https://www.npmjs.com/package/angular-permission) – Iman

+0

它看起來像你剛剛在此啓動。如何處理狀態/路由實際上並非角度合適的方法。在你太過分之前,我建議在這裏查看一下UI-Router for AngularJS:https://ui-router.github.io/ng1/。 –

回答

3
  1. 使用angular.js,角route.js,角cookies.js和app.js 索引頁面如下:

    <script src="//code.angularjs.org/1.2.20/angular.js"></script> 
    <script src="//code.angularjs.org/1.2.20/angular-route.js"></script> 
    <script src="//code.angularjs.org/1.2.13/angular-cookies.js"></script> 
    <script src="app.js"></script> 
    
  2. 在app.js

    var app = angular.module('app', ['ngRoute', 'ngCookies']); 
        app.config(config); 
        app.run(run); 
    
    config.$inject = ['$httpProvider','$routeProvider', 
    '$locationProvider']; 
    function config($httpProvider, $routeProvider, $locationProvider) {  
    //Set routing 
    $routeProvider 
        .when('/login', { 
         controller: 'LoginController', 
         templateUrl: 'login/login.view.html', 
         controllerAs: 'vm' 
        }) 
         .otherwise({ redirectTo: '/login' }); 
        } 
    
        //Write following code to make user login after page refresh 
         run.$inject = ['$rootScope', '$location', '$cookieStore']; 
        function run($rootScope, $location, $cookieStore, $http, chatService) 
        { 
        // keep user logged in after page refresh 
        $rootScope.globals = $cookieStore.get('globals') || {}; 
    if ($rootScope.globals.currentUser) {   
        // set token in request header 
        // $http.defaults.headers.common['Authorization'] = 
        $rootScope.globals.currentUser.authdata; 
    
    } 
    
        //On location change redirect user to login page if not login else 
    redirect based on role 
        $rootScope.$on('$locationChangeStart', function (event, next, current) 
    { 
        // redirect to login page if not logged in and trying to access a 
    restricted page 
        //allow login and register page for all(login/notlogin) user 
        var restrictedPage = $.inArray($location.path(), ['/login', 
    '/register']) === -1; 
        var loggedIn = $rootScope.globals.currentUser; 
        if (restrictedPage && !loggedIn) { 
         $location.path('/login'); 
        } 
        else{ 
        $scope.role=$rootScope.globals.currentUser.user.role;    
         if(data.role == "admin"){ 
          $window.location.href="AdminPage.html"; 
         } 
         else if(data.role == "Sales"){ 
          $window.location.href="sales_form.html"; 
         } 
         else if(data.role == "Account"){ 
          $window.location.href="account_form.html"; 
         } 
         else if(data.role == "Technical"){ 
          $window.location.href="Technical_Form.html"; 
         } 
         else{ 
          $scope.errorMsg="username or password is incorrect"; 
         } 
        } 
    }); 
    } 
    
  3. 在與登錄控制寫以下代碼

    app.controller('LoginCtrl',function($scope,$http,$window){ 
        $scope.login = function(){    
        data={ 
        email:$scope.email, 
        pwd:$scope.pwd 
        } 
        $http.post("widget/login.php",data).success(function(data){     
    if(!data.success){      
         $scope.errorMsg="username or password is incorrect"; 
    } 
    else{ 
        //Set cookie 
        $rootScope.globals = { 
         currentUser: { 
         user: data     
        }      
    
    $cookieStore.put('globals', $rootScope.globals); 
    //Redirect url 
    $window.location.href="/";    
    } 
    }); 
    
+0

終於得到了我正在尋找的答案。它正在爲我工​​作,並且加上幫助點是讓用戶在頁面刷新後保持登錄狀態。 –

2

在我看來,實現您的目標的最簡單方法是創建一個隱藏類型的輸入,並傳遞會話的值:1如果已登錄,則輸入0;如果登出爲樣本,則輸入0。

然後在Angular中創建一個條件。如果模型值= 0,則重定向到登錄頁面,否則重定向到某處。

3

您需要將角色變量存儲在rootcope中,以便每個控制器都可以訪問它。

登錄成功後,將作用可變

  $rootScope.role=data.role; 

然後存儲在rootScope在每個控制器中檢查角色的值並重定向伊瑟爾ID的角色不匹配所需的角色

  if($rootScope.role != "Sales"){ 
       $window.location.href="login.html"; 
      } 
+0

你能解釋更多關於我無法理解的控制器部分嗎?我需要爲這個** If **條件添加'app.run'。 –

+0

即使我已登錄,它正在重定向到登錄頁面。 –

3

你需要的是一個服務來處理登錄/註銷,這也會持續loggedInState。服務是通過周圍的角應用

module.service('LoginService', LoginService); 

function LoginService() { 
    var isLoggedIn = false; 

    var service = { 
    login: function() { 
     //do login work 
     loggedIn = true; 
    }, 
    logout: function() { 
     //do logout work 
     loggedOut = false; 
    }, 
    get isLoggedIn() { 
     return isLoggedIn; 
    } 
    }; 

    return service; 
} 

您可以使用路由解決銷售通路上打LoginService並重定向到登錄,如果沒有登錄數據的正確擴展的方式更多的信息在這裏:https://johnpapa.net/route-resolve-and-controller-activate-in-angularjs/

3

假設Angular在客戶端上運行,並且知道PHP正在服務器上運行,那麼我不會推薦在Angular中執行此任務,除非您有充分的理由。這不是因爲它不能完成,而是因爲(典型地)來自運行在客戶端機器上的代碼的結果不應該被信任,而來自服務器上運行的代碼的結果(通常)是可信的。

在PHP

session_start(); 
if($_SESSION(['loggedIn'])) 
{ 
    if($_SESSION(['role']) == 'sales') 
    { 
     //Do something 
    } 

    //Do something else 

} 
else 
{ 
    //Ask them to log in 
} 

通過PHP做的事情(或者更準確地說,通過使用服務器端語言),您可以更緊密地微調你想有發生什麼。如果有人禁用Javascript會怎麼樣?他們是否可以訪問特權信息?如果某人是惡意的(需要不是員工),他們是否可以在客戶端機器上設置一個狀態以獲取訪問權限?

3

我有同樣的問題,並通過reffering一些文檔解決它。

我們有後端作爲Java,角js.I張貼相同的工作正常。它可能會幫助你。

LogonController。JS

scope.loginMerchant = function(merchant){ 
     MerchantRepository.loginMerchant(merchant) 
     .then(function (response){ 

      scope.emailId=response.data.emailId; 
      MerchantRepository.setEmailId(scope.emailId); 
      if(response.data.userType == "merchant"){ 
       state.go("merchanthome"); 
      } 
      else 
      { 
       alert(" ID/Password is Invalid..."); 
       state.go("merchantlogon"); 
      } 
     }); 
    }; 

MerchantRepository.js

你可以在你的倉庫做這種方式,這樣在登錄過程中會設置emailId.And檢索每當訪問URL

this.setEmailId=function(emailId){ 
    this.emailId=emailId; 
    window.sessionStorage.setItem("emailId",emailId); 
} 

this.getEmailId=function(){ 
    return window.sessionStorage.getItem("emailId"); 
} 

HomePageController.js

scope.user=MerchantRepository.getEmailId(); 
if(scope.user== 'null' || scope.user== null){ 
    state.go("logon"); 
}; 

所以每次進入頁面的URL,爲登錄控制器的負載,並檢查details.If不存在重定向到登錄頁面。

編輯

如果要禁用後退按鈕問題also.Adding這上面的代碼將工作。

LogonController.js

doMerchantLogout(); 

function doMerchantLogout() { 
    MerchantRepository.doMerchantLogout().then(
      function(result) { 
       scope.merchantSatus = result.data; 
       scope.emailId= null;//so it set to null,this satisfies condition and redirects to login page 
       MerchantRepository.setEmailId(scope.emailId); 
       }); 
}; 

希望它可以幫助you.This工作片段。

謝謝

8

您應該使用角度路由而不是$ window.location.href。

讓我使用ui-router.向您展示您在角度庫加載後在index.html中添加此行。

<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script> 

在你app.js

var routerApp = angular.module('routerApp', ['ui.router']); 

routerApp.config(function($stateProvider, $urlRouterProvider) { 

    $urlRouterProvider.otherwise('/home'); 

    $stateProvider 

     // HOME STATES AND NESTED VIEWS ======================================== 
     .state('login', { 
      url: '/login', 
      templateUrl: 'login.html', 
      controller : 'LoginController' 

     }) 

     // SALES PAGE AND MULTIPLE NAMED VIEWS ================================= 
     .state('sales', { 
      url: '/sales', 
      templateUrl: 'sales_form.html', 
      controller : 'SalesController' 
      ...... 
      ...... 

     }); 
    }); 

現在在你的控制器

app.controller('LoginCtrl',function($scope,$http,$window,$state){ 

    $scope.login = function(){    
      data={ 
       email:$scope.email, 
       pwd:$scope.pwd 
      } 
      $http.post("widget/login.php",data).success(function(data){ 
       console.log(data); 
      if(!data.success){      
        $scope.errorMsg="username or password is incorrect"; 
        $state.go('login');    

      } 
      else{             
       $scope.role=data.role; 
       $scope.id=data.id; 
       if(data.role == "admin"){ 
        $state.go('admin'); //add admin state as admin in ui-router like sales 
       } 
       else if(data.role == "Sales"){ 
        $state.go('sales'); 
       } 
       ..... 

       else{ 
        $scope.errorMsg="username or password is incorrect"; 
        $state.go('login'); 
       } 
      } 

     }); 
     } 
    }); 
0

請儘量使用$狀態。

angular.module('app',[]) 
    app.controller('LoginCtrl',function($scope,$state){ 

    $scope.login = function(){    
      data={ 
       email:$scope.email, 
       pswd:$scope.pswd 
      } 
      $http.post("/login.php",data).success(function(data){ 
       console.log(data); 
      if(!data.success){      
        $scope.errorMsg="username or password is incorrect"; 
        $state.go('app.login');    

      } 
      else{             
       $scope.role=data.role; 
       $scope.id=data.id; 
       if(data.role == "admin"){ 
        $state.go('app.admin'); //add admin state as admin in ui-router like sales 
       } 
       else if(data.role == "Sales"){ 
        $state.go('app.sales'); 
       } 
       ... 
       ... 

       else{ 
        $scope.errorMsg="username or password is incorrect"; 
        $state.go('app.login'); 
       } 
      } 

     }); 
     } 
    }); 
相關問題