I am trying to do some authentication with AngularUI Router. $urlRouter.sync()
looks like exactly what I need. However, that's only available when I intercept $locationChangeSuccess
. But when I do that, $state.current.name
is empty, whereas I want it to be the current state.
Here's my code so far:
$rootScope.$on('$locationChangeSuccess', function(event, next, nextParams) {
event.preventDefault();
if ($state.current.name === 'login') {
return userService.isAuthenticated().then(function(response) {
var authenticated;
authenticated = response.authenticated;
return alert(authenticated);
});
}
});
Any pointers as to what I'm doing wrong?
I would suggest to go more "
UI-Router
way". We should use$rootScope.$on('$stateChangeStart'
event where$state.current
would be properly provided. Here is a working exampleLet's observe simple (but not naive) solution, which could be extended to any degree later. Also if you will like this approach, here is much more comprehensive implementation: angular ui-router login authentication
Firstly, let's have our user service defined like this:
So, we use async (here
$timeout
) to loaduser
object form a server. In our example it will have a property{isAuthenticated: false }
, which will be used to check if is authenticated.There is also sync method
isAuthenticated()
which, until user is loaded and allowed - always returnsfalse
.And that would be our listener of the
'$stateChangeStart'
event:What we are checking first, is if user is already loaded and authenticated (
var isAuthenticated = ...
). Next we will give green to any public method. This is done with thedata {}
property of the state object definition (see Attach Custom Data to State Objects)And that's it. In case of states defined like in a below snippet we can experience:
'public'
,'home'
are allowed to anybody'private'
,'private'
will redirect to login ifisAuthenticated === false
the
'login'
in this example provides quick way how to switch isAuthenticated on/offCheck that all here
Some other resources:
data
and authentication