Ember Authentication paradigm - ajax

Let's consider a trivial use case: User edits his profile + we have a RESTful server. This means we have to
send a token to the server and at the same time the new information about the editing. First, the server has to decode the token, and later to CRUD the DB. We want also to send back to the client a new json model about the new user profile.
BUT the token is really a huge one, so we must send it with a POST request. We can send the additional information as a query string at the same HTTP Post. Ember Data doesn't give us the ability to decide on sending a POST request. So we have to write a manual Ember.$.ajax. But how would we retrieve the new user model to Ember? We want to take advantage of Ember Data ORM's relationships and not reinventing the wheel.
Just for the record, the manual valid post request on the EditController is (after enabling CORS on the server)+(fBSignedRequest=> the token in my case):
Ember.$.ajax('http://myapi.com/api/usrEdit?Name='+myNewName, {
type: 'POST',
dataType: "json",
data: {fBSignedRequest: this.get("FBSignedRequest")},
success: function(data, response) {
console.log(data, response);
App.newUserProfile = data; //want it to become a part of the ED ORM
},
error: function (xhr) {
console.log('error')
}
});
This is really a trivial task to ask. Why couldn't I found any answer for over a month for this? How would you do the combination of a manual ajax and a build in Ember Data ORM?
If you have another idea about this whole authentication, I will be glad to hear.
Thank you a lot!

You could simply push the model you retrieve via your request into the store. See http://emberjs.com/guides/models/pushing-records-into-the-store/

Related

Securing web api using random session number

I am making a web API/Rest API in MVC where each API takes one parameter called user_session
So when a user logs in, I generate a 10 digit session and pass it back to user which needs to be given as input for any subsequent API calls.
Here's what my typical code looks like:
$.ajax({
url: '#Url.Action("GetUserDetail", "myapi")',
type: "GET",
data: { UserID: '#user.user_id', SessionID: '#user_session' },
dataType: "json",
success: function (response) {
}
})
My question is, is this the right approach or is there a better way of doing it? Is it secure?
You can very well use the HTTP Cookies for remembering the session instead of manually passing it as a param for every request.
I’ll give very short explanation on this topic.
Server sets a cookie when a user logs-in.
This cookie will be sent to all the api calls as it is defined as a HTTP cookie.
Server can validate or know about the session using this cookie value in header of the request.

JSON or Form Data? What's the preferred way to send data back to the server

