I am working on an Angularjs SPA with angular-ui-route v0.3.1.
Recently applied rule() to allow case insensitive urls...
$urlRouterProvider.rule(function ($injector, $location) {
//what this function returns will be set as the $location.url
var path = $location.path(), normalized = path.toLowerCase();
if (path != normalized) {
//instead of returning a new url string, I'll just change the $location.path directly so I don't have to worry about constructing a new url string and so a new state change is not triggered
$location.replace().path(normalized);
}
// because we've returned nothing, no state change occurs
});
also i am listening to $stateChangeStart event to check if the user is not logged in and redirect him to login page
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (!('data' in toState) || !('access' in toState.data)) {
messageHandler.show({
message: 'Access undefined for this state',
messageType: messageHandler.messageTypes.error
});
event.preventDefault();
}
else
if (!auth.authorize(toState.data.access)) {
event.preventDefault();// this line cause my circular issue
if (!auth.isLoggedIn()) {
var redirectState = toState.name;
auth.login( redirectState);
}
else {
messageHandler.show({
message: 'Seems like you tried accessing a route you do not have access to : ' + toState.name,
messageType: messageHandler.messageTypes.warning
});
$state.go('unauthorized');
}
}
});
The problem is that the role filter is do normalize the url, them when doing event.preventDefault() in $stateChangeStart event, the normalized url is being cancelled and the loop occurs again.
any help will be appreciated.
I am working on a project and it needs once a user entered his ID he wont be able to see the login page again when he will use the app.
I am not able to understand how to do this logic which I had tried is not working.
can anyone help me on this.This is my link of project on google drive have a look:
https://drive.google.com/open?id=0B51wL8pUai8XSHc0eHFQQ1cxX2M
You need to use localStorage in this case, where once you successfully login set your current user to true and on logout set that flag to false.
and over your app.run block you can put a condition.
$rootScope.$on('$stateChangeStart', function (event, toState, toParams,fromState, fromParams) {
if (toState.name !== 'login') {
if (!localStorageService.get('currentUser') {
event.preventDefault();
$state.go('login');
}
} else {
return false;
}
}
I have created an app with angular ui routing and states. Also I have a WEB API controller that can use to learn if user is authenticated or not. The problem is that http request to that WEB API has some delay to return result because is asynchronous.
I want, every time when user wants to go on state, to check if is authenticated or not, and give him access or redirect to login page. But first time when app running with someway i want to wait until i have answer from my WEB API.
I have this part of code
PlatformWeb.run(function ($rootScope, $state, $timeout, Authorization) {
$rootScope.$state = $state;
$rootScope.User = {
isAuthenticated: null,
targetState: null
}
Authorization.isAuthenticated().then(function (result) {
$rootScope.User.isAuthenticated = result;
$state.go($rootScope.User.targetState.name);
})
hasAccess = function () {
return $rootScope.User.isAuthenticated;
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
$rootScope.User.targetState = toState;
if ($rootScope.User.isAuthenticated == null)
event.preventDefault();
else {
if (!hasAccess()) {
event.preventDefault();
$state.go('PlatformWeb.Login');
}
}
});});
The first time when app runs, $rootScope.User.isAuthenticated is null, so i will prevent to load state. Also with my 'Authorization' service i call my asynchronous function to get if user if authenticated or not. Before i prevent loading state i keep when user wants to go, so when i have my result back from WEP API, I change the state '$state.go($rootScope.User.targetState.name);' to the state he want. Then I know if is authenticated or not and i ask if has permissions to go. If he hasn't then i redirect him to login state.
BUT event.preventDefault(); doesn't work as expected. When i run my app i get this error 'angular.min.js:6 Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.7/$rootScope/infdig?p0=10&p1=%5B%5D' multiple times.
Angular documentation says :
'10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []'
In my logic, 'stateChangeStart' function in condition '$rootScope.User.isAuthenticated == null' with event.preventDefault(); will make app logs here, and not run more until i know. When i get my result back from my WEBAPI I will go again in this function, but this time i know in which state to send him.
I would suggest, firstly always check where is current change navigating to... and get out if it is already redirected
$rootScope.$on('$stateChangeStart',
function (event, toState, toParams, fromState, fromParams) {
// are we already going to redirection target?
if(toState.name === 'PlatformWeb.Login'){
return; // yes, so do not execute the rest again...
}
$rootScope.User.targetState = toState;
if ($rootScope.User.isAuthenticated == null)
event.preventDefault();
else {
if (!hasAccess()) {
event.preventDefault();
// we will redirect here only if not already on that way...
$state.go('PlatformWeb.Login');
...
I have an angularJs app that requires authentication for most pages. I've implemented the checks similar to http://www.frederiknakstad.com/2014/02/09/ui-router-in-angular-client-side-auth/
In angular.module('myModule').run(), I have:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams){
if(toState.authenticate){
event.preventDefault();
var toUrl = $state.href(toState, toParams);
var promise = authService.isAuthenticated();
if (promise){
promise.then(function(){
// successful authentication proceed to requested state
$state.go(toState.name, toParams, {notify: false, inherit: false}).then(function(state){
$rootScope.$broadcast('$stateChangeSuccess', state.self, toParams);
});
},function(){
// failed authentication proceed to login
$state.go('login', {
next: toUrl
});
});
} else {
$state.go('login', {
next: toUrl
});
}
}
});
This is working just fine, however, when I tried to prevent a state change from within a controller when a form is dirty, it doesn't quite work. Here is how I add the listener in my controller:
$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if($scope.forms.myForm.$dirty) {
event.preventDefault();
modalAlert({
text: 'You have unsaved changes, are you sure you wish to continue'
}).result.then(function() {
// User is OK leaving dirty form, clear dirty flag to prevent this pop-up showing again and re-route
$scope.forms.myForm.$setPristine();
$state.go(toState, toParams);
}, function() {
// Cancelled request, stay on dirty form, don't need to do anything
});
}
});
Basically, what is happening, is the first $stateChangeStart is called, the auth is resolved, and it does a $state.go() to the next state we were going to. Meanwhile, the modal pops up asking to confirm and if I hit cancel, it reverts back to the previous state, but all my changes are gone because the auth checking already changed the state and lost all my changes. If the page I'm going to does not require authentication, then it works as expected.
How can I make my controller's $stateChangeStart execute first?
I want to prevent some flickering that happens when rails devise timeout occurs, but angular doesn't know until the next authorization error from a resource.
What happens is that the template is rendered, some ajax calls for resources happen and then we are redirected to rails devise to login. I would rather do a ping to rails on every state change and if rails session has expired then I will immediately redirect BEFORE the template is rendered.
ui-router has resolve that can be put on every route but that doesn't seem DRY at all.
What I have is this. But the promise is not resolved until the state is already transitioned.
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
//check that user is logged in
$http.get('/api/ping').success(function(data){
if (data.signed_in) {
$scope.signedIn = true;
} else {
window.location.href = '/rails/devise/login_path'
}
})
});
How can I interrupt the state transition, before the new template is rendered, based on the result of a promise?
I know this is extremely late to the game, but I wanted to throw my opinion out there and discuss what I believe is an excellent way to "pause" a state change. Per the documentation of angular-ui-router, any member of the "resolve" object of the state that is a promise must be resolved before the state is finished loading. So my functional (albeit not yet cleaned and perfected) solution, is to add a promise to the resolve object of the "toState" on "$stateChangeStart":
for example:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
toState.resolve.promise = [
'$q',
function($q) {
var defer = $q.defer();
$http.makeSomeAPICallOrWhatever().then(function (resp) {
if(resp = thisOrThat) {
doSomeThingsHere();
defer.resolve();
} else {
doOtherThingsHere();
defer.resolve();
}
});
return defer.promise;
}
]
});
This will ensure that the state-change holds for the promise to be resolved which is done when the API call finishes and all the decisions based on the return from the API are made. I've used this to check login statuses on the server-side before allowing a new page to be navigated to. When the API call resolves I either use "event.preventDefault()" to stop the original navigation and then route to the login page (surrounding the whole block of code with an if state.name != "login") or allow the user to continue by simply resolving the deferred promise instead of trying to using bypass booleans and preventDefault().
Although I'm sure the original poster has long since figured out their issue, I really hope this helps someone else out there.
EDIT
I figured I didn't want to mislead people. Here's what the code should look like if you are not sure if your states have resolve objects:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
if (!toState.resolve) { toState.resolve = {} };
toState.resolve.pauseStateChange = [
'$q',
function($q) {
var defer = $q.defer();
$http.makeSomeAPICallOrWhatever().then(function (resp) {
if(resp = thisOrThat) {
doSomeThingsHere();
defer.resolve();
} else {
doOtherThingsHere();
defer.resolve();
}
});
return defer.promise;
}
]
});
EDIT 2
in order to get this working for states that don't have a resolve definition you need to add this in the app.config:
var $delegate = $stateProvider.state;
$stateProvider.state = function(name, definition) {
if (!definition.resolve) {
definition.resolve = {};
}
return $delegate.apply(this, arguments);
};
doing if (!toState.resolve) { toState.resolve = {} }; in stateChangeStart doesn't seem to work, i think ui-router doesn't accept a resolve dict after it has been initialised.
I believe you are looking for event.preventDefault()
Note: Use event.preventDefault() to prevent the transition from happening.
$scope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
// transitionTo() promise will be rejected with
// a 'transition prevented' error
})
Although I would probably use resolve in state config as #charlietfl suggested
EDIT:
so I had a chance to use preventDefault() in state change event, and here is what I did:
.run(function($rootScope,$state,$timeout) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
// check if user is set
if(!$rootScope.u_id && toState.name !== 'signin'){
event.preventDefault();
// if not delayed you will get race conditions as $apply is in progress
$timeout(function(){
event.currentScope.$apply(function() {
$state.go("signin")
});
},300)
} else {
// do smth else
}
}
)
}
EDIT
Newer documentation includes an example of how one should user sync() to continue after preventDefault was invoked, but exaple provided there uses $locationChangeSuccess event which for me and commenters does not work, instead use $stateChangeStart as in the example below, taken from docs with an updated event:
angular.module('app', ['ui.router'])
.run(function($rootScope, $urlRouter) {
$rootScope.$on('$stateChangeStart', function(evt) {
// Halt state change from even starting
evt.preventDefault();
// Perform custom logic
var meetsRequirement = ...
// Continue with the update and state transition if logic allows
if (meetsRequirement) $urlRouter.sync();
});
});
Here is my solution to this issue. It works well, and is in the spirit of some of the other answers here. It is just cleaned up a little. I'm setting a custom variable called 'stateChangeBypass' on the root scope to prevent infinite looping. I'm also checking to see if the state is 'login' and if so, that is always allowed.
function ($rootScope, $state, Auth) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
if($rootScope.stateChangeBypass || toState.name === 'login') {
$rootScope.stateChangeBypass = false;
return;
}
event.preventDefault();
Auth.getCurrentUser().then(function(user) {
if (user) {
$rootScope.stateChangeBypass = true;
$state.go(toState, toParams);
} else {
$state.go('login');
}
});
});
}
as $urlRouter.sync() doesn't work with stateChangeStart, here's an alternative:
var bypass;
$rootScope.$on('$stateChangeStart', function(event,toState,toParams) {
if (bypass) return;
event.preventDefault(); // Halt state change from even starting
var meetsRequirement = ... // Perform custom logic
if (meetsRequirement) { // Continue with the update and state transition if logic allows
bypass = true; // bypass next call
$state.go(toState, toParams); // Continue with the initial state change
}
});
To add to the existing answers here, I had the exact same issue; we were using an event handler on the root scope to listen for $stateChangeStart for my permission handling. Unfortunately this had a nasty side effect of occasionally causing infinite digests (no idea why, the code was not written by me).
The solution I came up with, which is rather lacking, is to always prevent the transition with event.preventDefault(), then determine whether or not the user is logged in via an asynchronous call. After verifying this, then use $state.go to transition to a new state. The important bit, though, is that you set the notify property on the options in $state.go to false. This will prevent the state transitions from triggering another $stateChangeStart.
event.preventDefault();
return authSvc.hasPermissionAsync(toState.data.permission)
.then(function () {
// notify: false prevents the event from being rebroadcast, this will prevent us
// from having an infinite loop
$state.go(toState, toParams, { notify: false });
})
.catch(function () {
$state.go('login', {}, { notify: false });
});
This is not very desirable though, but it's necessary for me due to the way that the permissions in this system are loaded; had I used a synchronous hasPermission, the permissions might not have been loaded at the time of the request to the page. :( Maybe we could ask ui-router for a continueTransition method on the event?
authSvc.hasPermissionAsync(toState.data.permission).then(continueTransition).catch(function() {
cancelTransition();
return $state.go('login', {}, { notify: false });
});
The on method returns a deregistration function for this listener.
So here is what you can do:
var unbindStateChangeEvent = $scope.$on('$stateChangeStart',
function(event, toState, toParams) {
event.preventDefault();
waitForSomething(function (everythingIsFine) {
if(everythingIsFine) {
unbindStateChangeEvent();
$state.go(toState, toParams);
}
});
});
I really like the suggested solution by TheRyBerg, since you can do all in one place and without too much weird tricks. I have found that there is a way to improve it even further, so that you don't need the stateChangeBypass in the rootscope. The main idea is that you want to have something initialized in your code before your application can "run". Then if you just remember if it's initialized or not you can do it this way:
rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState) {
if (dataService.isInitialized()) {
proceedAsUsual(); // Do the required checks and redirects here based on the data that you can expect ready from the dataService
}
else {
event.preventDefault();
dataService.intialize().success(function () {
$state.go(toState, toParams);
});
}
});
Then you can just remember that your data is already initialized in the service the way you like, e.g.:
function dataService() {
var initialized = false;
return {
initialize: initialize,
isInitialized: isInitialized
}
function intialize() {
return $http.get(...)
.success(function(response) {
initialized=true;
});
}
function isInitialized() {
return initialized;
}
};
You can grab the transition parameters from $stateChangeStart and stash them in a service, then reinitiate the transition after you've dealt with the login. You could also look at https://github.com/witoldsz/angular-http-auth if your security comes from the server as http 401 errors.
I ran in to the same issue Solved it by using this.
angular.module('app', ['ui.router']).run(function($rootScope, $state) {
yourpromise.then(function(resolvedVal){
$rootScope.$on('$stateChangeStart', function(event){
if(!resolvedVal.allow){
event.preventDefault();
$state.go('unauthState');
}
})
}).catch(function(){
$rootScope.$on('$stateChangeStart', function(event){
event.preventDefault();
$state.go('unauthState');
//DO Something ELSE
})
});
var lastTransition = null;
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams, options) {
// state change listener will keep getting fired while waiting for promise so if detect another call to same transition then just return immediately
if(lastTransition === toState.name) {
return;
}
lastTransition = toState.name;
// Don't do transition until after promise resolved
event.preventDefault();
return executeFunctionThatReturnsPromise(fromParams, toParams).then(function(result) {
$state.go(toState,toParams,options);
});
});
I had some issues using a boolean guard for avoiding infinite loop during stateChangeStart so took this approach of just checking if the same transition was attempted again and returning immediately if so since for that case the promise has still not resolved.