1

I want to check if the User is still Active if not I want to redirect it to the Login page

I am having this check in a controller which is not a good Idea. Can someone help me please.

this is the Controller

pmaster.controller('AuthenticationCheckControll', ['localStorageService','$scope', '$location', '$window', function (localStorageService, $scope, $location, $window) {

var isValid = localStorageService.get("userID");
// I want this condition be check on every view in this application
if (isValid ==null)
{
    $window.location = "/AngularView/html/Master.html#/Login";
}

}]);

Lamin L Janneh
  • 75
  • 1
  • 10
  • You can just use a $rootScope variable and set it to true if the user is logged in. Since you're not using sessions or anything, the user will get logged out on window close or if you attach an event handler to change this $rootScope variable to false. – A.Sharma Jul 19 '16 at 15:30
  • yes!. Currently I am getting the userID and store it in a localStorageService. I want anytime the view changes let it check for that condition – Lamin L Janneh Jul 19 '16 at 15:36

2 Answers2

1

For shared sharing utility functions, you can use a 'service' to bundle them.

Angular services are: Lazily instantiated – Angular only instantiates a service when an application component depends on it. Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

Services Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

More information & example here

A similar example : AngularJS - User-Registration-and-Login-Example

Also note that 'factories' are available in Angular. Some interesting information about the difference 'Service' vs 'Factory' can be found here.

Community
  • 1
  • 1
daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
1

You can simply add below code in routes

$urlRouterProvider.otherwise(function(){
  var isValid = localStorageService.get("userID");
  if (isValid ==null){
     return '/Login';
  }else{
     // Your home page state url
  }
});

Or an easy way is,

  $urlRouterProvider.otherwise(localStorageService.get("userID") ? "/login" : "/homepage");
Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28