Wednesday, May 17, 2017

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

Leave a Comment

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.

6 Answers

Answers 1

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

Answers 2

You need to store the role variable in the rootscope so every controller can access it.

After login success, store the role variable in rootScope

            $rootScope.role=data.role; 

Then in each controller check the value of the role and redirect the iser id the role is not matching the required role

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

Answers 3

The easiest way to achieve your goal in my opinion is to create an input of type hidden, and pass the value of your session: 1 if logged in and 0 if logged out as a sample.

Then create a condition inside Angular. If model value is = 0 then redirect to login page, else redirect somewhere.

Answers 4

What you need is a service to handle login/logout that also persists the loggedInState. Services are the proper scalable way to pass data around an angular app

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

You can use route resolve on the sales path to hit the LoginService and redirect to login if not logged in. More info here: https://johnpapa.net/route-resolve-and-controller-activate-in-angularjs/

Answers 5

Assuming that Angular is running on the client and knowing PHP is running on the server, then I would not recommend doing this task in Angular, unless you have a good reason. This isn't because it can't be done, but because (typically) results from code run on a client machine should not be trusted, while results from code run on the server (typically) can be trusted.

In PHP

session_start(); if($_SESSION(['loggedIn'])) {     if($_SESSION(['role']) == 'sales')     {         //Do something     }      //Do something else  } else {     //Ask them to log in } 

By doing things in PHP (Or more accurately, by using a server side language) you can more closely fine tune what you want to have happen. What if someone disables Javascript? Will they have access to privileged information? What if someone is malicious (Needs not be an employee), can they hand craft a state on the client machine to gain access?

Answers 6

I had the same problem and resolved it through reffering some docs.

We had backend as Java,with angular js.I am posting the same which is working fine.It might help you.

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

You can do this way in your repository,So that during login it will set emailId.And retrieves whenever the url is accessed

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

So each time you enter url of the page,The controller loads and checks for login details.If not present redirects to login Page.

Edit

And if you want to disable back button problem also.Adding this to above code will work.

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

Hope it might help you.This is working snippet.

Thank you

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment