My Angular application talks to a REST API I've built and I'd like to only make certain routes in my application accessible to users who are logged in.
At the moment, the user logs in with a username/password and the API gives them an encrypted access token. I then store that access token in local storage and send it in all future requests to the API. This is working brilliantly, however I'd also like to make some parts of my application accessible only to logged in users. For example, if I tried to go to my account settings while I'm not logged in, I want Angular to redirect to the login page.
I can do this really easily with the $locationChangeStart event in my application's run function:
$rootScope.$on('$locationChangeStart', function(event) {
// Check if user has an authentication token in local storage, redirect to /login if they don't
});
the problem with this is it will apply this to *all* of my routes. I'd like to only apply it to certain routes. I was imagining doing something like the following:
$routeProvider.when('/account/settings', {templateUrl: '/partials/account/settings.html', controller: 'AccountSettingCtrl', requiresAuthentication: true});
$rootScope.$on('$locationChangeStart', function(event, route) {
if (route.requiresAuthentication && !$localStorage.user.authToken) {
$location.path('/login');
}
});
The other solution I've thought of is to check every response to the API and if it returns a 403 (meaning the user isn't sending a valid auth token) redirect to the login page. But this has the disadvantage of only redirecting when there's an API request, so the account settings page will still be visible until a request is sent to the API and a response returned.
I've had a quick look into route resolves however they're really confusing me and I'm not sure they're even the way to go. Any advice?