3

Background

My app needs to make a request to the server to verify whether or not the user has an authenticated session, before the first state is loaded. As depending on on the url, the user may need to be redirected to the login page.

i.e if the initial url is myapp.com/#/profile and the user doesn't have a pre-existing authenticated session, they'll be redirected to myapp.com/#/login


Problem

I have logic in place to deal with this situation, but immediately after the session data request is made to the server and before it completes, the initial state change is triggered and the page loads and displays, before the server responds


Possible Solutions

1) I'm using django as my backend, so could just remove the initial server request from the app and pass the data direct to the app in the django template. Either through

  • ng-init of the main controller - although i've read that this is a bad idea, as it's not it's intended usage

  • Or in a script tag in the django template - which i'm loathe to do, as i'd rather keep all my application logic seperate in js files

2) Listen for the initial $stateChangeStart, cancel it and then call $state.reload() once the server requests completed


Question

It would seem to me to be a fairly common requirement to fulfill certain criteria before the initial state change occurs, so i'm wondering if i've missed something in the docs and there's already an inbuilt way to deal with this scenario?

Or is there a way to deactivate the $urlRouterProvider/$stateProvider to prevent the initial state change from occurring?

10
  • 1
    Depending on how you're doing routing in Angular, use the resolve property for routes: docs.angularjs.org/api/ngRoute/provider/$routeProvider - I use this for exactly what you're talking about. In the resolve callback, I make an AJAX request to my server to get user info from the session. If nothing is returned, that means they're not authenticated and I reject the promise that is used in the resolve
    – Ian
    Jul 3, 2014 at 14:53
  • Thanks @Ian. I'd considered that, but wouldn't it mean having to add the same function to every states resolve property?
    – james
    Jul 3, 2014 at 14:56
  • I'm not sure I follow, but I think so, yes. You can declare the function once, and then use it for all your routes (pass the reference) - what's wrong with that?
    – Ian
    Jul 3, 2014 at 14:57
  • Nothing i suppose. It would just seem cleaner if there were a way to add a generic resolve to the routeProvider itself - which gets called for all routes - rather than having to add it to every route in the config. And then maybe a way to then remove it as well, once it's no longer needed.
    – james
    Jul 3, 2014 at 15:01
  • I would love to hear someone else's solution, because the use of resolve is all I could find in my extensive searching when I needed a solution for something like this. It seems like any form of listening for a state change (or whatever) doesn't allow you to "resume" or "cancel" (only "cancel").
    – Ian
    Jul 3, 2014 at 15:17

1 Answer 1

5

Assuming that all of your authentication logic is already inside something like AuthService, wouldn't it be possible to do the following?

// 'AuthService' injected earlier
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if (!AuthService.isAuthenticated()) {
        // prevent navigation. don't go anywhere;
        // navigation will occur inside AuthService
        event.preventDefault();

        AuthService.setNextState(toState.name);
        AuthService.authenticateWithServer();
    }
    // proceed normally if user is already authenticated
});

Then, your AuthService:

app.service('AuthService', function($rootScope, $http, $state) {
    var next;

    this.setNextState = function(nextState) { next = nextState; };

    this.isAuthenticated = function() { ... };

    this.authenticateWithServer = function() {
        $http.post('/authen', { ... }).success(function(user){
            // house-keeping
            $rootScope.user = user;

            // navigate by state name
            $state.go(next);
        }).error(function(error) {
            // navigate to login screen
            $state.go('login');
        });
    };
});

This way, your state definition is clean, and the authentication logic is isolated in one place. You can also be sure that navigation will never take place until you have all the info you need.

2
  • Thanks, it's helped me come up with a similar solution. My problem's slightly different, as there are states that an unauthenticated user can visit
    – james
    Jul 3, 2014 at 21:52
  • @james If it helps, you should consider accepting the answer. At least in the future people will be more inclined to click in and read this page instead of ignoring it as unanswered question.
    – b0nyb0y
    Jul 3, 2014 at 22:09

Your Answer

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

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