I have an Angular app using UI Router where I'm trying to validate a user's token, if one exists, when the app runs. I am also checking that the user has permission to access certains routes. The problem is that $stateChangeStart
is running before I receive the response back from the authorization endpoint. Here's some code (coffeescript with js below) - this is all within my run
block.
app.run(($rootScope, $state, $stateParams, $log, Auth) ->
currentState = 'home'
$rootScope.$state = $state
# read a cookie if cookie exists
if Auth.setAuthenticationToken()
# hit api endpoint to validate token
Auth.validateToken (user) ->
# route to current state
# this returns after $stateChangeStart runs below
$state.go(currentState)
$rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
currentState = toState.name
Auth.setAuthenticationToken()
$rootScope.error = null
# compare users access permissions with incoming route's access level
if (!Auth.authorize toState.data.access, Auth.user)
event.preventDefault()
$rootScope.error = "Sorry, you haven't provided the required credentials."
$log.warn $rootScope.error
)
My question is how can I get the $stateChangeStart
to run only after the response from the auth endpoint has been returned. This only needs to happen the first time. Every subsequent state change can be done without hitting the auth endpoint.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…