Reputation: 101
I've got an angular1 Application which uses auth0.js to authenticate. I want to store the token in my tokenService when my app is recieving the callback from auth0.
How can i create an ui.router state matching the url so that my resolve can proccess the request and fetch additional data?
$stateProvider
.state('RecieveAuth', {
url: "",
resolve: tokenresolve,
controller: function($tate){
$state.go("MainSite");
},
data: { requirelanguage: true, requireLogin: true },
})
does not work, And if i use "/" as an url it does not match "#accesstoken="
I already tried to do the processing in run, but in this version i don't know how to keep the controllers waiting until my http call completed.
Any help is greatly appreciated.
Upvotes: 0
Views: 191
Reputation: 5014
In your resolve function, call a service from whatever factory for instance (where Data is a factory):
$stateProvider
.state('RecieveAuth', {
url: "",
resolve: {
content: function(Data) {
return Data.isAuth()
}
},
controller: function($tate){
$state.go("MainSite");
},
data: { requirelanguage: true, requireLogin: true },
})
And in your Data Factory, the isAuth() function can look like:
let isAuth = function() {
// Get Token from URL or local storage
let urlParameters = $location.search();
let token = '';
if ( urlParameters.hasOwnProperty('accesstoken') ) {
tokenSurvey = urlParameters['accesstoken'];
}
let deferred = $q.defer();
$resource('Call your server with the token retrieved above').query().$promise.then( (data) => {
//User successfully, auth, rreturn resolve promise
deferred.resolve(data);
},
(error) => {
// Eror during Auth, reject promise, state will not be loaded (you have to handle errors in this case)
deferred.reject(error);
});
return deferred.promise;
};
Upvotes: 0
Reputation: 101
I found a workaround using an injector:
$urlRouterProvider.otherwise(function ($injector, $location) {
var state = $injector.get('$state');
var $rootScope = $injector.get("$rootScope");
var accountSvc = $injector.get("accountSvc");
var tokenService = $injector.get("tokenService");
console.log('location', $location, 'location.search()', $location.search());
if ($location.$$url.indexOf('/access_token=') >= 0) {
accountSvc.authenticateAndGetProfile(function () {
tokenService.Reload();
$rootScope.Authenticate();
state.go('Folders');
}, function () {
state.go('Folders');
});
}
return $location.path();
});
Upvotes: 0