React-rails store POST request response - ruby-on-rails

currently i used Ruby on Rails as my backend to serve API to my apps. And my front end i use React-rails gem (React.js) to get/post data and generate output. Both API and apps are on different server.
My problem here is, i cannot store response from POST request i made in react. How can i do so ? I am new in react btw.
What i want to do now is when user want to login the apps will POST request to API and get "auth_token" response. I want to store this "auth_token" response in header and access into dashboard. But i stuck now how can i store the auth_token ftw.
Below is my code for POST data :
var LoginBody = React.createClass(
{
handleClick() {
var username = this.refs.username.value;
var password = this.refs.password.value;
$.ajax({
url: 'http://localhost:3001/api/v1/users/central/signin?',
type: 'POST',
dataType: 'json',
data: { user_login:{email: username, password:password} },
success: (data) => {
this.setState({auth_token: data.auth_token});
}.bind(this),
});
},
getInitialState(){
return {
auth_token: []
}
},
If there's someone that could solve my problem and teach me how can i store in header in my apps i really appreciate it.

Just store them in local storage like:
localStorage.authToken = data.auth_token
And then whenever you need them in your future requests, just read as:
localStorage.authToken

Related

Guest Cart Selected Variations not working in Etsy API

When using the addToGuestCart method of the guestCart API endpoint the selected_variations parameter isn't working. I've tried sending the post data in JSON format with selected_variations being set to an array
containing two variations retrieved from the getInventory endpoint. The API request gives a 200 HTTP response but doesn't return any data, and the item doesn't appear in the Etsy cart. Making the same API call without the selected_variations set works fine. Can you please advise the correct format for including selected_variations in a call to the addToGuestCart endpoint?
This worked for me:
const guestCart_data = {
url: "https://openapi.etsy.com/v2/guests/:guest_id/carts",
method: "POST",
data: {
guest_id: guestId,
listing_id: listingId,
quantity: 1,
selected_variations: `{"47626759898" : "55055453743", "513": "86877352060"}`
// selected_variations: `{"<property_id>" : "<value_ids>", "<property_id>": "<value_ids>"}`
},
};

Perform call to Microsoft Graph Api for Intune approveApps

I am working on automating Intune to perform the Managed Google Play Application approvals, the API documentation I have been referencing is here:
https://learn.microsoft.com/en-us/graph/api/intune-androidforwork-androidmanagedstoreaccountenterprisesettings-approveapps?view=graph-rest-beta
Requirements for approveApps is almost identical to syncApps:
https://learn.microsoft.com/en-us/graph/api/intune-androidforwork-androidmanagedstoreaccountenterprisesettings-syncapps?view=graph-rest-beta
I can make the call to syncApps successfully but approveApps returns BadRequest. The only difference between the calls appears to be the body requirements.
It needs packageIds as a String collection and approveAllPermissions as a Boolean.
Please help me to successfully make a post to https://graph.microsoft.com/beta/deviceManagement/androidManagedStoreAccountEnterpriseSettings/approveApps
Minimum Reproducible Code:
var authHeader = {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json"
};
var appApprovePostData = JSON.stringify({
packageIds: ["com.bundle.example"],
approveAllPermissions: true
});
var appApproveOptions = {
method: "POST",
uri:
"https://graph.microsoft.com/beta/deviceManagement/androidManagedStoreAccountEnterpriseSettings/approveApps",
headers: authHeader,
body: appApprovePostData
};
response = await request(appApproveOptions);
The application needs to be prefaced with "app:". So, in your example, you need
var appApprovePostData = JSON.stringify({
packageIds: ["app:com.bundle.example"],
approveAllPermissions: true
Couple of thoughts -
If you get back a RequestID, can you post that?
Can you compare the request body submitted by the Azure Portal (F12 developer mode to get the request body trace) for the same app approval with your request body generated from code?
Dave

Sencha Touch 2 & Spring Security cross-domain login

I need use API of some server from Sencha Touch 2 app . For using this API I need authenticate on server.
So I already implemented login functionality :
Ext.Ajax.request({
url: 'http://192.168.1.2:8080/spring-security-extjs-login/j_spring_security_check',
method: 'POST',
params: {
j_username: 'rod',
j_password: 'koala',
},
withCredentials: false,
useDefaultXhrHeader: false,
success: function(response){
var text = response.responseText;
Ext.Msg.alert("success", text, Ext.emptyFn);
},
failure: function(response){
var text = response.responseText;
Ext.Msg.alert('Error', text, Ext.emptyFn);
}
});
But how I can call API , because after authentication I try call API but they already want authentication. Probably I need save JSESSIONID and added it to another request, but I don't know how I can do it.
I can't use withCredentials: true , so I need to find another solution.
How I can get Set-Cookies from response HTTP Header ?
I see in Chrome console, that JSESSIONID present in response header , so , i need get it.
Please, help me find any solutions.
You can use requestcomplete & beforerequest events to read response headers and to write request headers respectively. Here is sample code :
Ext.Ajax.on('requestcomplete', function(conn, response, options, eOpts){
var respObj = Ext.JSON.decode(response.responseText);
Helper.setSessionId(options.headers['JSESSIONID']);
}, this);
Ext.Ajax.on('beforerequest', function(conn, options, eOptions){
options.headers['JSESSIONID'] = Helper.getSessionId();
}, this);

AntiForgery and JSON incompatible?

I have been successfully using the AntiForgery option with Ajax in Orchard Modules for a while. Recently, I have been wanting to change from using the default ContentType = 'application/x-www-form-urlencoded; charset=UTF-8' to a JSON payload (ContentType='application/JSON').
As soon as I do this I get an exception thrown by ASP.NET 'A required anti-forgery token was not supplied or was invalid.'. OK, but how do I go about adding the __RequestVerificationToken while preserving JSON payload?
For reference, here is the code I'm using:
var config = {
url: url,
type: "POST",
data: data ,
dataType: "json",
contentType: "application/json; charset=utf-8"
};
$.ajax(config);
Controller (blows up with 'A required anti-forgery token was not supplied or was invalid.' before it gets here):
[HttpPost]
public ActionResult Update(ShoppingCartItemVM[] items)
{
// do stuff
}
Is this a limitation of the Orchard AntiForgery wrapper or of the MVC AntiForgery functionality? Or am I being stupid (again)?
Giscard is correct. I'll dig a bit deeper.
Note: Only the "post" results in orchard controller require the anti forgery token. So there is less of a requirement to remember that where using a "Get" in a request for json.
Often you will want to send more data than just the request token. In that case the 'data' object you send with your request must contain that __RequestVerificationToken value. In that case jQuery is useful for example:
var defaultPostValues = { __RequestVerificationToken:'#Html.AntiForgeryTokenValueOrchard()', id: 1, ..etc.. };
var myValues = { answers: [1,5,5,10] };
var data = $.extend({}, defaultPostValues, myValues);
var config = {
url: url,
type: "POST",
data: data ,
dataType: "json",
contentType: "application/json; charset=utf-8"
};
$.ajax(config);
The anti-forgery token can also be turned off per module definition (if I remember correctly?).
Module.txt
Name: Polls
AntiForgery: false
Author: Matt
... removed for brevity
Features:
Polls
... etc
However I would recommend using the antiforgery if your calls are within Orchard's modules, and disabling if and only if your data is needed else where by external requests. But I would recommend WebAPI within Orchard for that case but that creates a whole new story and probably likely moves far out of scope.
Maybe try this:
​data = {color: 'red', weight:'20lbs'};
// do some more work...
// Append the anti-forgery token to the POST values:
data['__RequestVerificationToken'] = '#Html.AntiForgeryTokenValueOrchard()';
// Make the .ajax() call:
var config = {
url: url,
type: "POST",
data: data ,
dataType: "json",
contentType: "application/json; charset=utf-8"
};
$.ajax(config);
If you are forming the json somewhere other than a razor view, you can do the #Html.AntiForgeryTokenValueOrchard() inside a razor view and pass it to a javascript object or variable so you can add it to the json via javascript.
EDIT: In addition to the method Matthew posted, you can also append the anti-forgery token to the POST values right before you make the AJAX call without using .extend(). Example: http://jsfiddle.net/JC66L/.

Phonegap App communicate with Rails 3 App using authentication

I am trying to write an iOS app using Phonegap to communicate with my Rails3 app. I cannot figure out how to handle authentication. I am using Devise/Warden in my Rails app.
I am able to login successfully in my iOS app via ajax but then subsequent calls are giving me a "Unauthorized". It appears that the session cookie isn't getting set in my iOS app.
How do I keep my iOS app aware of my rails authenticated session?
The answer was two fold.
First I had to add this to my ajax requests in the iOS app:
xhrFields: {
withCredentials: true
}
as in...
$.ajax({
url: ....,
type: "GET",
xhrFields: {
withCredentials: true
},
complete: hideLoader,
error: function(xhr,txt,err) {
// you can't get back anyways
window.location.hash = "";
},
success: function(data,status,res) {
window.location.hash = "";
}
});
Second I had to add this to my Application Controller in the Rails app:
def protect_against_forgery?
unless request.format.json?
super
end
end

Resources