Skip to content

Instantly share code, notes, and snippets.

@dillonforrest
Created February 21, 2014 18:41
Show Gist options
  • Save dillonforrest/9140513 to your computer and use it in GitHub Desktop.
Save dillonforrest/9140513 to your computer and use it in GitHub Desktop.
/*
* Trying to ensure users are logged in. I don't want unverified users to look
* at any of the pages. So, on either $locationChangeStart or $routeChangeStart,
* I'd like to check if I'm logged in. If I'm not logged in, abort the route
* change and go to login route. If I AM logged in, continue changing the route.
*/
angular.module('myModule', [
'ui.state', // using AngularUI's $stateProvider
'ui.router', // using AngularUI's $urlRouterProvider
'UserService' // this checks whether or not users are logged in
])
.config(['$stateProvider', '$urlRouterProvider', function myAppConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('apples', {
url : '/apples',
template : '<p>apples</p>'
})
.state('bananas', {
url : '/bananas',
template : '<p>bananas</p>'
})
.state('login', {
url : '/login',
template : '<p>login</p>'
})
;
$urlRouterProvider.otherwise('login');
}])
.run(['$rootScope', '$location', 'UserService', function run($rootScope, $location, User) {
$rootScope.$on('$locationChangeStart', function checkLogin(evt, newRoute, oldRoute) {
if (!User.loggedIn) {
evt.preventDefault();
$location.path('/login'); // <-- this doesn't work D:
}
});
}])
/* add controllers etc */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment