Quick AJAX / JSON security question - ajax

In a form I have I want to be able to check whether the intended email address or username is unique as part of the validation process
I have created a JSON file with PHP from database data to work with JavaScript validation but the problem is that anybody can see the JSON file
Is there a way around this and still be able to use this method?

In short, no.
Why don't you just create an ajax function that takes in the email address and returns a boolean indicating whether it's unique by querying the database? JQuery has great AJAX capabilities: http://api.jquery.com/category/ajax/

Related

Google Apps Script - Query Parameters from opening form passed when submitting form

Current Situation
I have a Web App with an example URL that looks like this
https://script.google.com/a/domain.com/macros/s/Adlksjflf09_LEg8kdlf9/exec?ID=1
This Web App has a doGet(e) function that redirects it to a Google Form URL. Using the example above, it would look like this
https://docs.google.com/forms/d/e/1FAIpQLSfi8jWUK2N4y03N4YYJ9p8Cyr2x06b1C6WgS_TcV98WM_ACtQ/viewform?ID=1
This ID field does not pre-fill any of the questions in the Google Form. Essentially, it's meant to hold information.
When a user submits a form response, I'm combining information from the query parameters as well as the form response and sending it as a payload to a webhook URL.
How I do that is by using CacheService. When a user opens the first URL, the doGet(e) function stores the e.queryString as a Hash in the cache. Then when a user submits the form, I can get the information from the cache and combine it with the formResponse.
The issue I have now is related to concurrency. There will be a case where more than 1 user has opened the first URL. This results in Hash['queryString'] to be overwritten in the cache which is not what I want.
Actual Question
Is there a way to take query parameters from an onFormSubmit from a form and combine it with the form response without using CacheService since my current solution does not support concurrency?
From my understanding, the onFormSubmit trigger doesn't have an e (event variable) for me to do something like a e.queryString to get the query parameters. I may be wrong, need someone to confirm.
OR
Is it possible to cache information in such a way that I can keep track of whose query string is whose and then pull the appropriate information when submitting the form.

Symfony2 : Best way to check form, client side

I'm developing a form with Symfony2 : several text inputs and one file input (for one picture). I have defined some asserts (maxLength, minLength...) in my entity in order to check the form (isValid).
My problem is : if the user puts bad data in text input (text too long or too short...), he still can submit the form, and error and printed but the user have to re-choose his picture.
As I think it's impossible to keep the picture in the form after bad validation, I should maybe check the form in client side (javascript), before submit.
So, is there an automatic way to do this (to forbidden submit until data are correct)? Can we get the assert minLength, maxLength value in twig ?
Thank you !
Ben.
You can use js validation before submitting the data, using some js form validation tools, but this way you need the replicate the validation logic from the server, so if validation rules changes, you need to modify on both server and client side. I recommend this method to reduce the traffic between client-server.
If you don't want this, use ajax form submitting (example here). You still validate the form using symfony, but the page won't refresh, so you won't lose the attached file. But this generates additional traffic to server, and you also need to implement error displaying using javascript.

Dynamically add form to formset in Django and submit with AJAX

