Check if email already exist in MySql Database - mysql

How can I check if an email already is in Mysql database on NodeJs?
I'm using the following code
app.use(express.static(__dirname + '/public'));
router.get('/',function(req,res) {
res.sendFile(path.join(__dirname + '/public/html/index.html'));
var email = req.query.email;
if (email != null) {
conn.query('INSERT INTO users (email) VALUES (?)', [email], function(err, result) {
if (err) throw err;
console.log('1 record inserted')
})
}
});

This is an example from a store stay project I had.
I use this method because it is convenient for me.
const [isItemExist] = await SQL(`
SELECT * FROM products WHERE products.id =${Item} `)
if (!isItemExist) {
return res.send({ err: 'product not found' })
}

Check if e-mail exist only do insert if it doesn't:
router.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/public/html/index.html'));
var email = req.query.email;
if (email != null) {
conn.query('SELECT * FROM users WHERE email=?', [email], function(err, result) {
if (err) throw err;
if (result.length > 0) {
console.log('Email already exist')
}
else {
conn.query('INSERT INTO users (email) VALUES (?)', [email], function(err, result) {
if (err) throw err;
console.log('1 record inserted')
})}
})
}
})

Related

Username already Exist

app.post('/addUsername', (req, res)=> {
const username = req.body.username;
db.query("SELECT * FROM userbase WHERE username = ?"), [username], (err, result)
if(result == username)
{
db.query("INSERT INTO userbase (username) VALUE (?)", [], (err, result)=> {
console.log(err);
})
}
else{
db.query("INSERT INTO userbase (username) VALUE (?)", [username], (err, result)=>
{
console.log(err);
})
}
})
I was trying to make it so if the username exist it would not send data to the database. but I dont think I structured this correctly. Basically this database is a big list full of usernames.

Not a valid BCrypt hash. error is occuring

I have a problem in comparing method of bcrypt. This mthod is not able to compare password properly. Please sort out me from this problem.There is problem with comparing method its not working.I have a problem in comparing method of bcrypt. This mthod is not able to compare password properly. Please sort out me from this problem.There is problem with comparing method its not working.
app.post('/upload', (req, res) => {
// hash and save a password
const pass = bcrypt.hashSync(req.body.password);
const username = req.body.username;
console.log(bcrypt.compareSync(req.body.password, pass));
const sql = "INSERT INTO data ( password, username ) values (?,?)";
db.query(sql, [pass, username], (err, rows, fields) => {
if(!err){
res.send({
key: rows
});
}
else {
console.log(err);
}
});
})
app.post('/show', (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query("SELECT * FROM data WHERE username = ?",[username], function(err, results){
if (err) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"err ocurred"
})
}else{
if(results.length >0){
// console.log(bcrypt.compareSync(password, results[0].password));
if(bcrypt.compareSync(password, results[0].password)){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}else{
res.send({
"code":204,
"success":"Email does not exits"
});
console.log(results.length);
}
}
})
})

How to select rows[0] while inserting in node-mysql?

I'm fairly new to nodejs and callbacks. Here is my problem, using passportJS's LocalStrategy and node-mysql :
exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
console.log('data : ', data);
//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(password, salt, null, function(err, hash) {
// Store hash in your password DB.
if (err) return next(err);
data.password = hash;
//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
console.log(err);
return next("Mysql error, check your query");
}
return done(null, rows[0]);
});
});
});
});
I'm trying to return rows[0] containing all the data, but i don't know how should i implement the SELECT command ? Is it before or after the callback for the insertion ? For the moment, rows[0] is naturally undefined.
what about using async.waterfall?
I solve similar problem.
insert query
get auto_incremnet number from rows[0]
select query
website of async here
https://github.com/caolan/async#waterfall
Also, as bcrypt is asyncronous,
data,password = hash
this code doesn't work properly.
I want to execute same type of code for yours but I can't.
So, I use bcrypt in Sync and pass the hash to query.
Here is my solution :
exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return done(err);
}
// Store hash in your password DB.
bcrypt.hash(password, salt, null, function(err, hash) {
if (err) {
return done(err);
}
data.password = hash;
//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
return done(null, false, {
message: 'Mysql error, check your query !'
});
}
// to return all the info in rows[0]
connection.query('SELECT * FROM USERS WHERE email = ?', data.email, function(err, rows) {
if (err) {
return done(null, false, {
message: 'Email not found !'
});
}
return done(null, rows[0]);
});
});
});
});
});

