This story is unavailable.

Let me give you an overview of the auth process in my current project. I’m pretty sure it’s not the cleanest solution, but it works.

First of all I’m using $rootScope.currentUser to store the user data and keep track of whether the user is logged in, not logged in, or login is still pending. Its value will be a profile object, false or undefined, respectively. This last part is to make the distinction between a completed but failed auth check and a pending auth check (request for /profile is still running, see below). When logging out or on a failed login attempt I also set $rootScope.currentUser to false.

In app.config I’ve configured an AuthInterceptor service, very much like the example in my article:

$httpProvider.interceptors.push('AuthInterceptor');

The AuthInterceptor will check for a 401 response from the server and do a $rootScope.$broadcast(‘AuthInterceptor:notAuthenticated’). In app.run I listen to this event and when it triggers, $rootScope.currentUser is set to false and a dialog box with the login form is opened. You may want to do something else instead (e.g. redirect to login page).

Then, in app.run there is a call to AuthService.restore() which fetches /profile and stores the returned user profile in $rootScope.currentUser. If it fails (404) because the user is not logged in, $rootScope.currentUser is again set to false.

Now, throughout the application you can refer to $rootScope.currentUser (available in any template via {{ currentUser }}, except inside directive isolate scope).

To secure routes I’m using a service called AuthResolver. For each route that I want to require authentication for, I add a ‘resolve’ property to the route definition, for example:

$stateProvider
.state('secured', {
url: '/secured',
templateUrl: 'modules/secured/secured.html',
controller: 'MyController as myCtrl',
resolve: {
auth: resolveAuthentication
}
});
/** @ngInject */
function resolveAuthentication(AuthResolver) {
return AuthResolver.resolve();
}

The AuthResolver itself was described in my article. It basically does a $rootScope.$watch on currentUser and checks for the three scenarios (object, false, undefined). So long as the value is undefined (profile request is still pending), the value will not be resolved and the route will not be executed. If the user is not logged in (i.e. currentUser is false), the app will redirect to the login page. Otherwise the route will be resolved with the current user profile.

I hope this helps.