Skip to content

Instantly share code, notes, and snippets.

@pechorin
Created December 11, 2013 14:52
Show Gist options
  • Save pechorin/7911719 to your computer and use it in GitHub Desktop.
Save pechorin/7911719 to your computer and use it in GitHub Desktop.
ui-router state constraints example
// Protection for ui-router states
//
// usage:
//
// app.run(function($stateConstraints) {
//
// $stateConstraints.protect({
// state : 'myState',
// guard : function($currentUser) { // <- any service
// // guard should return FALSE if transition to state should be cancelled
// if ($currentUser.isSignedOut()) return false
// };
// onFail: function() {
// alert("Signed users only");
// }
// });
//
// })
angular.module('app.services').service('$stateConstraints', function($injector, $rootScope) {
var service = this;
// list of all available guards
this.guards = {
signedEmployerOnly : function($currentSession, $state) {
if ($currentSession.isSignedIn() && $currentSession.user.isEmployer()) {
return true;
} else {
$state.go('default');
return false;
}
},
signedEmployerOwnerOnly : function($currentSession, $state, $stateParams) {
if (service.guards.signedEmployerOnly($currentSession, $state)) {
// TODO: check state params here
return true;
} else {
return false;
}
},
signedOutOnly : function($currentSession) {
return $currentSession.isSignedOut() == true;
}
}
// options -> {
// guard: guardFunction,
// state: 'stateName'
// }
this.protect = function protect(options) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if ( toState.name != options.state ) return;
var guardResult = $injector.invoke(options.guard, undefined, { toParams: toParams, toState: toState });
if (guardResult == false) {
event.preventDefault();
if ( _.isFunction(options.onFail) ) {
$injector.invoke(options.onFail);
} else {
$injector.invoke(function($state) {
console.log("request to " + toState.name + " declined with guard");
$state.go('default');
});
}
}
})
}
})
@pechorin
Copy link
Author

Usage example:

app.run(function($stateConstraints) {

  var $protect = $stateConstraints.protect;

  $protect({
    state : 'employer_profile',
    guard : $stateConstraints.guards.signedEmployerOnly,
    onFail: function() {
      console.log("employers only")
    }
  })

  $protect({
    state : 'vacancies',
    guard : $stateConstraints.guards.signedEmployerOnly
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment