17

How can I redirect to the login page if someone tries to hit any other route when they are not authenticated? Is there a "best" way to do this in AngularJS?

Seems like a common problem but I can't seem to find a way to do this. Thank you in advance for your help.

martoncsukas
  • 2,077
  • 20
  • 23
sturoid
  • 2,501
  • 4
  • 20
  • 36
  • 2
    Create a `$routeChangeStart` or `$stateChangeStart` listener (for ui router), check the auth status, redirect to login if not authenticated. – Mohammad Sepahvand Oct 01 '14 at 16:18

2 Answers2

22

The best way to do this is to set up a '$routeChangeStart' listener which checks an 'authProvider' service function to verify that there is a user logged in. In our 'app.js' or in a separate file:

angular.module('myApp')
     .run(['$rootScope', '$location', 'authProvider', function ($rootScope, $location,     authProvider) {
        $rootScope.$on('$routeChangeStart', function (event) {

        if (!authProvider.isLoggedIn()) {
          console.log('DENY : Redirecting to Login');
          event.preventDefault();
          $location.path('/login');
        }
        else {
          console.log('ALLOW');
        }
  });
}])

Then for our 'authProvider' service:

angular.module('myApp')
  .factory('authProvider', function() {
    var user;
      return {
        setUser : function(aUser){
          user = aUser;
        },
        isLoggedIn : function(){
          return(user)? user : false;
        }
      };
  });

This solution was created from an answer here on stack overflow.

Thank you @MohammadAwwaad

Community
  • 1
  • 1
Rorschach120
  • 1,200
  • 1
  • 11
  • 18
  • Thanks @Rorschach120. That did the trick. The only thing that confuses me is the preventDefault(). Do you even need that for this to work? The redirect is preventing the default action and redirecting so it seems like you don't but I could not be seeing something. – sturoid Oct 01 '14 at 17:15
  • +1 because its redirecting to login page for unauthorized users but how to make user logged in via server side code like php? How to make any page accessible without need of being logged-in e.g. sign-up page? – RN Kushwaha Mar 02 '15 at 09:21
  • 3
    http://stackoverflow.com/questions/20969835/angularjs-login-and-authentication-in-each-route-and-controller?rq=1 – Mohammad Awwaad Jul 26 '16 at 10:07
  • I can still give the complete URL and the user gets navigated to whatever page he requests for. –  Jan 17 '17 at 10:52
0

I am doing this a different way now, with Node.js & Express & the passport module, but before that, when I was using PHP, I did it with several Angular modules. I had an outside module on my <html> tag with ng-app, then ng-controllers at certain tags, like <body> & certain <div>s. In one of these ng-controllers, I had an authentication function, then I had an ng-if for login, logout, etc. If the user is not logged in, I hid the current page and ng-included the appropriate page. Otherwise, I ng-included the current page.

That was probably not the best solution, but I didn't want to use third-party modules. If you get confused or have any questions (I know I was pretty confused) just ask.

trysis
  • 8,086
  • 17
  • 51
  • 80
  • I did something like this as well. Controlling the visible template with a variable in a main controller outside the whole thing. Then I realized that's precisely what `ng-view` is for, so I'm tryna use that instead. – tscizzle Jun 24 '16 at 04:20