Is escape enough to prevent sql injection? - javascript

const mysql = require('mysql2');
const con = mysql.createConnection({
host: "****",
user: "****",
password: "****",
database: "****"
});
app.get('/:userId', function(req, res) {
if(req.params.userId.match(/^[0-9]+$/) != null){
con.query("select * from users where user_id = "+con.escape(req.params.userId), function (err, result, fields) {
if (err || result[0] == null){
console.log(err);
res.status(404).send('The page was not found');
}else{
res.render('pages/index', {
userName:result[0].user_name,
bio:"bio"
});
}
});
}else{
console.log("The user entered letters and/or special characters");
res.status(404).send('The page was not found.');
}
I want to prevent sql injection, is checking for special characters + escape enough to provide high level security?
I didn't find much documentation on how escape works, that's why I'm asking

Related

How to query a mysql database with Node.js to get specific users (fields) by name in url, not only by ID

I know how to query a SQLite Database with Node.js to bring back a specific key with the corresponding field information but I am unable to find the right syntax to do it in Mysql.
I want to put a specific station name in the url such as and result all its information from the database. example. http://localhost:5000/station/
The database result would be:
["station":"winton", "location":"123 Byers Lane", "property size":"3000"]
<sqlite> needs to be put in <mysql>
app.get('station/:stationid', req, res) => {
const stationToLookup = req.params.stationid;
db.all (
'SELECT * FROM stores WHERE station = $station',
{
$station = stationToLookup
},
(err, rows) => {
console.log(rows);
if (rows.length > 0){
res.send (rows[0]);
}else{
res.send({});
}
});
});
You should install mysql driver first via npm. npm install mysql
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
app.get('station/:stationid', req, res) => {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM stores WHERE station ='" + req.params.stationid + "'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
NOTE how the double quotes and single quotes have been used in the code above. The query is inside double quotes and then the value of a field which we are going to find is between single qoutes embedded inside double qoutes just after the = sign.
Here seems to be a solutioin.....#James #SonuBamniya
//(2)getting all stations names
app.get('/stationNames/:stationid',(req,res)=>{
const nameToLookup = req.params.stationid;
//console.log(nameToLookup);
db.query('SELECT * FROM stores WHERE station = ?', [nameToLookup],(err, rows, fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});

password hashing in nodejs

I am new to StackOverflow, and to the development world. Currently learning JS and node, I am developing a personal project which will be a task management web app. I wrote the register/auth controllers for user data inserts/checks in DB (using MySQL), but ATM I am saving the password in plain text. I want to hash the password and save it in the DB, but when I go look into the table, the passed value is saved as "Object Promise", so it's not currently hashing I think. How can I correctly save the value in registration and validate it in auth? Below is the code of both auth and register controllers. Thanks.
register-controller:
var mysqlConnection = require ('../config');
const bcrypt = require ('bcrypt');
const saltRounds = 10;
module.exports.register=function(req,res){
var today = new Date();
var users={
"firstname":req.body.firstname,
"lastname" : req.body.lastname,
"email":req.body.email,
"password":bcrypt.hash(req.body.password, saltRounds),
"signup_date":today,
"last_login_date":today
}
mysqlConnection.query('SELECT count(email) as count FROM users where email = "' + req.body.email + '"', function (error, results) {
console.log(error, results[0].email);
})
mysqlConnection.query('INSERT INTO users SET ?',users, function (error, results, fields) {
console.log(error, results);
if (error) {
res.json(
error
)
}else{
console.log('User registered succesfully.');
res.redirect('/');
}
});
}
and this is auth-controller:
var mysqlConnection = require ('../config');
const bcrypt = require ('bcrypt');
module.exports.auth = function (req, res, next) {
var email = req.body.email
var password = req.body.password
console.log(email, password);
mysqlConnection.query('SELECT password FROM users where email = "' + email + '"', function (error, results) {
console.log(error, results[0]);
if (error) {
res.error = error;
}else{
if(results.length >0){
bcrypt.compare(password,results[0].password, function (err,res){
if(password === results[0].password){
console.log('User logged in succesfully.');
res.error = error;
res.user = results[0];
res.redirect('/');
}else{
res.error = error;
res.user = null;
}
}
)}
else{
res.error = error;
res.user = null;
res.redirect('/register');
}
}
next();
});
}

Node Js Session user id

Hello I'm just new to Node.js and currently working on session login.
Why can't I set session inside my query function?
Why do I need req.session.save() to save it, but after redirecting to some page session its still not totally set and the page needs to refresh to show session.
Here is my function in setting session
client.query(
"Select id FROM users Where username = '" + req.body.username + "' AND password = '" + req.body.password + "'",
function(err, result) {
if (err) {
return console.error('error running query', err);
} else {
done();
req.session.user_id = result.rows;
req.session.save();
res.redirect('/wall');
}
});
You might want to simplify your example and clarify what libraries you are using. I am assuming you are using express and express-session. I set up a simple example where when you go to to /login?username=yourname page it redirects you to a different page where it shows your name.
var app = require('express')();
var http = require('http').Server(app);
var session = require('express-session');
var mysql = require('mysql')
app.use(session({secret: 'super secret'}));
var client = mysql.createConnection({
host: "My",
user: "private",
password: "configuration",
database: "my_db"
});
app.get('/login', function(req, res, next) {
var sessionData = req.session;
client.query('SELECT * from users where username = ?', [req.query.username], function(err, rows) {
if(err) throw err;
if (rows.length) {
var user = rows[0]
req.session.username = user.username;
req.session.user_id = user.id
res.redirect('/signed_in');
} else {
res.send("user not found")
}
})
})
app.get('/signed_in', function(req, res){
res.send(req.session.user_id + "," + req.session.username);
});
http.listen(3000);
Quentin is right you should look out for sql injections. in the case of node you typically do something like this, depending on what sql library you are using.
client.query(
"Select id FROM users Where username = ? AND password = ?", [req.body.username, req.body.password],
function(err, result) {
// Your code
}
As for why you have to refresh the page after you reload it my guess is something related to done function since i don't know what it is doing in your code. I have no idea why you need to call save, it is not necessary in my example.

string interpolation with sqlite3 and Node

Somewhat new to this, but I'm having an issue inserting a variable into my sqlite3 query. I get the error { [Error: SQLITE_ERROR: no such column: shmee] errno: 1, code: 'SQLITE_ERROR' } where shmee in this case is req.body.username
Not sure what I'm doing wrong here? Any guidance?
app.post('/users/login', function (req, res) {
console.log(req.body)
var query = "SELECT username, password FROM users WHERE username = "+req.body.username+";"
db.all(query, function (err, data) {
if (err) {
console.log(err);
} else if (req.body.password === data.password) {
//set cookie with user info
req.session.user = data;
res.redirect('/users/'+data.username);
} else {
console.log(data)
console.log('password not correct');
res.redirect('/cbt');
}
})
});
Do not concatenate data into query strings; this is a serious source of security vulnerabilities!
Use query parameters; wherever you want to pass data into a query, put a ?, and pass it as an additional argument to run:
db.run("SELECT username, password FROM users WHERE username = ?",
username,
function(err, data) {...});
Also hash your passwords.

mySQL base authentication error in express framework

Recently I put my interest in node.js and learned a great about it and quickly move to the express framework. I've tried to connect my express application with mysql database and succeeded. Now I try to authenticate a simple login from connected with mysql database but I can't do that. Still don't get it why it is happening. Bellow here is the code I've used. A help will be greatly welcome.
var mysql = require('mysql');
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'express_db',
password: '12345'
});
connection.connect();
exports.admin_login = function (req, res) {
res.render('./admin/login', {title: 'Please provide your credentials to login'});
};
exports.admin_home = function (req, res) {
var parse = req.body;
var name = parse.name;
var password = parse.password;
var sql = "select * from user where name = " + connection.escape(name) + " and password = " + connection.escape(password);
connection.query(sql, function (err, results) {
if (err) throw err;
if (name == results[0].name && password == results[0].password) {
req.session.regenerate(function () {
req.session.name = results[0].id;
res.render('./admin/home', {username: results[0].name});
});
}
});

Categories

Resources