I'm messing around with Django and AngularJS, attempting to send data back to my server using the $http resource. It looks like I could do this by either posting the data back as a form by setting the content-type as follows:
$http({
url: url,
data: form_encoded_data,
method: 'POST',
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
});
Or post back JSON in the request body with something like this:
$http.post(url, json_data)
.success(function(data, status, headers, config) {
...
}
In the first method, I can get access to the form data in my Django view via request.POST, and in the second, I can get access to the JSON via request.body. They both seem to work, but what's considered best practice?
I'm not sure what the convention for JSON data is. What I am sure of is that there is a convention for getting form data. In the absence of a compelling reason to use JSON, I would tend to think it's better to stick with the request.POST
I would go with using a form, it just makes sense intuitively and it is what I have used every time.
I prefer to use the $http service that accepts an object literal for configuration:
$http({method:'POST',url:'api/customers/add', data: customer})
.success(function(data) {
...
});
The result is promise object where you can immediately call .success. Its cleaner and easier to read IMO.
Note: customer is typically a data-bound object literal in JSON notation, but it does not have to be.

Using web2py, jQuery and ajax, how do you post to a database?

Using web2py I am trying to use ajax to put data into a table in my database, but I'm needing a bit of help.
Here is the function I am using (it currently has dummy data in the data section, rather than being passed data from a form):
function submitData(){
$.ajax({
type: "POST",
url: "requests",
data: {
id: 1,
user_id:111,
bottle_image:'',
bottle_name:'JJjman',
bottle_description:'Lol',
request_creationDate:'2000-01-01',
request_expiryDate:'2003-08-08',
request_fulfilled:false
},
success: function(){
alert('Posted data');
}
});
}
I have a html button with this function attached to its 'onclick', but at the moment all it does is reload the page and not pass any data onto the database. The success alert is also coming up.
Firebug is saying that the POST does contain all that data, but I'm not sure if the POST is actually going anywhere..
Am I missing any steps needed to actually pass this data to the database? Or could this just be that my data isn't all the right type for the database?
Cheers guys
Simply sending a post from the browser won't do anything on the server unless you have code on the server to handle the data and insert it into the database.
I strongly recommend you read through the relevant parts of the book to learn how to do this. The Overview chapter provides an introductory tutorial, including building an image blog that involves modeling a database table and creating a form to post records to that table.
Review the DAL chapter for details on modeling your database, the section on SQLFORM for details on creating forms associated with database tables, and the sections on ajax and components for details on using Ajax to post forms.
The easiest way to do what you want would be something like this:
In /models/db.py:
db = DAL('sqlite://storage.sqlite')
db.define_table('bottle',
Field('user_id')
Field('bottle_image'),
Field('bottle_name'),
Field('bottle_description', 'text'),
Field('request_creationDate', 'date'),
Field('request_expiryDate', 'date'),
Field('request_fulfilled', 'boolean'),
format='%(bottle_name)s')
In /controllers/default.py:
def index():
return dict()
def add_bottle():
return dict(form=SQLFORM(db.bottle).process())
In /views/default/add_bottle.load:
{{=form}}
In /views/default/index.html:
{{extend 'layout.html'}}
{{=LOAD('default', 'add_bottle.load', ajax=True)}}
Then go to /yourapp/default/index, and you will see a form, which will post records to the database via Ajax.

Ajax security: how to be sure that data sent back to the server is generated by my code?

I apologize in advance if this question sounds naive to you.
The problem is this: I have this function and I want the callback function to send the "response" back to my server via Ajax.
function FbInviteFriends()
{
FB.ui({
method: 'apprequests',
message: 'Hi! Join me on XXXXXXX'
},
//My callback function
function(response){
//Send response to my server
}
Is there a way to check that the response I'm going to receive server-side is actually the same I got when the callback function is called and that the response hasn't been modified on the client-side by the user?
Thanks!
There's a few ways, but all of them fall on the same principle - you can never know for sure, so treat it with a grain of salt and validate.
That said, one way to put at least one usage constraint may look like this:
Page accessed: Generate a token GUID. Render it at the client.
Store in the user session the moment it was created/used, together with user profile.
Client appends the token to all Ajax posts.
Token is validated at the server; must match SessionID, user profile (if any), and maximum usage timeout.
If it fails validation, abort the operation.

django csrf in ajax not work

I have a form and post it to server using json data,and the server save it in database. here is my code
function saveChanges() {
var items = [];
$('ol.item_list > li.item').each(function(){
items.push(getItemData($(this)));
});
var csrftoken = $.cookie('csrftoken');
$.ajax({
url : '',
type: 'POST',
headers : {"X-CSRFToken": csrftoken},
data : $.toJSON(items),
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);
},
});
}
The problem is, I call saveChanges (via a button) twice, all return 200 http ok. So I got duplicate data in database. Should the csrf token provent duplicate sumbit? How can I fix it?
You should prevent double submission by taking care to properly
lay out your script execution flow & script structure so that you prevent that.
No, the CSRF token doesn't prevent duplicate submit of any kind. Its purpose is to prevent Cross Site Request Forgery, nothing else. It creates a token so nobody can trick you in submitting requests you don't intend to do.
If you want to prevent duplicate submits, a way would be to disable the submit button after it is clicked once. However, this is by no means a good solution, since JavaScript runs on client side and can easily be manipulated (e.g. via Firebug). So duplicate submits would still be possible, just not that obviously.
A better way is to do validation in your server-side Python code. You can check if the submitted data is already in the database and, if so, ignore the request or optionally return an error message. This makes sure that even by fiddling around with the JavaScript, an evil-meaning user cannot save data twice.
I would use both of these means, the first one simply to tell the user that he should not try to submit the same data twice - that's just an interface perk.

Resources