Skip to content

Instantly share code, notes, and snippets.

@ygotthilf
Last active August 29, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygotthilf/f64687447b2847c2ed83 to your computer and use it in GitHub Desktop.
Save ygotthilf/f64687447b2847c2ed83 to your computer and use it in GitHub Desktop.
AngularJS 1.x : Route access restriction
// module is your angular module
module.run(authRouting);
/* @ngInject */
function authRouting($state, $rootScope, $urlRouter, Auth) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
var requireAuth;
if (toState.data) {
requireAuth = toState.data.requireAuth; // PROPERTY TO SET FOR ROUTE ACCESS RESTRICTION
}
if (requireAuth) {
var auth = Auth.isLoggedIn(); // CHECK IF USER IS LOGGED IN (SYNC)
if (!auth) {
event.preventDefault();
Auth.isLoggedInAsync() // CHECK IF USER IS LOGGED IN (ASYNC)
.then(function() {
$urlRouter.sync();
})
.catch(function() {
$state.go('login'); // REDIRECT TO LOGIN
});
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment