if -else condition is not working in node js - mysql

What I am trying to implement is that after logged in ,system will check user's role and redirect the user accordingly.
1- Admin
2- User
role field is integer type. below is my code
router.post('/signin', function (req, res, next) {
session_store = req.session;
req.assert('Emailid', 'Please fill register Email Address').notEmpty();
req.assert('Emailid', 'Email not valid').isEmail();
req.assert('password', 'Please fill the Password').notEmpty();
var errors = req.validationErrors();
if (!errors) {
Emailid = req.sanitize('Emailid').escape().trim();
password = req.sanitize('password').escape().trim();
var query = 'select * from userdetails where Emailid=? and password=?';
var sql='select role from userdetails where Emailid=?'
db.query(query, [Emailid, password], function (err, rows) {
if (err) {
var errornya = ("Error Selecting : %s ", err.code);
console.log(err.code);
req.flash('msg_error', errornya);
res.redirect('/login-Form');
} else {
if (rows.length <= 0) {
req.flash('msg_error', "Wrong email address or password. Try again.");
res.redirect('/login-Form');
}
else {
session_store.is_login = true;
session_store.user = Emailid;
db.query(sql, Emailid, function (err, result) {
if (err) throw err
else {
if (result == 1) { // facing issue here. It is directly going to else block though the user role is 1 in the mysql table
console.log(result)
res.redirect('/Dashboard');
}
else {
res.redirect('/Audit-Record');
}
}
});
}
}
});
}
else {
res.redirect('/login-Form');
}
});
I guess I am making some mistake while comparing the result value. Can anyone of you please check and let me know where I am going wrong.
Thanks in advance!

