Posting a single quote into a Postgres database - javascript

I am currently trying to take a string submitted from a form and make an api call to submit the message into the Postgres data base. Everything works sucessfully except when dealing with single quotes. The simplified code is:
const message = form.get('message').replace(/\'/g, "E\'\'")
urlData = ...&reasoning=${message}
methodApi = ...
axios.get(methodApi + urlData);
I am currently using the .replace function above to follow the format when dealing with single quotes. And it works but the message submitted to the database has the E present
example value from db after submission:
testing single quote: E'
When I do not use the .replace function the api gets cut off and wont submit, also just replacing a single quote with \' does not work and two single quotes does not work either.
So basically I've made progress and am trying to have the "E" not show up in the db.
Most likely a simple fix but each time I push the code to the dev environment to test the db it takes about 20 minutes, so asking here while I work on it will save some time.
Thanks and let me know if this is confusing I will be sure to respond asap!

Related

Remove last 3 letters of div (hidde also in browser page source)

this is my HTML
<div id="remove">Username</div>
and this is my JS code
function slice() {
var t = document.getElementById("remove");
t.textContent = t.textContent.slice(0, -3);
}
slice();
Username load from foreach
{foreach from=$last_user item=s}
{$s.date}
{$s.username}
{/foreach}
This code working and remove 3 letter but when right click on browser and look at page sources i can see "Username" !
I need remove three letter because of privacy and security .
something like
*** name or usern ***
Thank for help me !
The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know.
You'll need to fix this on your backend - either hard-code in
<div id="remove">Usern</div>
or, for a more dynamic approach, use a template engine (or whatever's generating the HTML) and look up how to change strings with it. For example, in EJS, if user is an object with a username property, you could do
<div id="remove"><%= user.username.slice(0, -3) %></div>
Changing the content only with client-side JavaScript will not be sufficient, if you wish to keep some things truly private.
With Smarty, you can define a modifier that takes a string and returns all but the last three characters of it.
function smarty_modifier_truncate_three($string)
{
return substr($string, 0, -3);
}
and then in your template, replace
{$s.username}
with
{$s.username|truncate_three}
If you want only the first three characters, it's easier because you can use the built-in truncate.
{$s.username|truncate:3}
JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters.

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:
var UserName = #Request.QueryString["UserName"];
But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:
var UserName = ANT -- ANT 37690 / THIRD PARTY
So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS?
The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].
One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.
var UserName = #new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);
The shorter version of this for a string is:
var UserName = "#System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";
or overloaded version that wraps the result in double quotes:
var UserName = #System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);
You need to include quotes for the value.
var UserName = "#(Request.QueryString["UserName"])";
Otherwise the name will come through verbatim in your code and cause the problems you are seeing.
There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.
If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.
var sanitizedJsVariable = "#System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

"Fixing" JSON coming out of MySQL

I'm fetching JSON code stored in MySQL and it has extra slashes, which I have to remove in order to parse it in JavaScript, after I print it on the page. Right now I'm doing the following:
$save = str_replace("\n", "<br>", $save); // Replace new line characters with <br>
$save = str_replace('\\"', '"', $save); // top-level JSON
$save = str_replace('\\\\"', '\"', $save); // HTML inside top level JSON
$save = str_replace('\\\\\\\\\\"', '\\\\\"', $save); // HTML inside second level JSON
Here is an example JSON code, as it comes out from MySQL:
{\"id\":2335,\"editor\":{\"selected_shape\":\"spot-7488\"},\"general\":{\"name\":\"HTML Test\",\"shortcode\":\"html-test\",\"width\":1280,\"height\":776},\"spots\":[{\"id\":\"spot-7488\",\"x\":9.9,\"y\":22.6,\"default_style\":{\"use_icon\":1},\"tooltip_content\":{\"content_type\":\"content-builder\",\"plain_text\":\"<p class=\\\"test\\\">Test</p>\",\"squares_json\":\"{\\\"containers\\\":[{\\\"id\\\":\\\"sq-container-293021\\\",\\\"settings\\\":{\\\"elements\\\":[{\\\"settings\\\":{\\\"name\\\":\\\"Paragraph\\\",\\\"iconClass\\\":\\\"fa fa-paragraph\\\"},\\\"options\\\":{\\\"text\\\":{\\\"text\\\":\\\"<p class=\\\\\\\"test\\\\\\\">Test</p>\\\"}}}]}}]}\"}}]}
And here is how it's supposed to look in order to get parsed correctly (using jsonlint.com to test):
{"id":2335,"editor":{"selected_shape":"spot-7488"},"general":{"name":"HTML Test","shortcode":"html-test","width":1280,"height":776},"spots":[{"id":"spot-7488","x":9.9,"y":22.6,"default_style":{"use_icon":1},"tooltip_content":{"content_type":"content-builder","plain_text":"<p class=\"test\">Test</p>","squares_json":"{\"containers\":[{\"id\":\"sq-container-293021\",\"settings\":{\"elements\":[{\"settings\":{\"name\":\"Paragraph\",\"iconClass\":\"fa fa-paragraph\"},\"options\":{\"text\":{\"text\":\"<p class=\\\"test\\\">Test</p>\"}}}]}}]}"}}]}
Please note that I have HTML code inside JSON, which is inside another JSON and this is where it gets a bit messy.
My question - is there a function or library for PHP (for JS will work too) which covers all those corner cases, because I'm sure someone will find a way to break the script.
Thanks!
The short answer, which is woefully inadequate, is for you to use stripslashes. The reason this answer is not adequate is that your JSON string might have been escaped or had addslashes called on it multiple times and you would have to call stripslashes precisely once for each time this had happened.
The proper solution is to find out where the slashes are being added and either a) avoid adding the slashes or b) understand why the slashes are there and respond accordingly. I strongly believe that the process that creates that broken JSON is where the problem lies.
Slashes are typically added in PHP in a few cases:
magic_quotes are turned on. This is an old PHP feature which has been removed. The basic idea is that PHP used to auto-escape quotes in incoming requests to let you just cram incoming strings into a db. Guess what? NOT SAFE.
add_slashes has been called. Why call this? Some folks use it as an incorrect means of escaping data before sticking stuff in a db. Others use it to keep HTML from breaking when echoing variables out (htmlspecialchars should probably be used instead). It can also come in handy in a variety of other meta situations when you are defining code in a string.
When escaping data input. The most common escaping function is mysqli_real_escape_string. It's very important to escape values before inserting them in a db to prevent sql injection and other exploits but you should never escape things twice.
So there's a possibility that your code is double-escaping things or that addslashes is getting called or something like magic_quotes is causing the problem, but I suspect it is another problem: some JS code might be supplying this JSON not as a proper JSON string, but one that has been escaped so to define a string within javascript.
If you take your example JSON string above, and slap some quotes around it:
var myJSON = "<put your string here>";
then SURPRISE your javascript is not broken and the var myJSON contains a string that is actually valid JSON and can be parsed into an a valid JSON object:
var myJSON = "{\"id\":2335,\"editor\":{\"selected_shape\":\"spot-7488\"},\"general\":{\"name\":\"HTML Test\",\"shortcode\":\"html-test\",\"width\":1280,\"height\":776},\"spots\":[{\"id\":\"spot-7488\",\"x\":9.9,\"y\":22.6,\"default_style\":{\"use_icon\":1},\"tooltip_content\":{\"content_type\":\"content-builder\",\"plain_text\":\"<p class=\\\"test\\\">Test</p>\",\"squares_json\":\"{\\\"containers\\\":[{\\\"id\\\":\\\"sq-container-293021\\\",\\\"settings\\\":{\\\"elements\\\":[{\\\"settings\\\":{\\\"name\\\":\\\"Paragraph\\\",\\\"iconClass\\\":\\\"fa fa-paragraph\\\"},\\\"options\\\":{\\\"text\\\":{\\\"text\\\":\\\"<p class=\\\\\\\"test\\\\\\\">Test</p>\\\"}}}]}}]}\"}}]}";
console.log(JSON.parse(myJSON)); // this is an actual object
The key here is to examine the point of entry where this JSON arrives in your system. I suspect some AJAX request has created some object and rather than sending valid JSON Of that object, it is sending instead an escaped string of a JSON object.
EDIT:
Here's a simple example of what happens when you have too many encodings. Try running this JS in your browser and observe the console output:
var myObj = {"key":"here is my value"};
console.log(myObj);
var myJSON = JSON.stringify(myObj);
console.log(myJSON);
var doubleEncoded = JSON.stringify(myJSON);
console.log(doubleEncoded);