better way of selecting 1 to many?

I have an express.js based rest application. Please have a look on following code and suggest me what would be better way.
I want to select user and its associated images (1 user has many images).
function getUser (connection, req, res) {
var userId = req.params.id;
connection.query('SELECT * FROM user p'
+ ' WHERE p.id = ' + connection.escape(userId), function handleSql(err, rows) {
if (err){ logAndRespond(err,res); return; }
if (rows.length === 0){ res.send(204); return; }
var adId = rows[0].adId;
// load images
connection.query('SELECT id, url FROM image WHERE ad_id = ' + connection.escape(adId), function (err, imgRows) {
if (err){ logAndRespond(err,res); return; }
if (rows.length != 0){
rows[0].images = imgRows;
}
res.json({'user': rows});
connection.release();
});
});
}
You don't have to escape parameters by yourself
You don't release the connection if an error occurred
The problem now is I don't know what you want to do with selected rows. You are also checking the rows.length twice but if there weren't any records in the first query then the second one will not be executed.
function getUser(conn, req, res) {
conn.query("SELECT * FROM user p WHERE p.id = ?;", [req.params.id], function(err, rows) {
if (err) {
return logAndRespond(err, res);
}
if (!rows.length) {
return res.send(204);
}
conn.query("SELECT id, url FROM image WHERE ad_id = ?;", [rows[0].adId], function(err, imgRows) {
if (err) {
return logAndRespond(err, res);
}
if (rows.length) { // ???
rows[0].images = imgRows;
}
res.json({"user": rows});
conn.release();
});
});
}

Hashes won't match

I took a few code snippets from that repo https://github.com/DanialK/PassportJS-Authentication , and adapted it so instead of using MongoDB I'm using MySQL. This is my code to check the password:
User.checkPassword = function(username, password, done) {
pool.getConnection(function(err,connection){
connection.query("SELECT * FROM " + userTable + " WHERE username=? LIMIT 1;",[username], function(err, user){
// if(err) throw err;
if(err) return done(err);
if(!user[0]){
console.log("Incorrect User")
return done(null, false, { message : 'Incorrect Username.' });
}
user = user[0];
hash(password, user.salt, function(err, hash){
hash = hash.toString("hex");
if(err) return done(err);
if(hash == user.hash){
console.log("SUCCESS!");
return done(null, user);
}
done(null, false, {
message : 'Incorrect password'
});
});
});
});
};
The MySQL field to store the hash is varchar(128), and before adding the hash to the table I use toString('hex') in the buffer to store it. The hash is made with https://github.com/visionmedia/node-pwd . My code look a lot like the tutorial's code but for MySQL. But when I try to compare the passwords, the hashes aren't equal. Why's that?
Here's the code that I use to register an user:
User.cadastrar = function(username,password,done){
var User = this;
hash(password, function(err, salt, hash){
hash = hash.toString('hex');
if(err) throw err;
// if (err) return done(err);
pool.getConnection(function(err,connection){
connection.query("INSERT INTO " + userTable + " (username,salt,hash) VALUES (?,?,?);", [username,salt,hash], function(err, user){
if(err) throw err;
// if (err) return done(err);
connection.query("SELECT * FROM " + userTable + " WHERE username=? LIMIT 1;",[username], function(err,user){
done(null, user[0]);
});
});
connection.release();
});
});
}