The issue got resolved. Actually I was comparing in wrong way. we need to write it like this
else {
session_store.is_login = true;
session_store.user = Emailid;
db.query(sql, Emailid, function (err, result) {
if (err) throw err
else {
**if (result[0].role == 1)** {
console.log(result)
res.redirect('/Dashboard');
}
else {
res.redirect('/Audit-Record');
}
}
});

Related

Update only one column in user info - MySQL NodeJS

I'm builing a classic CRUD (create, read, update, delete) API with NodeJS/Express and MySQL.
I created a route to update my user informations that works fine.
The problem :
If I dont send EVERY data (first_name, last_name etc...), the columns with no data update to undefined in MySQL database, and the column with data don't update. I would like that if I don't send data, no change happens for the columns, and only the one with datas change.
Here is my controller :
module.exports.updateUser = (req, res, next) => {
if (req.method == "PUT") {
let userDetails = `UPDATE users SET first_name = '${req.body.first_name}', last_name = '${req.body.last_name}', user_name = '${req.body.user_name}' WHERE id = ${req.params.id}`;
sql.query(userDetails, function (err, result) {
if (!err) {
res.status(200).json({ message: "User infos updated." })
} else {
res.status(401).json({ message: "Error when updating user infos." })
}
})
}
}
So, if I make a PUT request on an existing user in db with only the mail for example :
{
"mail": "test2#test2.com"
}
all my user datas become null and user.mail stays the same.
Anyone could help me on this ?
Thank you 🙂
Use this query for update one or more filled update at a time
module.exports.updateUser = (req, res, next) => {
if (req.method == "PUT") {
let query = '';
if(req.body.first_name){
query = `first_name =
'${req.body.first_name}'`
}else
if(req.body.last_name){
query = ` last_name =
'${req.body.last_name}'`
}else
if(req.body.user_name){
query = `user_name =
'${req.body.user_name}'`
}eles if(req.body.first_name
&& req.body.last_name)
{
query =`first_name = '${req.body.first_name}', last_name = '${req.body.last_name}'`
}else if(
req.body.last_name && req.body.user_name
{
query = `last_name = '${req.body.last_name}', user_name = '${req.body.user_name}'`
}else if(req.body.first_name
&& req.body.last_name && req.body.user_name)
{
query =`first_name = '${req.body.first_name}', last_name = '${req.body.last_name, user_name = '${req.body.user_name}'}'`
}
let userDetails = `UPDATE users SET ${query} WHERE id = ${req.params.id}`;
sql.query(userDetails, function (err, result) {
if (!err) {
res.status(200).json({ message: "User infos updated." })
} else {
res.status(401).json({ message: "Error when updating user infos." })
}
})
}
}
Thanks to #jutendra, it works.
After few months (and gained skills), here is a cleaner version if ever someone is interested :
module.exports.updateUser = (req, res, next) => {
if (req.method !== "PUT") return;
const updates = [];
if (req.body.first_name) updates.push(`first_name = '${req.body.first_name}'`);
if (req.body.last_name) updates.push(`last_name = '${req.body.last_name}'`);
if (req.body.user_name) updates.push(`user_name = '${req.body.user_name}'`);
if (updates.length === 0) {
res.status(400).json({ message: "No updates provided" });
return;
}
const query = `UPDATE users SET ${updates.join(", ")} WHERE id = ${req.params.id}`;
sql.query(query, (err, result) => {
if (!err) {
res.status(200).json({ message: "User infos updated." });
} else {
res.status(401).json({ message: "Error when updating user infos." });
}
});
};

Express JS query Error Handling not working

this is my first post on Stackoverflow, so please be kind.
I have a huge problem, which I couldn't fix by googling (which is pretty rare).
I want to create a simple error handling in my query, but it won't work.
Here's the code:
pool.query("SELECT password_hash FROM User WHERE email = ?",
req.body.EMailLogin, (error, results, fields) => {
if(error) {
// It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
} else {
// And then it crashes here, because password_hash is undefined
let hash = results[0].password_hash;
bcrypt.compare(req.body.PasswordLogin, hash, function(err, result) {
if (result == true) {
ses.user = req.body.EMailLogin;
req.session.cookie.expires = false;
req.session.save(() => {
return res.redirect('/index');
});
} else {
res.render(); // My Page for Wrong Password (ignore this)
}
});
}
}
);
Throw the error inside the if
if(error) {
throw error;
} else {
I think that the error is how you're passing the parameter, it should be an array:
pool.query("SELECT password_hash FROM User WHERE email = ?",
[req.body.EMailLogin],
I hope this fixes your problem.
You missed to check weather query return data or not and also you can pass values either using object or array(in your case, should be array)
pool.query("SELECT password_hash FROM User WHERE email = ?", [req.body.EMailLogin],
(error, results, fields) => {
if (error) {
// any error like wrong query, connection closed, etc.
// It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
} else if (results.length === 0) {
// email not found in database
// My Page for Wrong Email ???
} else {
// And then it crashes here, because password_hash is undefined
let hash = results[0].password_hash;
bcrypt.compare(req.body.PasswordLogin, hash, function (err, result) {
if (result == true) {
ses.user = req.body.EMailLogin;
req.session.cookie.expires = false;
req.session.save(() => {
return res.redirect('/index');
});
} else {
res.render(); // My Page for Wrong Password (ignore this)
}
});
}
}
);

How to get username of a person who is logged in,from database mysql in node.js

I have made a login system where i am logging in using mobile number and password.Before my code was showing welcome back 03**** ** because i had used request.session.number. I have changed the code so that i can get first name from the database whether employer or helper login.But it is not working.It is showing welcome back, undefined. I am unable to get the name from database.Can anyone tell me how to get it or where i am wrong. I will be thankful if anyone can help me in this regard.
app.post('/auth', function(request, response) {
var number = request.body.number;
var password = request.body.pwd;
if (number && password) {
var sql = `SELECT fyp_helpers.Mobile_number AS number,fyp_helpers.Password AS Password FROM fyp_helpers WHERE Mobile_number = ? UNION SELECT
fyp_employers.Employer_Contact AS number , fyp_employers.Employer_Password AS Employer_Password FROM fyp_employers
WHERE Employer_Contact = ?`;
connection.query(sql, [number, number], function (error, results, fields) {
if (results.length > 0) {
var hashedPassword = results[0].Password;
bcrypt.compare(password, hashedPassword, function (cryptErr, cryptResult) {
if (cryptResult) {
request.session.loggedin = true;
request.session.number = number;
var name= connection.query(`select fyp_helpers.First_Name As name FROM fyp_helpers UNION select fyp_employers.Employer_Fname As name FROM fyp_employers`,[name,name],function(error, results, fields)
{
if(!err)
console.log(name);
else
console.log(error);
})
response.redirect('/home');
} else {
response.send('Incorrect Password!');
console.log(cryptErr);
}
response.end();
});
} else {
response.send('User not registered');
}
});
}
else {
response.send('Please enter Username and Password!');
response.end();
}
});
app.get('/home', function(request, response) {
if (request.session.loggedin) {
response.send('Welcome back, ' + request.session.name + '!');
} else {
response.send('Please login to view this page!');
}
response.end();
});
app.listen(3000);
Everything is working fine but the only problem is it is not getting name.
Edit
var name= connection.query(`select fyp_helpers.First_Name As name FROM fyp_helpers UNION select fyp_employers.Employer_Fname As name FROM fyp_employers`,[name,name],function(error, results, fields)
{
if(!error) {
request.session.name = name;
console.log(name);
}
else
console.log(error);
})
I have declared name to session but it is still not working.Do i place it on wrong position or my query is not right to select the name?
You forgot to add name in request.session.name. Variable name is fetched but not used.

undefined value Array inside Json

This is my code to get logged-in user data
router.post('/login', function (req, res, next) {
/* look at the 2nd parameter to the below call */
let errors = [];
if (!req.body.password || !req.body.email) {
req.flash('error_msg', 'please enter email and password');
res.redirect('/login')
}
passport.authenticate('local', function (err, user, info) {
if (err) { return next(err); }
if (!user) {
req.flash('error_msg', 'your email or password is not correct');
res.redirect('/login')
}
req.logIn(user, function (err) {
if (err) { return next(err); }
var type = user.type;
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
connection.query("update table set last_login = '"+formatted+"' where id = '"+user.id+"'", function (err, rows) {
if(type == '0'){
res.redirect('/login');
}
else if(type == '1'){
console.log(user);
res.cookie('user', user).redirect('/dashboard');
}
else{
res.redirect('/customers');
}
});
});
})(req, res, next);
});
i'm try to console some data in node js and in which data is getting something like this.
{
email: 'test#gmail.com',
username: 'tester',
id: 9,
password: '7ZaOhA0Q0tMTqHC8ExpOLDEdetCb3zKzQYFHIh9RpuI=',
type: '1',
token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImVtYWlsIjoic2l2YWFAZ21haWwuY29tIiwidXNlcm5hbWUiOiJzaXZhYSIsImlkIjo5LCJwYXNzd29yZCI6IjdaYU9oQTBRMHRNVHFIQzhFeHBPTERFZGV0Q2Izekt6UVlGSEloOVJwdUk9IiwidHlwZSI6IjEiLCJ0b2tlbiI6IiJ9LCJpYXQiOjE1MzQ1Njg3NjEsImV4cCI6MTUzNDU3MTc2MX0._3AspvfLO2K46OVilqsLtfiRcZTG2ZYvGJWe6jaQ3ZA',
customers: undefined
}
now i want to display customers field data which is contain data like this abc,xyz,pqr and it seems undefined.
so how can i get data instead of undefined and please tell me the reason behind undefined value if you know
Thank you in advance your help make my day brighter.

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