24

Using the $rootScope.$on('$routeChangeStart', function(event, next, current), I'm redirecting to the signin page if the route requires authentication. That works perfectly.

How do I redirect back to the intended route though after signing in?

4
  • $location.path( value) docs.angularjs.org/api/ng.$location
    – charlietfl
    Commented Oct 31, 2013 at 1:55
  • Yes, but how do I pass the URL from that flagged the redirect to the signin route so that I can then user $location.path(callingRoute)? Commented Oct 31, 2013 at 2:00
  • where's the logic to check if user logged in? Could store current path in a service before sending to login. path() is both setter and getter
    – charlietfl
    Commented Oct 31, 2013 at 2:08
  • 2
    @julie-coderiver you should add your solution as its own answer to the question, so that way people can vote on it and you can get additional reputation that way.
    – user456814
    Commented Feb 14, 2014 at 19:00

3 Answers 3

25

This is a simplified version of what's working for me:

app = angular.module('ngApp', []).config(function ($routeProvider) {
  $routeProvider
    .when('/dashboard', {
        templateUrl: 'dashboard.html',
        controller: 'dashboardController',
        loginRequired: true //
      })
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'loginController'
      })
    .otherwise({redirectTo: '/login'})
});

Then in the application's run block:

app.run(function ($location, $rootScope) {
    var postLogInRoute;

    $rootScope.$on('$routeChangeStart', function (event, nextRoute, currentRoute) {

    //if login required and you're logged out, capture the current path
        if (nextRoute.loginRequired && Account.loggedOut()) {
          postLogInRoute = $location.path();
          $location.path('/login').replace();
        } else if (postLogInRoute && Account.loggedIn()) {
    //once logged in, redirect to the last route and reset it
          $location.path(postLogInRoute).replace();
          postLogInRoute = null;
        }
    });
});
3
  • 1
    +1 for this solution. The other answers are missing key components, but this solution worked a charm for me. Thanks, @SteveEnix!
    – Ed B
    Commented May 8, 2015 at 20:48
  • Works like a charm!
    – KhoPhi
    Commented Jun 6, 2016 at 17:08
  • Thank you, exactly what I was looking for! I had almost the same thing with a sessionStorage system.. but not really good way... yours is way better
    – KCarnaille
    Commented Jul 19, 2016 at 8:38
7

Here is an example of how I am doing it, hope it helps:

On the route provider, first set up the public access somehow:

// Just a demo on how the routes were set up to determine public access
angular.module('ngApp', []).config(function ($routeProvider) {

    $routeProvider

        .when('/', {
            templateUrl: 'views/main.html',
            controller : 'MainController',
        })

        .when('/login', {
            templateUrl  : 'views/login.html',
            controller   : 'LoginController',
            publicAccess : true // This is used in $routeChangeStart later
        });

    });

});

Then:

$rootScope.$on('$routeChangeStart', function(event, next, current) {

    var publicAccess = next.publicAccess || false;

    // This is just a service I made, this is how I check logged in status
    // AuthenticationService.check() returns a promise
    AuthenticationService.check().then(function() {

        // As this is a promise, this block signals that the user is logged in
        // If the page is marked as public access, then redirect to private area    
        if (publicAccess)
            $location.path('/').replace();

    }, function() {

        // Since this segment of the promise signals that the user is not
        // logged in, if the page is not publicly accessible, redirect to login
        if (!publicAccess)
            $location.path('/login').replace();

    });

});
5
  • Thank you. Mine is similar but a bit different. I updated the question to show how I solved. Cheers Commented Oct 31, 2013 at 2:08
  • Glad you got it sorted out :) Commented Oct 31, 2013 at 2:09
  • Francisco, could you share the AuthenticationService code? Thank you! Commented Jan 14, 2014 at 19:24
  • I was unable to find the code sample from above, but here is a very similar authentication service I made with AngularJS. It uses all the same concepts but is a little more in-depth. It is using an AspNet Identity back-end so you'll have to fill in the gaps. gist.github.com/franciscopreller/8427264 -- The equivalent to AuthenticationService.check() is AuthenticationService.updateState() on the Gist. Commented Jan 14, 2014 at 22:36
  • 3
    Well, this doesn't seem to be answering the OP's question, as it doesn't redirect back to the original route.
    – Léo Lam
    Commented Jun 26, 2014 at 15:12
1

The following answer is from the OP.


Here's how I solved it:

I added this event broadcast into the $routeChangeStart

$rootScope.$on('$routeChangeStart', function(event, next, current) { 

  if (next.authRequired) {

    var deferred = $q.defer(),
          _token = mainConfig.csrfToken;

    security.getCurrentUser(true, _token).success(function (data, status, headers, config)     {

      if(status == 200) {
        // set the local scope variables
        next.scope.isAuthenticated = true;
        next.scope.user = security.currentUser;
        // Broadcast out to each of the listeners
        $rootScope.$broadcast('currentUserAuthenticated');

      // Any other response requires a signin.  Redirect.  
      } else {
        next.scope.isAuthenticated = false;
        next.scope.user = null;
        $rootScope.$broadcast('authenticationRequired', $location.url());
        $location.path('/signin');
      }
    });
  }
});

Then in my security factory, I listened for the event and stored the location, like so:

$rootScope.$on('authenticationRequired', function(event, callingRoute) {
redirectRoute = callingRoute;
});
3
  • Don't you have to inject $location? Commented Aug 9, 2015 at 16:01
  • Yes, but in the outer controller/factory/service/whatever, not in the $rootScope.$on() event handler.
    – Léo Lam
    Commented Aug 10, 2015 at 2:20
  • this does not make sense at all. the login service will never reach the event. Commented Jul 25, 2017 at 2:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.