Redirect index page if user is logged in AngularJS

rorymadden picture rorymadden · Feb 2, 2013 · Viewed 30.5k times · Source

I am trying to vary the page a user sees when they go to my website. If they are anonymous they should see the register page. If they have logged in they should see their dashboard.

I have a service which checks to see if the user is logged in (e.g. check cookies) which triggers when the Angular services load. I have tried to use the $routeProvider to redirect but the service has not been triggered when the $routeProvider is being initialized so it always thinks that the user is not logged in.

I can redirect easily once the initial page has been loaded but I am struggling to redirect the first page loaded. Can anyone give advice on how to do this?

Answer

Jigar Patel picture Jigar Patel · Feb 2, 2013

Make sure to read comment under the answer. When I answered this question I didn't thought about unit tests and design. I was just demonstrating that what can be one of many ways to achieve the desired result

I think the best way to do it under controller or your app.config.run. In your case you should create another module to check for user login status. Inject user login status checking module to your app module.

Here is the link to the sample followed by the app.js code

http://plnkr.co/edit/dCdCEgLjLeGf82o1MttS

var login = angular.module('myLoginCheck', [])
  .factory('$logincheck', function () {
    return function (userid) {
      // Perform logical user logging. Check either 
      // by looking at cookies or make a call to server.
      if (userid > 0) return true;
      return false;
    };
  });

var app = angular.module('myApp', ['myLoginCheck']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/publicurl', {})
      .when('/loginurl', {})
      .when('/unauthorize', {})
      .otherwise({redirectTo: '/'});
  })
  .run(function ($logincheck, $location) {
    //console.log("Into run mode");
    console.log("Userid 5 is logged in: ", $logincheck(5));
    console.log("Userid 0  logged in: ", $logincheck(0));

    //now redirect to appropriate path based on login status
    if ($logincheck(0)) {
      //$location.path('/loginurl'); or          
    }
    else {
      //$location.path('/publicurl'); or 
    }
  });

app.controller('MainCtrl', function ($scope) {
  $scope.name = 'World';
});