Data passed to other pages via hyperlink is being cut off

I have a form that contains 2 <select>, the first select auto-populates itself upon page load, while the second select populates itself based on the choice selected in the first select.
To accomplish this, whenever the the select's state changes, the selected value in the first would be passed to a seperate page where it is used to populate the 2nd <select>
Problem
The selected value( Food & Beverages in this case) which is passed through the url is being cut off halfway, causing an incomplete string to be send to the processing page for the 2nd , which causes it to be unable to run.
Steps taken to identify the issue
I've echoed the values that is passed through the url and only got "Food", with the rest of the string cut off. I've tried replacing the string values to Food and Beverage, and the whole thing works perfectly, leading me to conclude that the string is being cut off due to the ampersand(&) sign which causes the computer to treat the part of the string after the ampersand as another value to be passed through the URL.However, as i did not assign it to a variable, it is not being passed through.
Question
Is there any way for me to pass the value without it being cut off?
Code Extracts:
Processing Page
<?PHP
include("cxn.inc");
$query=$cxn->prepare("SELECT * FROM `BusinessSubCategory` WHERE `BusinessCategory`=:businesscategory");
$query->bindValue(":businesscategory",$_GET['category']);
$query->execute();
$count=$query->rowCount();
if($count>0)
{
echo"<option id='subcategory' value=''>Please select a SubCategory</option>";
while($result=$query->fetch(PDO::FETCH_ASSOC))
{
$subcategory=$result['BusinessSubCategory'];
echo"<option id=$subcategory value=$subcategory >$subcategory</option>";
}
}
else
{
echo"<option id='subcategory' value=''>Error,fetch query not run. </option>";
}
?>
JQuery Code
$(document).ready(function(){
$('#BusinessCreateCategory').load('getbusinesscategory.php');
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
window.location.href='getbusinesssubcategory.php?category='+category;
});
EDIT:Tried encodeURIComponent, but the data is not being encoded as i can see from the url of the processing apge that it is cut off at the ampersand.HOWEVER, if i were to manually enter the url as a string and then code it using encodeURIComponent, it works wonderfully.CAn anyone shed some light on why i am unable to encode $('#BusinessCreateCategory').val(); ? Thanks!
E.gThis works
var category="Food & Beverages";
var encoded =encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
E.g This does not
var category=$('#BusinessCreateCategory').val();
var encoded= encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
If it helps, the data i am trying to pass through the url is taken from my database.
You need to encodeURIComponent the value for category before using it in a URL.
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
var encoded = encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
});
Ampersand is a special character that garbles the URL you are trying to pass. Encoding the value should allow you to treat it as a single value.
There is a browser limit to how many characters can pass through. Do you have an example of the complete string that you are trying to pass? I would initially suspect that this could be an encoding issue.
encodeURIComponent to encode the string being passed.
The value should be encoded but when you query your db it might look for exact match, in case you fail to see any output via the encoded string use decodeURIComponent to decode the string before passing it to db. Check the output at phymyadmin before your formally put the code.

Getting the thread id in Gmail

I'm looking for a way to figure out how to get the thread id for a particular email on Gmail, just before it is sent OR at the point where the send button is clicked.
Currently, I'm working with Javascript in order to scrape other items off the email and store them in a record which works pretty well for everything except the thread id.
The thread ID can be found after I send the email within the URL:
https://mail.google.com/mail/u/0/?shva=1#inbox/13ddda647539dcca
In this case, the thread id (if I'm right - is 13ddda647539dcca.
Any help would be appreciated.
If anyone is still interested - You can retrieve the thread id after the email is sent by observing the that appears at the top of the page. This span contains a link which has an attribute named 'param' which has the thread-id.
You could try:
var matched = window.location.hash.match(/[A-Za-z0-9]+$/);
if (matched) {
// Found alphanumeric string at end of hash
}
And you can get the value with matched[0].
window.location.hash should only grab the "#inbox/13ddda647539dcca" part. Then the regex is to match against any alphanumeric characters at the end of the string. So the fact that "inbox" is separated from the thread id by a "/" is important.
Of course, all of this depends on the reliability of Gmail keeping the URL following the same convention as it currently seems to be.

Categories

Resources