Username already Exist - mysql

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.

Related

Check if email already exist in MySql Database

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')
})}
})
}
})

Why am I getting false all the time?

Password hash is working and its storing correctly
But while comparing the res is always returning false
Even though the password is correct. I am using bcryptjs for hashing
app.post("/api/register", (req, res) => {
const { name, email, school, phone, password } = req.body;
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(password, salt, function (err, hash) {
con.query(
`INSERT INTO users(uid, u_name, u_email, u_school, u_phone, u_password) VALUES ('[value-1]','${name}','${email}','${school}','${phone}','${hash}')`,
function (err, result) {
if (err) {
console.log(err);
}
console.log(result);
}
);
});
});
});
app.post("/api/login", (req, res) => {
const { email, password } = req.body;
con.query(
`SELECT * FROM users WHERE u_email='${email}'`,
function (err, result) {
if (err) {
res.send(err.sqlMessage).end();
} else {
bcrypt.compare(password, result[0].u_password).then((res) => {
console.log(res);
});
}
}
);
});
You need to hash the password variable before you compare it in the login route. Otherwise you're comparing a hash and a string and those do not mix.
Thanks for the response.
I found the mistake it was in my database.
I limit my password varchar(30) but the string size was 60 thats why it was not working

MySQL Node JS DELETE no working - 0 rows affected

I am trying to create a post route that will delete a user's data from several tables. I checked in mySQL workbench that the database user has this privilege. However when I click delete on the frontend, the queries appear to run but the rows do not get deleted. Can you someone please tell me where I am going wrong?
app.post('/disposal', redirectLogin, async(req, res) => {
const user = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
await connection.query(userStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(holdingsStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(cashStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
connection.query(tradesStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
});
});
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})
I needed to change user = res.locals to { user } = res.locals as it the former was coming back 'undefined' as it was not properly extracting.
You don't need to nest the calls if you are using async/await.
As the res.locals is an object which contains the user property, you have to get the user property.
You could get it by using Object destructuring syntax.
Try this.
app.post('/disposal', redirectLogin, async (req, res) => {
const { user } = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
try {
let results = await connection.query(userStmt);
console.log(results);
let holdinResult = await connection.query(holdingsStmt);
console.log(holdinResult);
let cashResult = await connection.query(cashStmt);
console.log(cashResult);
let tradesResult = await connection.query(tradesStmt);
console.log(tradesResult);
} catch (error) {
throw error
}
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})

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]);
});
});
});
});
});