How to escape mysql special characters with sockets.io/node.js/javascript - javascript

I am using sockets.io to insert user-generated messages into MySQL, but I'm running into issues inserting records with an apostrophe. I've been trying to use the replace() method on the client side script, but the input text is passing with the apostrophe.
socket.on('refresh feed',function(msg){
str=msg.replace("'", "\'");
alert(str);
$("#chtxt").append(str + '<br />');
});
The above attempt will alert any string without the special character, but does not alert when it exist. I believe that I'm actually alerting after the message has been sent to sockets.
So, I tried adapting this code which watches for the enter key press to also watch for the apostrophe, with no luck there either.
$('#omnibox').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('input[name = "clicky"]').click();
return false;
}
if(key == 222) // the apostrophe key code
{
alert('Apostrophe!')
return false;
}
});
I researched the question of how to replace special characters for MySQL using javascript but found outdated stacks explaining why client-side validation for this is not a good idea.
That's fine. If I shouldn't do this client side, I need to know then how to do it in my server.js node script, then. It is still javascript, so a solution on either side, provided it's secure would be great.
Server-side code:
var add_status = function (status,callback) {
pool.getConnection(function(err,connection){
if (err) {
callback(false);
return;
}
connection.query("INSERT INTO `videosub` (`url`) VALUES ('"+status+"')",function(err,rows){
connection.release();
if(!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
Thanks!

Don't do it
You are asking about the wrong solution to the problem.
To replace the apostrophes with backslash-apostrophes you might use:
str = msg.replace(/'/g, '\\\'');
but you should not do that. I am only providing that info because that's what your question asks about but read below.
Why it's a bad idea
You shouldn't do it on the client side and you shouldn't do in on the server side either. If avoiding SQL injection vulnerabilities was a simple matter of replacing apostrophes with backslash-apostrophes then it wouldn't be an issue. Unfortunately it's more complicated.
Having the info that you provided it's even impossible to tell whether backslash-apostrophe would even do what you expect in the first place without seeing your code that actually makes the database queries. But it doesn't matter because you should never ever do that. Never. See those answers to see why - those questions are not about SQL injections but the code examples included SQL injection vulnerabilities and the answers explain it:
cannot use backtick when using nodejs 7.3.0
Node js - Promise Rejection Warning when process a lot of data
Is it possible to listen for object instantiation in Node.js?
Obligatory comic strip
What you should do instead
That having been said, you didn't tell what module you're using to query the database but no matter if you're using the mysql module or Sequelize or anything worth its salt, there should always be a mechanism of interpolating variables in a safe manner without manually escaping and concatenating the strings.
Examples
You didn't show even a single line of code that is relevant here so I cannot tell you how to fix it but consider this example:
Unsafe:
connection.query(
"SELECT * FROM player WHERE nick = '"
+ data.login + "' AND pass = '" + data.pass + "'",
function (err, rows) {
//...
}
);
Still unsafe, complex, unreadable, unmaintainable and unreliable:
connection.query(
"SELECT * FROM player WHERE nick = '"
+ data.login.replace(/'/g, '\\\'') + "' AND pass = '" + data.pass.replace(/'/g, '\\\'') + "'",
function (err, rows) {
//...
}
);
Safe and simple:
connection.query(
"SELECT * FROM player WHERE nick = ? AND pass = ?", [data.login, data.pass],
function (err, rows) {
// ...
}
);
More info
For more info see the docs:
https://www.npmjs.com/package/mysql
http://docs.sequelizejs.com/en/v3/

Related

Javascript Logging function

For a little project I'm coding besides my job I wanted to make a log function so I can output simple things into a textfile like the user input and possible errors that occured.
I wanted to make this log a simple .txt.
The problems I ran into were the following:
I want to check if the file already exists if not, create a new one;
Then when the file exists I want to write below the existing contents.
This is what I got so far:
/*
Form:
\r\n
\r\n *** logged (<dd.mm.yyyy> || <hh:mm:ss>) ***
\r\n
\r\n <pMessage>
\r\n
\r\n *** log end ***
*/
function log(pMessage)
{
var logPath = "../../Logs/SiteLog.txt";
}
I know it is not much because I haven't done anything there yet. So i basically need three things: Checking if the file exists, creating a file, editing the file.
Thanks in advance for your help.
If this is client side, the browser will prevent you from writing to the file system. If this is strictly for your own testing purposes locally, you could write to window.localStorage
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This would allow you to read and write from a local storage that the browser caches based on domain
function read (name) {
return window.localStorage.getItem(name)
}
function write (name, value) {
var report = window.localStorage.getItem(name) + '\n' + value
window.localStorage.setItem(name, report)
return report
}

Express.js - How to send alert from Express to Client using res.render? Not res.send

I want to send the alert message to client.
So, I found that.
res.send(<'alert("XXX!!!")');
In this way, I didn't use res.render();
I want to use together.
Or
I want to send alert message using res.render();
How do I this?
This is the code.
if (err)
console.log(err);
if (flag === 1) { //함수 이름 중복
try {
//res.send('<script>alert("함수 이름 중복!")</script>');
LoadDB(res);
} catch (exception) {}
}
else {
//(4) 데이터베이스 insert 쿼리
var query = "insert into automation_script set ?";
conn.query(query, set, function (error, result, fields) {
if (error) {
console.log('Insert_DB error' + error);
} else {
try {
LoadDB(res);
} catch (exception) {}
}
});
}
//(5) 데이터베이스 해제
conn.end();
Thanks you.
res.send(<script>alert("your alert message"); window.location.href = "/page_location"; </script>);
There are a lot of problems here. For one I'm not sure you understand how try catch blocks work. You have an unnecessary amount of ifs that aren't being handled too. Those problems aside, the answer to the question you asked is a websocket. From the looks of your code and question, I think what you're really looking for is how to send a response from an http get request in express. There are many ways to solve the problem you are asking to be solved. From the code I see above I don't think you have a good understanding of client/server models and It would be to your benefit to read up on how http works. I also can't answer your question because the code snippet you pasted does not provide enough context to answer your question. Most importantly though, alert is not a function in node. calling alert does nothing. In fact when you do res(alert("something")), if alert is defined in your global namespace (I hope it isn't), you are sending back undefined. There is such a thing as isomorphism, however, web api functions are exclusive to the client. I hope that helps.
res.send("alert("your alert message"); window.location.href = "/page_location"; ");
same answer as M.HUSSAIN only he forgot the string quotes aroud the expression

Express API - Verifying req.body elements

Am building an api using express and node.js.
I'm working on basic validation and want to verify items being passed in exist and are safe (done in addition to validation on client side).
So i have teh following:
router.post('/register', function(req, res) {
for (var itemsFromBody in req.body){
console.log(itemsFromBody);
}
However when i check the console all i see are the names of the Keys e.g. username, email etc, not the values themselves.
How do i obtain those?
Also I'll be doing validation on those eg making sure its not empty - do i need to follow a simple if-then statement or is there some nice npm package that exists that allows me to verify?
Thanks!
for (var itemsFromBodyIndex in req.body){
if (req.body.hasOwnProperty(itemsFromBodyIndex)) {
console.log(req.body[itemsFromBodyIndex]);
}
}
This should work !
Useful links:
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/for...in
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/hasOwnProperty
And what about an error catcher into the loop if all of your fields are required ?
for (var itemsFromBodyIndex in req.body){
if (req.body.hasOwnProperty(itemsFromBodyIndex)) {
console.log(req.body[itemsFromBodyIndex]);
if(req.body[itemsFromBodyIndex] == null){
// handle empty field
}
}
}
The for -- in will only give you keys, as you noticed above. You need to use those keys to get the values
for (var itemsFromBody in req.body){
console.log("Key: " + itemsFromBody + " Value: " + req.body[itemsFromBody]);
}

How do I encrypt a variable in javascript?

I have been searching for ages and couldn't find a way to encrypt my javascript variable, because its used for a password:
function lg() {
var input = document.getElementById("values").value;
if (input == pass) {
$("nil").replaceWith($("<success>" + "Success!" + "</success>"));
sleep(4000);
sleep(2000);
window.location.replace("http://google.com");
}
else if (input == "") {
$("nil").replaceWith($("<error>" + "Error: No input detected!" + "</error>"));
}
else {
$("nil").replaceWith($("<error>" + "Incorrect Password!" + "</error>"));
}
}
var pass="test3r"; // The one I need to encrypt
I don't think you would need my html or css as its just my javascript variable I need to encrypt. The variable I need to encrypt is my var pass one.
If your javascript is running on client side so it's not best decision to hold password in js code. And any user can just skip password check by editing code.
But if you really need this, only option I see is to use hash of password and some js library to create exact hash of user input.
For example if you will you md5 hash function (not really strong one, but there are lost of implementations in js) your password hash will look like a50bdfb74649a14c1f86b6d012f2caad
And password check will looks like if (md5(input) == pass) { ...
}
You should read about hash functions and use "salt" when hashing password to make decoding your password harder.

Lotus notes automation from browser

I have been trying to automate Lotus Notes mail fillup from a browser interface.
After refering to Richard Schwartz's answer, i came up with this piece of code using the Lotus.NotesSession class.
function SendScriptMail() {
var mToMail = document.getElementById('txtMailId').value
var mSub = document.getElementById('txtSubject').value
var mMsg = document.getElementById('txtContent').value
var Password = "yyy"
alert("1");
var MailFileServer = "xxx.com"
var MailFile = "C:\Program Files\IBM\Lotus\Notes\mail\user.nsf"
alert("2")
var Session;
var Maildb;
var UI;
var NewMail;
var From = "user#xxx.com"
try {
alert("3")
// Create the Activex object for NotesSession
Session = new ActiveXObject("Lotus.NotesSession");
alert("4")
if (Session == null) {
throw ("NoSession");
} else {
Session.Initialize(Password);
// Get mail database
Maildb = Session.GetDatabase(MailFileServer, MailFile);
alert("5")
if (Maildb == null) {
throw ("NoMaildb");
} else {
NewMail = MailDB.CreateDocument();
if (MailDoc == null) {
throw ('NoMailDoc');
} else {
// Populate the fields
NewMail.AppendItemValue("Form", "Memo")
NewMail.AppendItemValue("SendTo", mToMail)
NewMail.AppendItemValue("From", From)
NewMail.AppendItemValue("Subject", mSub)
NewMail.AppendItemValue("Body", mMsg)
NewMail.Save(True, False)
NewMail.Send(False)
}
}
}
} catch (err) {
// feel free to improve error handling...
alert('Error while sending mail');
}
}
But now, alerts 1,2,3 are being trigerrd, and then the counter moves to the catch block. The lotus notes session is not being started.
In a powershell script that I was previously looking at there was a code regsvr32 "$NotesInstallDir\nlsxbe.dll" /s that was used before the Session = new ActiveXObject("Lotus.NotesSession");. Is there something similar in javascript too, if so how do i invoke that dll.
I think I've realised where I am going wrong. According to me, upto alert("5") things are good. But since Lotus.NotesSession doesn't have a CreateDocument() method, it is throwing the error. I am not sure how to create the document and populate the values though.
Since you've chosen to use the Notes.NotesUIWorkspace class, you are working with the Notes client front-end. It's running, and your users see what's happening on the screen. Are you aware that there's a set of back-end classes (rooted in Lotus.NotesSession) instead of Notes.NotesSession and Notes.NotesUIWorkspace) that work directly with Notes database data, without causing the Notes client to grab focus and display everything that you're doing?
Working with the front-end means that in some cases (depending on the version of Notes that you are working with) you're not going to be working directly with the field names that are standard in Notes messages as stored and as seen in the back-end. You're going to be working with names used as temporary inputs in the form that is used to view and edit the message. You can see these names by using Domino Designer to view the Memo form.
Instead of using 'SendTo', try using:
MailDoc.Fieldsettext('EnterSendTo', mToMail)
Regarding the Body field, there's no temporary field involved, however you haven't really explained the difficulty you are having. Do you not know how to display the interface that you want in the browser? Do you not know how to combine different inputs into a single FieldSetText call? Or are you just dissatisfied with the fact that FieldSetText can't do any fancy formatting? In the latter case, to get more formatting capability you may want to switch to using the back-end classes, which give you access to the NotesRichTextItem class, which has more formatting capabilities.

Categories