当用户未登录或用户尝试使用angularjs直接从URL访问页面时,重定向到登录

时间:2017-05-09 04:02:15

标签: php angularjs redirect

我正在创建一个小项目,如果用户角色为销售,则在登录后,它会将用户重定向到销售表单页面。 现在,如果用户通过在URL中输入其路径来尝试访问Sales form页面,并且用户未登录,我该如何将用户重定向到“登录”页面。这是我的Angular部分。

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作为Backend,你可以在$http.post部分看到它,所以请相应地给出你的答案。感谢帮助并提前谢谢你。

8 个答案:

答案 0 :(得分:9)

你应该使用angular routing而不是$ 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'); 
                }   
            }

        });
      }
   });

答案 1 :(得分:3)

您需要将角色变量存储在rootscope中,以便每个控制器都可以访问它。

登录成功后,将角色变量存储在rootScope中

            $rootScope.role=data.role;

然后在每个控制器中检查角色的值并重定向角色与所需角色不匹配的iser id

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

答案 2 :(得分: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 :(得分:3)

假设Angular正在客户端上运行并且知道PHP正在服务器上运行,那么我不建议在Angular中执行此任务,除非您有充分的理由。这不是因为它无法完成,但是因为(通常)客户端计算机上运行的代码的结果不应该被信任,而服务器上运行的代码(通常)的结果可以被信任。 / p>

在PHP中

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

    //Do something else

}
else
{
    //Ask them to log in
}

通过使用PHP(或更准确地说,使用服务器端语言),您可以更精确地调整您想要发生的事情。如果有人禁用Javascript怎么办?他们是否可以访问特权信息?如果某人是恶意的(需要不是员工),他们可以在客户端计算机上设置状态以获取访问权吗?

答案 4 :(得分:3)

我遇到了同样的问题,并通过提供一些文档解决了这个问题。

我们有后端作为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时,控制器都会加载并检查登录详细信息。如果没有重定向到登录页面。

修改

如果你想同时禁用后退按钮问题。将此代码添加到上面的代码中也可以。

<强> 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);
               });
};

希望它可以帮到你。这是一个工作片段。

谢谢

答案 5 :(得分:3)

  1. 使用angular.js,angular-route.js,angular-cookies.js和app.js 索引页面如下:

    <Style TargetType="DataGridRow" BasedOn="{StaticResource {x:Type DataGridRow}}">
                            <EventSetter Event="MouseDoubleClick" Handler="PreviewMouseDown"/>
                        </Style>
    
  2. 在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>
    
    1. 在login-Control中编写以下代码

          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";
              }   
         }
      });
      }
      

答案 6 :(得分:2)

在我看来,实现目标的最简单方法是创建一个隐藏类型的输入,并传递会话的值:如果登录则为1,如果作为样本注销则为0。

然后在Angular中创建一个条件。如果模型值为= 0,则重定向到登录页面,否则重定向到某处。

答案 7 :(得分:0)

请尝试使用$ state。

   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'); 
                }   
            }

        });
      }
   });