Last active
August 29, 2015 14:28
-
-
Save ygotthilf/f64687447b2847c2ed83 to your computer and use it in GitHub Desktop.
AngularJS 1.x : Route access restriction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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