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.
Related
I've tried some methods but nothing works
and I'm trying to change
Anyone can give me a little trick to create this function in node js?
Your suggestions will be very helpful for me to solve it
//router_register.js
// Definisikan router dari express
const router = require('express').Router();
// Ambil index.js dari controller dan panggil variabel didalamnya
const registerController = require('../controllers').register;
// Definisikan middleware verify.js
const verifyUser = require('../configs/verify');
// Rute 'http://localhost:5050/register/' digunakan untuk menampilkan form register
router.get('/', verifyUser.isLogout, registerController.formRegister);
// Rute 'http://localhost:5050/register/save' digunakan untuk menyimpan data yang diinput user saat register
router.post('/save', verifyUser.isLogout, registerController.saveRegister);
// Export agar dapat dibaca oleh express
module.exports = router;
//controller_register
const config = require('../configs/database');
let mysql = require('mysql');
let pool = mysql.createPool(config);
pool.on('error', (err)=> {
console.error(err);
});
module.exports = {
formRegister(req, res) {
res.render("login", {
// Definisikan semua varibel yang ingin ikut dirender kedalam register.ejs
url: 'http://localhost:5050/',
});
},
saveRegister(req, res) {
let username = req.body.username;
let email = req.body.email;
let password = req.body.pass;
if (username && email && password) {
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query(
`INSERT INTO table_user (user_name, user_email, user_password) VALUES (?,?,SHA2(?,512)); `, [username, email, password], function (error, results) {
if (error) throw error;
req.flash('color', 'success');
req.flash('status', 'Yes..');
req.flash('message', 'Registrasi berhasil');
res.redirect('/login');
});
connection.release();
})
} else {
res.redirect('/login');
res.end();
}
}
}
And please tell me which parts I should fix to make it even better for this coding
You have a couple of options. May be even both to get a robust solution. As you asked for general direction, instead of giving you exact code, I will try to point you in right direction.
In your saveRegister function, before you run INSERT, using email, you can run another query to fetch any existing user's with the incoming email address. If you find one, throw an exception for user trying to register with existing email.
To make this even better, you can add a UNIQUE constraint on your table in the database for the user_email column. This way if you do try to save another user with a duplicate email, you should get an exception that your try block will catch.
All the best. Please update the question with specifics if you try this approach and still need more help.
I am trying to make a log in system. Right now I am working on allowing the user to register. I am trying to make it so you can't create an account that has the same username or email as another. However, it is giving me a parse error.
Here is the code:
app.post("/create", (req, res) => {
const email = req.body.email;
const username = req.body.username;
const password = req.body.password;
db.query("SELECT email, username FROM users WHERE email = ? AND username = ?"),
[email, username],
(err, result) => {
if (err) {
console.log(err);
} else if (result) {
res.send("Username or Email is already in use.")
} else {
db.query(
"INSERT INTO users (email, username, password) VALUES (?,?,?)",
[email, username, password],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
}
};
});
Here is the error I am getting:
{
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND username = ?' at line 1",
sqlState: '42000',
index: 0,
sql: 'SELECT email, username FROM users WHERE email = ? AND username = ?'
}
I am new in node.js
I am trying to make a login and registration system using express.js, vanilla JS, CSS, HTML, and MySql.
below is code that handles routing as well as parses HTTP Post requests made by the client which consists of username and password. username and password are stored inside fields.username and fields.password
functions userRegistration(...) and userLogin(...) are defined inside db.js ( shown at the end ); they are exported from db.js and are imported in users.js
users.js
router.post('/register', (req, res, next) => {
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var userInfoArray = [fields.username, fields.password]
db.userRegistration(userInfoArray)
})
});
router.post('/login', (req, res, next) => {
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var userInfoArray = [fields.username, fields.password]
db.userLogin(userInfoArray)
})
});
I have created userinfo table to store usernames and passwords.
As shown below I am getting username and password by HTTP post method. Which I am parsing using
formidable module which gives me fields.username and fields.password values.
I am using query(...) method to query database providing actual SQL as string named registrationQueryString (to insert an entry into table) and loginQueryString(to find whether provided username and password are in the database or not)
db.js
var username, password;
var userInfoArray = [username, password]
const registrationQueryString = "INSERT INTO (username, password) userinfo VALUES ( ?, ? )"
const loginQueryString = "SELECT (username, password) FROM userinfo WHERE EXISTS (SELECT (username, password) FROM userinfo WHERE username = (?) AND password = (?))"
function userRegistration (userInfoArray){
dbConnection.query( registrationQueryString, userInfoArray, function(err, results, fields) {
if (err) throw err
console.log(results)
})
}
function userLogin (userInfoArray){
dbConnection.query( loginQueryString, userInfoArray, function(err, results, fields) {
if (err) throw err
console.log(results)
})
}
It is giving me an error
"wer" is random value I provided as username and password
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(username, password) userinfo VALUES ( 'wer', 'wer' )' at line 1
at Query.Sequence._packetToError (F:\dr.server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (F:\dr.server\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (F:\dr.server\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (F:\dr.server\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (F:\dr.server\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (F:\dr.server\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (F:\dr.server\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (F:\dr.server\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
--------------------
at Protocol._enqueue (F:\dr.server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (F:\dr.server\node_modules\mysql\lib\Connection.js:198:25)
at Object.userRegistration (F:\dr.server\db.js:29:18)
at F:\dr.server\routes\users.js:12:8
at zalgoSafe (F:\dr.server\node_modules\dezalgo\dezalgo.js:20:10)
at f (F:\dr.server\node_modules\once\once.js:25:25)
at IncomingForm.<anonymous> (F:\dr.server\node_modules\formidable\src\Formidable.js:183:9)
at IncomingForm.emit (events.js:400:28)
at IncomingForm._maybeEnd (F:\dr.server\node_modules\formidable\src\Formidable.js:612:10)
at QuerystringParser.<anonymous> (F:\dr.server\node_modules\formidable\src\plugins\querystring.js:36:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(username, password) userinfo VALUES ( 'wer', 'wer' )' at line 1",
sqlState: '42000',
index: 0,
sql: "INSERT INTO (username, password) userinfo VALUES ( 'wer', 'wer' )"
}
I know that something is wrong with my SQL queries but I am not able to figure it out.
Any help will be welcomed.
If this information isn't enough I can give specific code through github.
Not able to add a comment, yet. Have you tried to change your SQL statement to:
INSERT INTO tbl_name (col_name, col_name) VALUES ('value', 'value')
"INSERT INTO userinfo (username, password) VALUES ( 'wer', 'wer' )"
https://dev.mysql.com/doc/refman/8.0/en/insert.html
Edit:
In your post:
It is giving me an error
I know that something is wrong with my SQL queries but I am not able to figure it out.
The code above is not meant to be the answer. As I previously mentioned, not able to comment, yet. The above code is just a pointer to the correct answer. You have to change your MySQL query to the syntax above. The link provided gives you the correct syntax.
"insert into userinfo(username, password) values('wer', 'wer');"
You can use template literals to do so.
var username, password;
const registrationQueryString = `INSERT INTO (username, password) userinfo VALUES ('${username}', '${password}')`
And then use registrationQueryString as a raw query.
Bear in mind this is an ES2015 feature and should be available in any recent version of Node.js. More about template literals at MDN Web Docs
First update this query from
INSERT INTO (username, password) userinfo VALUES ( ?, ? )
to
INSERT INTO userinfo (username, password) VALUES ( ?, ? )
Please don't use this type of query
SELECT (username, password) FROM userinfo WHERE EXISTS (SELECT (username, password) FROM userinfo WHERE username = (?) AND password = (?))
Replace it with the following
const ObjQr = [
req.body.username,
req.body.password
];
const SsQl = "CALL SpSelectUser(?,?)";
query(SsQl, ObjQr, (err,results,fields) => {
if(err) {
res.send('ERROR');
}
else {
const Info= {
UserInfo : results[0]
};
res.json(Info);
}
});
Try to use StoredProcedure instead of direct query to avoid race condition and Sql-Injection.
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);
})
});
I'm developing a node.js app with express and mongoDb and mongoose. The app saves the user in the code below with no problem, but in this code it always console error even if the process is success, and the user is saved.
I'm trying to make flash messages and validation but I can't go ahead with this problem.
Also, I'm not sure if I'm using the right post method or not(should I use res.status(500).send('error')) inside the post?
newUser.save().then(function (error) {
if (error) {
console.log('error') // always prints this
} else {
console.log('success')
}
})
the full code
var User = require('../models/User')
var router = require('express').Router()
router.route('/user/signup')
.get(function (request, response) {
// render the form
response.render('user/signup')
})
.post(function (request, response) {
var username = request.body.name
var password = request.body.password
var newUser = new User({
name: username,
password: password
})
newUser.save().then(function (error) {
if (error) {
console.log('error')
} else {
console.log('success')
}
})
response.redirect('/')
})
I think you want to pass the function directly to save() as the callback
newUser.save(function (err, user) {
if (err) ..
})
With the approach you're currently taking, I think you'll want to use catch
newUser.save().then(function (user) }})
.catch((err) => ...);
Source: mongoose docs