Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to login when user is not logged in or user tries to access page directly from URL using angularjs

I am creating a small project in which if user role is Sales then after login it will redirect user to sales form page. Now how can I redirect user to Login page if user tries to access Sales form page by entering its path in URL and also user is not logged in.This is my Angular part.

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

        });
    }

});

From this how can I redirect user to login page if user is not logged in or tries to access page directly from URL. And One more thing I'm using PHP as Backend as you can see it in $http.post part so give your answer accordingly.Appreciate help and Thank you in advance.

like image 836
Krishna Patel Avatar asked May 09 '17 04:05

Krishna Patel


2 Answers

  1. Use angular.js,angular-route.js, angular-cookies.js and app.js on index page as follows:

     <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. In 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";
            }   
       }
    });
    }
    
    1. In login-Control write following code

        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="/";            
      }
      });
      
like image 108
Arun Saini Avatar answered Oct 15 '22 16:10

Arun Saini


you should use angular routing instead of $window.location.href.

Let me show you using ui-router.Add this line in index.html after angular library loaded.

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

In your 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'
            ......
            ......

        });
     });

Now In your controller

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

        });
      }
   });
like image 45
Bhoomi Bhalani Avatar answered Oct 15 '22 18:10

Bhoomi Bhalani