I have read a lot of answers relating to how to dynamically add forms to an model formset in Django and can successfully implement that. However, I would now like to submit the formset with AJAX. This is mostly working now but I have an issue that I can't find a solution to in any other answer:
If you dynamically add a form to the formset, you give it a new form id number that is one larger than the maximum the form currently has and you also increment the management TOTAL_FORMS count by one. The newly added form then saves successfully as a new object.
I am trying to submit by AJAX so the user can continue editing without having the page refresh. The formset saves fine but any dynamically added forms are now existing objects. To account for this I need to increment the INITIAL_FORMS count on the management form when the save is successful. Easy enough. However, I've also realised I need to give the newly created objects an ID since they now exist in the database.
How can I get my view to tell me the ID of the new objects in its response to the AJAX call? Or is there a better way of looking at this?
Django forms and formsets are intended for classic browser-based posting of data. Though they can definitely be made to work with Javascript, the more you want to part from the normal behavior, the more complex it gets.
Depending on your requirements, you might start thinking about dropping it and switch to Javascript + REST endpoint. Of course, if you need progressive enhancements and you are required to have it work without javascript, that's not an option.
In any case, you want to have a customized view for posting from JS, so that you can get the result back and parse it easily in your AJAX handler. Probably some JSON.
There are several approaches you could take.
Have your AJAX send data to a different URL. This is pertinent if you have an API or are planning to build one at some point. So your form, when submitted normally, will do its old-style processing but your AJAX will talk to the API endpoint instead.
For instance, your form send to https://example.com/myform, but your Javascript code talks to REST api at https://example.com/api/v1/mymodel/ (sending PUT, POST and DELETE requests as appropriate).
Or if you don't have an API and building one seems overkill, you may just alter your view so it formats its output differently depending on whether the data is being submitted in the regular way or using AJAX.
You'd go about it like this:
class MyFormView(.....):
def render_to_response(self, context, **kwargs):
if self.request.is_ajax():
return self.render_to_json(context, **kwargs)
return super().render_to_response(context, **kwargs)
def render_to_json(context, **kwargs):
data = {
# see below!
}
return HttpResponse(
content=json.dumps(data).encode('ascii'),
content_type='application/json',
)
This is just an outline. You need to ensure is_ajax will detect it properly (see django doc). And you need to properly build data from context: extract the things you want to send back to your JS code and put them in the dict.
You will find it's manageable if you just do this for one, maybe two views in your project, but very quickly you'll want to have a small API instead, especially given how easy it is to build one with packages such as Django REST framework.
In your view, where you save the object, AFTER the save, the object.id will contain the new id for the object, which you can return via json or however you want in your ajax response, and then yes you will need to fill that into the formset row so that it will be submitted the next time.
One thing you have to watch out for is that django expects all existing rows to be at the top of the formset, and any new rows to be at the bottom. Otherwise, the formset save will complain about missing id's. So if you're doing any kind of sorting in your javascript, you can't do that.. unless you do quite a bit of fixing of all the field names etc in the formset. The formset code uses the numbers in the management form to determine which rows to insert and which rows to update, it does not do it on the basis of whether or not an id is present. Unfortunately...

How to avoid "The action you have requested is not allowed" error with Knockout postJson function call

CodeIgniter gives an error "The action you have requested is not allowed." when it fails the check for CSRF. As I understand it, this means the POST is missing the hidden token from the form that proves that an attack is not being done.
The token is generated automatically with a call to the CI form_open function.
In my case, I'm using Knockout to post the contents of a ViewModel for saving, like this:
ko.utils.postJson($("form")[0], self.pages);
I've found solutions elsewhere that simply turn off the CSRF setting for the specific page, but that doesn't seem like a good solution.
Presumably because the token is not being received, the postJson call is not submitting the existing form. Is there a way to either submit the required token along with the JSON data or submit the JSON data with the existing form?
try to use form_open() and form_close
all form helper functions that will help.
or: I think it's from time zone difference as the Security class depends on time for hashing.

Client side to server side calls

I want to change the list of available values in a dropdown depending on the value selected in another dropdown and depending on values of certain fields in the model. I want to use JQuery to do this. The only hard part is checking the values in the model. I have been informed that I can do this using Ajax. Does anyone have any idea how I will approach doing this?
AJAX is indeed the technology your looking for. It is used to sent an asynchronous request from the client browser to the server.
jQuery has an ajax function that you can use to start such a request. In your controller you can have a regular method tagged with the [HttpPostAttribute] to respond to your AJAX request.
Most of the time you will return a JSON result from your Controller to your view. Think of JSON as something similar to XML but easier to work with from a browser. The browser will receive the JSON and can then parse the results to do something like showing a message or replacing some HTML in the browser.
Here you can find a nice example of how to use it all together.

Resources