20

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?

P.S.
  • 15,970
  • 14
  • 62
  • 86
rorymadden
  • 954
  • 3
  • 10
  • 20

2 Answers2

20

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';
});
Alan Dunning
  • 1,341
  • 8
  • 17
Jigar Patel
  • 4,585
  • 1
  • 17
  • 20
  • 1
    Thanks for your response. The issue I have is that when using the $routeProvider I cannot access the logic to check if the user is logged in because the app.config is loaded before the services are loaded. Unless I'm doing it wrong and there is a way to check a users cookies to see if they are logged in without using services? If so, then I could check for it when I set up the app.config. Thanks – rorymadden Feb 02 '13 at 23:31
  • It is absolutely doable.You have to create another module and inject that module into your main app. I have changed my answer accordingly. – Jigar Patel Feb 03 '13 at 03:19
  • 4
    I am not sure it is a good idea to use app.run; this goes against angular's decoupled approach and makes the app hard to test---every time you load the app module in a test it is going to try logging you in! Sure you can actually log in in your tests, but that it would be way better if you didn't have to login. – jdg Mar 17 '14 at 09:59
3

I just did this, by making a dummy template and small controller for the / path which redirects as appropriate.

controllers.controller('loginController',
                       ['$scope', '$location', '$cookies',
                        function($scope, $location, $cookies) {
    if (!!$cookies.user) {
        console.log("already logged in!");
        $location.path('/shows');
    } else {
        console.log("need to login!");
        $location.path('/users');
    }
}]);

var app = angular.module('app', ['ngRoute', 'ngCookies', 'controllers', 'services']);

app.config(['$routeProvider',
            function($routeProvider) {
    $routeProvider.when('/users', {
        templateUrl: "partial/users.html",
        controller: 'userController'
    });
    $routeProvider.when('/shows', {
        templateUrl: "partial/shows.html",
        controller: 'showController'
    });
    $routeProvider.when('/', {
        template: '',
        controller: 'loginController'
    });
    $routeProvider.otherwise({
        redirectTo: '/'
    });
}]);
a1291762
  • 196
  • 1
  • 5