How do I update loggedInUser after onlogin in Mozilla Persona - javascript

I'm using Mozilla Persona on a project. I would like to update loggedInUser after onlogin. But loggedInUser is an attribute of an object passed to navigator.id.watch().
navigator.id.watch() was called once (in a AngularJS service).
Should I call it again, passing the full object? It doesn't seem right. Am I wrong? =P
Here is my service:
app.factory('persona', function ($rootScope, $http) {
navigator.id.watch({
loggedInUser: null,
onlogin: function onlogin(assertion) {
console.log(this);
$http.post('/signIn', { assertion: assertion })
.then(function (data, status, headers, config) {
$rootScope.$broadcast('signIn', data.data);
}, function (data, status, headers, config) {
$rootScope.$broadcast('signInError', data.data);
});
},
onlogout: function onlogout(param) {
$http.get('/signOut')
.then(function (data, status, headers, config) {
$rootScope.$broadcast('signOut', data.data);
}, function (data, status, headers, config) {
$rootScope.$broadcast('signOutError', data.data);
});
}
});
return {
signIn: function signIn() {
navigator.id.request();
},
signOut: function signOut() {
navigator.id.logout();
}
};
});

Can't you just make loggedInUser become global or at least "locally global" below the same scope as your navigator.id.watch method, just like the MDN example?
After that you can get the JSON response from the Persona service, which contains some data, including the e-mail. So you could pass that data on your AJAX response and fill the loggedInUser variable
https://developer.mozilla.org/en-US/docs/Persona/Quick_Setup#Step_3.3A_Watch_for_login_and_logout_actions
var currentUser = 'bob#example.com';
navigator.id.watch({
loggedInUser: currentUser,
onlogin: function(assertion) {
$.ajax({
type: 'POST',
url: '/auth/login', // This is a URL on your website.
data: {assertion: assertion},
success: function(res, status, xhr) { window.location.reload(); },
error: function(xhr, status, err) {
navigator.id.logout();
alert("Login failure: " + err);
}
});
},
onlogout: function() {
$.ajax({
type: 'POST',
url: '/auth/logout', // This is a URL on your website.
success: function(res, status, xhr) { window.location.reload(); },
error: function(xhr, status, err) { alert("Logout failure: " + err); }
});
}
});
JSON response sample from MDN:
{
"status": "okay",
"email": "bob#eyedee.me",
"audience": "https://example.com:443",
"expires": 1308859352261,
"issuer": "eyedee.me"
}

At the navigator.id.watch call, set loggedInUser: localStorage.getItem('persona') || null (the null is important), then, when Persona login is successful, do localStorage.setItem('persona', theUserEmail), when it is failed, do localStorage.removeItem('persona').

Related

ReactJs Promise + Ajax Return Value

I have a function which uses jquery to call API and get a result. My API end is programmed to return the number "19" just for testing.
export function clientAdd(data) {
return (dispatch) => {
return $.ajax({
url: "http://api.example.com/client/add/",
headers: {'AUTHORIZATION': `${sessionStorage.jwt}`},
type: 'POST',
cache: false,
data: data,
dataType: 'json',
success: function (data) {
let redirectUrl = '/client/' + data
return redirectUrl';
},
error: function(xhr, status, err) {
if (xhr.status === 401) {
sessionStorage.removeItem('jwt');
return '/signin';
}
console.log('xhr',xhr.responseText);
console.log('status',status);
console.log('err',err);
return dispatch({type: GET_CLIENT_FAIL, err});
}
})
}
}
Then in my component, upon clicking on the submit button, it will call the onSave function as follows
onSave(event) {
//event.preventDefault();
this.props.actions.clientAdd(this.state.credentials).then((result) => {
return this.setState({redirect: true, newCustomerId: result})
}).catch((result) => {
return this.setState({redirect: false, errorMessage: result})
});
}
Where the result is supposed to be the redirectUrl or ErrorMessage.
However, I'm keep getting the number 19 which is returned by my API.
I read online if I want to use promise in my component, i have to add return infront of $.ajax, if not "then" will be undefined.
What you can do is, create your own promise and put the ajax call inside it
Then call resolve and pass data that you want when then is called
resolve(data_passed_to_then)
Like this :
return new Promise((resolve,reject) => {
$.ajax({
...
success: function (data) {
let redirectUrl = '/client/' + data
resolve(redirectUrl);
},
error: function(xhr, status, err) {
...
// return dispatch({type: GET_CLIENT_FAIL, err});
reject(err);
}
})
})

How to get response status code in angular 1.5.6?

