Retrieving JSON from cookies - javascript

My cookie is set as follows
cookies[:cart] = "[{"id":"23","amount":"9"},{"id":"37","amount":"4"}]"
cookies[:cart] returns [{"id":"23"
and calling .each on cookies produces this abomination:
["cart", "[{\"id\":\"23\""] ["\"amount\":\"9\"}", nil] ["{\"id\":\"37\"", nil] ["\"amount\":\"4\"}]", nil]
I'm totally lost and can't really figure out what is going on (I suspect the ',' is doing some funny stuff).
So my questions are:
Is there a way around this?
Am I doing something terribly wrong by storing JSON in cookies?
if point_2 then, What would be a better way? (I'm mainly storing with Javascript and reading with RoR, and I figured parsing with the build in JSON functions would be easier.)

Your hash looks like this in ruby: [{id:23,amount:9},{id:37,amount:4}]
To turn it into json use [{id:23,amount:9},{id:37,amount:4}].to_json which will give you:
"[{\"id\":23,\"amount\":9},{\"id\":37,\"amount\":4}]"

Still not sure if what I'm doing is the right way to handle such situations but my supposed work around is as follows:
I call .replace(/,/g, '.'); in Javascript before storing the cookie, and I call .replace(/\./g, ','); after retrieving it in Javascript and .gsub(/\./, ",") after retrieving it in RoR.
Seems like a horrible workaround for me, but for the time being it is an OK solution for me as I'm 100% certain that there will never be dots used in this cookie.

Related

How to encode/decode URL parameters in javascript?

Before anyone jumps in and says, "Oh!! that's a bad idea", I know it is.
I want to keep both the key and value in the query string to be not easily visible to the end user.
I have something like this google.com/?category=textile&user=user1
I need to make it unintelligible like this: google.com/?kasjdhfkashasdfsf32423
Is there any way to achieve this in javascript. I have already seen this
I have already seen this
and this.
but I don't think encoding will solve the problem. Also, this code is entirely in client side. I know that it is not secure but I just need this is a naive, weak defense.
Please help.
Edit
I apologize if my question was not clear earlier.
The URL google.com/?category=textile&user=user1 is being passed on from a different application.
The values passed in the query string directly controls what is being displayed to the user. As is, anyone with no technical knowledge can easily change the value and view the data corresponding to a different category or user. I need to make this unintelligible so that it is not obvious. If a user is a techie and figures out the encryption used, then it is fine. I need a stop-gap solution till we have a better architecture in place
You can use base64. Javascript has native functions to do that :
alert(btoa("category=textile&user=user1")); // ==> Y2F0ZWdvcnk9dGV4dGlsZSZ1c2VyPXVzZXIx
and to reverse it :
alert(atob("Y2F0ZWdvcnk9dGV4dGlsZSZ1c2VyPXVzZXIx")); // ==> category=textile&user=user1
Be careful to read the doc if you have unicode strings, it's a little different : https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
If you don't looking for serious strong crypto, you can use ROT13:
http://en.wikipedia.org/wiki/ROT13
This is enough for slightly obfuscate keys/values in the your URLs.

How do I escape SQL query's single quotes for query generated in javascript/jquery in cartodb database?

I am using javascript/jquery to generate a sql query.
I have a sql query I'm generating and using inside a javascript/jquery script.
Something like this:
var storeName;
var query = "SELECT * FROM stores where storeName = '" + storeName + "';";
(storeName is generated through jquery when a user selects from html)
So when storeName is something like "Jackson Deli" the query runs just fine.
But then when storeName is "Jackson's Deli" it does not work and it seems to be because the apostrophe in Jackson's is treated like a closing quote. I know I can escape a quote by doubling it if I was hard-coding the query... so
SELECT * FROM stores where storeName = 'Jackson''s Deli';
should work. But I'm not hard-coding the query. Instead it's being generated by user input and may or may not have an apostrophe in the name. How would I go about escaping ' this character in this case? I would need it to work inside Javascript/jquery.
Would I need to write an if statement that looks for ' in storeName and replaces it with '' ??
Or is there another way to go about this?
EDIT:
Ouch! Normally, yes, I realize the perils of generating a query on the client side.
So here's some more context. I'm working with cartodb and following their documentation. Here's an example from their repo doing something similar to what I'm talking about (they have other examples too):
https://github.com/CartoDB/cartodb.js/blob/develop/examples/layer_selector.html
You can't run a query in cartodb that lets you modify data in any way -- you can only run queries that let you retrieve data. So I'm still thinking about what the best way to escape this quote character would be.
DO NOT GENERATE SQL ON THE CLIENT SIDE... EVER
That being said, if you are going to use a dynamic query, you are best off escaping the user input and binding it to a prepared statement on the server side.
If you post more details about which database (MySQL, Postgres, etc.) and what language you are using for server processing- you will get better answers.
Yes... I am fully aware this doesn't answer the question. Nobody should be creating code this way though.
Edit: Made the warning bigger for emphasis.
I see others have answered but I wanted to approach this question from a few angles.
The question you're asking is a good one. You recognize that the SQL doesn't work with single quotes. You realize that something needs to be escaped. These are a good starting point for a few considerations that will hopefully help you to architect software in a secure and maintainable way.
Never directly execute client code/content - Generating SQL or any kind of code/instructions (javascript, bytecode, compiled code) from a client is always a poor idea because it breaks a few critical concepts.
It's hard to maintain because you cannot control the input fully. Sure you could escape the SQL but that doesn't fix both strange case scenarios where you have other characters you didn't account for.
It isn't secure - Your relationship to variables, inputs, CGI params, file contents, database fields whose values came from the aforementioned list, or just about anything that came from a remote system, remote user cannot ever be trusted. Always check, sanitize and validate inputs. I can open the source to your page, see where you add a check for single quotes and change that and then execute the code to delete your records, have it email if certain stored procedures are available, run code on the SQL backend, drop databases (assuming the query runs under appropriate privileges.)
It blends/blurs the lines between client input/display and business logic. Research MVC, n-Tier development and other concepts for an introduction to the concepts of separating your business logic from display/inputs. This is critical not only for scalability and performance but also to reduce the change of issues such as this from causing critical security flaws.
Approach your software development from the bad-guys perspective - Instead of "How can I escape this string to make it work." try "How can I bypass the escape on this page to allow me to delete records, view things I should, etc.
Don't feel bad because the approach is wrong,learn from it. I see alot of comments about how you should never ever do this (and they're right) but many of us learned this lesson the hard way. We laugh at Little Bobby Tables because we've all written or had to support code that did this. The key is to understand the underpinning of why it's a bad idea and then use that in designing software. Welcome to the school of hard knocks. We're all graduates and thankfully you could learn from our comments rather than when somebody tinkers and corrupts, deletes or infiltrates your database and application.
To get you started on this journey may I suggest reading the following:
SQL Injections Explained
And as an added bonus XSS E.g. escaping OUTPUT that originated from an external system or person. for example a comment entry that contains Hi!!! <script>alert('Thanks to this site not escaping this output I get to run this code under your login. Thanks for the 4000 crates of free tshirts you just ordered for me');</script> how are you??? so that when you output it you get
Comments:Hi!!! <script>alert('Thanks to this site not escaping this output I get to run this code under your login. Thanks for the 4000 crates of free tshirts you just ordered for me');</script> how are you???
Which is "valid" HTML and the browser will execute it.
Final thoughts - Adopt the motto Trust but Verify and you'll be OK
FYI, CartoDB does not allow you to execute a query that changes something in the table, it's read-only.
Send data to your server first, then escape all chars that need to be escaped with addslashes() command (provided that you are using PHP).
addslashes() command on PHP
After you are done with eascaping characters, you can send your data to cartoDB using their API and your API key.
cartoDB does provide insert/update/delete tasks through its SQL API. See this link:
http://developers.cartodb.com/documentation/sql-api.html

Adapting Etherpad to react on new params

I try to adapt etherpad so it is only accessible if certain params are sent with the request.
For example I want a certain pad just to be displayed if there is a unique id provided like
http://myetherpad.com/thepadid?myparam=blub
Does anyone know where exactly I can parse the params? I searched all the js-files but didn't find exactly what I am looking for.
I found out that there is some kind of request object. You can access it like
request.params.padId
But I also don't know where to search for the implementation of this object.
I hope somebody can help me. Thanks :)
You could probably hack something into the code at https://github.com/ether/pad/blob/master/etherpad/src/etherpad/licensing.js#L153
But if all you need is some kind of password protection, there are easier ways. The easiest would be to use something that is built in to your web server, or to use the built-in pro functionality -- more on that on http://etherpad.org/2010/10/14/241/
(Your idea with using URL-parameters for password could be simplified; just use a complicated pad name and only those with the URL will find it. Having a "nice" pad name and adding a complicated password at the end doesn't protect the pad at all.)
For anyone with the same problem: You can get the GET-parameters via
request.headers['Referer']
It returns the URI the user called. But I still don't know how to do it properly (or get the POST parameters).

Where to start with JSON? (Closed)

I'm trying to get started with JSON. I've set the link to the JSON.js file using a script link, and I've set my objects using JSON, but it returns no results at all when I try to refer to the object. The JSON doesn't seem to be working at all. If anyone could point me in the right direction it'd be appreciated. I've looked all over the internet and haven't found much to help me.
Thanks guys. The JSON website helped me figure it out
Get Firefox, get Firebug, learn to use it to see what javascript is being loaded, and where the errors are.
Oh, and post some code.
Take a look-see at this
http://json.org/
basically you need to understand that json is a way to stream javascript object literals and arrays from a server to the client (and vice-versa). Open up firebug/webkit and in the console try
var obj = JSON.parse('{"test": 1}')
and you will see that obj is an object literal with a test property.
edit -- note that the link I provided mentions that json is a "is a lightweight data-interchange format" -- so its does not need to be javascript specific. But I think in practice you will get the most mileage using json in conjunction with javascript.
Here's a couple of links that might help:
http://secretgeek.net/json_3mins.asp
http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)

A working Json library for Javascript?

I went to http://www.json.org/js.html and downloaded the json2.js, thinking i'd be fine, afterall that site is on the top in a google search for 'json javascript' - also they have this really cool url :)
So i've been working a bit with it and it seemed fine, but now i start running into trouble with it - it simply won't parse certain stuff i encode with Newtonsoft's JSON .NET serializer. Ok so perhaps the .net seralizer messes up? Not how i see it - it produces a fine javascript string that looks like perfect json.
The problem comes when it has to encode a single quote ' and perhaps double quotes ".
Take a look at these examples (only parts of the full string)
{"Id":10651,"Text":"\'69"}
{"Id":184,"Text":"13\""}
Am I missing something? it's part of a bigger string and all put in a javascript variable like this
var jsonObject = '[{"Id":46,"Type":2,.....................
I'm thinking it has to escape the singlequote in the string to avoid conflicting with my wrapping of the string in single quotes, and escape the double quote to avoid conflicting with the json format?
So either i'm doing something wrong or the json2.js is not doing it right? Or yeah perhaps the .net json is messing up - i'm kinda thinking i'm messing it up, but i've been trying to do all sorts of stuff to help with the parsing like escaping/unescaping etc. before the serializing/deserializing.
Ok i solved the problem. Actually the hint Joel gave me in the comment on my question to try and eval it instead lead me to thinking i can trust this json i'm trying to parse/eval, and since i know it at the time of building the page, why not hardcode it into the webpage AS an object - no escaping of quotes or anything and no evaluating and best of all - no strings :P
So thanks to both you Joel and you torial :)
This may be a lead...
http://binnyva.blogspot.com/2006/10/invalid-json.html
And if you are serializing, perhaps protect yourself by serializing to &apos; and from &apos;.

Categories

Resources