In AngularJS, there are many ways to ensure a user is authenticated before allowing them access to a route.
My preferred method uses $routeChangeStart in angular.run
to control which routes are allowed.
Here is a very simple example. It assumes that ALL routes except /intro
require login. It could be modified to allow other routes.
.run(function ($rootScope, $location, AccountService) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
// if route requires auth and user is not logged in
if ( $location.url() !== '/intro' && !AccountService.hasToken()) {
// redirect back to login
return $location.path('/intro');
}
});
})
This works pretty well for me. Unfortunately, the newest version of IonicFramework has switched to the Angular-UI Router framework. This has some great benefits but broken my authentication.
Fortunately, the fix is pretty simple. The only difference is that $routeChangeStart
is replaced with $stateChangeStart
. Here's the new code:
.run(function ($rootScope, $location, AccountService) {
$rootScope.$on('$stateChangeStart', function (event, next, current) {
// if route requires auth and user is not logged in
if ( $location.url() !== '/intro' && !AccountService.hasToken()) {
// redirect back to login
return $location.path('/intro');
}
});
})