I was trying a lot of aproaches, some of them:
$http({
method: 'GET',
url: '/Url'}).then(function successCallback(response) {
}, function errorCallback(response) {
});
var req = {
method: 'GET',
interceptor: {
response: function (response) {
console.log(response)
var result = response.resource;
result.$status = response.status;
return result;
}
},
url: url,
headers: {
'Authorization': token
}
}
$http(req).success(function (data, status, headers, config) {
console.log(data, status, headers, config);
}).error(function (data, status, headers, config) {
console.log(data, status, headers, config);
});
And a lot of others with no result, so I really need help !!!
I would grateful for any help
The first approach looks close to what you need.
function successCallback(response) {
console.log('status code: ', response.status);
}
Currently the callback is empty so we are accessing response object and logging status code from it.
The first way is the more direct way of doing but I'm pretty sure that the response functions should be anonymous. Putting a console.log() in both will help.
$http({
method: 'GET',
url: '/Url'
}).then(function(response) {
console.log(response.status);
}, function(response) {
console.log(response.status);
});
If that doesn't work just put the console.log(response) in both to see what it gets you.
You can use httpinterceptor if you want to track all your requests :
myModule.factory('myHttpInterceptor', function ($q) {
return {
response: function (response) {
// do something with success response
// status in response.status
return response;
},
responseError: function (response) {
// do something with error response
// status in response.status
return $q.reject(response);
}
};
});
myModule.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});

TypeError: successFunction is not a function - angular.js:13529

bookController.js:
Getting two parameters from url 1) clientid 2) bookId
$scope.clientId = $location.search().clientId;
$scope.bookId = $location.search().bookId;
bookService.getSingleBook($scope.clientId, $scope.bookId,$scope.getResponse, $scope.ErrorResponse);
bookService.js
this.getSingleBook = function (clientId, bookId, successFunction, errorFunction) {
ajaxService.AjaxGet("http://localhost/samplewebsite/api/Book?clientId=" + clientId + "&bookId=" + bookId, successFunction, errorFunction);
};
ajaxService.js
this.AjaxGet = function (route, successFunction, errorFunction) {
blockUI.start();
setTimeout(function () {
$http({ method: 'GET', url: route }).success(function (response, status, headers, config) {
blockUI.stop();
successFunction(response);//getting type error
}).error(function (response) {
blockUI.stop();
errorFunction(response);
});
}, 1000);
};
successFunction(response) is getting data as response but when it returning the response it though an error TypeError: successFunction is not a function - angular.js:13529

ajax JSONP alway return Uncaught SyntaxError: Unexpected token :

I'm sending an ajax request to a remote api.
This is the response I receive when i'm just browsing to the URL:
{
"organizations":[],
"displayName":"Asaf Nevo",
"roles":[
{
"name":"provider",
"id":"106"
}
],
"app_id":"app_id",
"email":"email",
"id":"id"
}
Now the api is in a different ORIGIN so I needed to use JSONP in my call:
$.ajax(
{
url: KeyrockConfig.defaultInstanceUrl + uri,
type: method,
dataType: "jsonp",
data: params,
success: function (result, status, xhr) {
callback(result, status, xhr);
},
//TODO consider having a different callback for error
error: function (xhr, status, error) {
callback(error, status, xhr);
}
}
);
But I'm keep getting Uncaught SyntaxError: Unexpected token :
I tried to do:
$.ajax(
{
url: KeyrockConfig.defaultInstanceUrl + uri,
type: method,
dataType: "jsonp",
jsonp:false,
jsonpCallback: function (response) {
alert(response);
},
data: params,
success: function (result, status, xhr) {
callback(result, status, xhr);
},
//TODO consider having a different callback for error
error: function (xhr, status, error) {
callback(error, status, xhr);
}
}
);
But the alert was never called. What do I do wrong?

$http.post angularjs do not get in to success or error

My code is like this
$http.post("../services/myurl.aspx?Param=" + finaldata, '', { 'Content-type': 'text' })
.success(function (pricedata) {
alert (success)
})
.error(function () {
alert('we have failed to make a connection with the server. Please try after some time');
});
When I make this call neither success nor error happens.But the service is called. I am a little confused. can anyone point out what I am doing wrong?
You should use service to post data, here is how you could do it.
doSomething: function (data, url) {
return $http({
url: url,
method: 'POST',
data: data
});
},
and in your controller consume this service as
someService.doSomething($scope.MyData, $scope.Url)
.success(function (response) {
console.log("Success", response);
})
.error(function (data, status, headers, config) {
console.log("Error");
});
Try this simple code....
$http({
method: 'POST',
url: "../services/myurl.aspx?Param=" + finaldata,
})
.success(function (data, status, headers, config) {
var success="success"
alert (success);// or alert("success")
})
.error(function (data, status, headers, config) {
alert('we have failed to make a connection with server. Please try after some time');
});

Categories