bcrypt issue using nodejs - mysql

I have successfully encrypted the password and stored in my DB during registration. But when I am login, I am comparing the password and trying to login, during the login period my sql query is falling to read the password and I am getting hash is not defined. Please let me know where I am going wrong.
router.post('/login', function(req,res) {
var password = req.body.password;
var user_name = req.body.user_name;
var response = {};
bcrypt.compare(password, hash, function(err, res) {
db.query('select user_id,email FROM user where password = ? AND user_name = ? OR email = ?',
[hash, req.body.user_name, req.body.user_name], function (error,rows) {
if (error) {
res.json(error)
} else {
response.msg = 'Login Success';
}
});
}
});

router.post('/login', function(req,res) {
var password = req.body.password;
var user_name = req.body.user_name;
var response = {};
var hash = db.query('SELECT hash FROM user WHERE user_name = ?', [req.body.user_name]);
bcrypt.compare(password, hash, function(err, res) {
db.query('select user_id,email FROM user where password = ? AND user_name = ? OR email = ?',
[hash, req.body.user_name, req.body.user_name], function (error,rows) {
if (error) {
res.json(error)
} else {
response.msg = 'Login Success';
}
});
}
});

Related

Retrieving hashed password from sql database

Having issues comparing user password and hashed password using bcrypt.I'll be glad if anyone helps.
Here is my login code snippet
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
const searchSql2 = 'SELECT * FROM users WHERE user_name = ?'
con.query(searchSql2,[username], async(err, results,fields) => {
if (err) throw err;
const hashedPassword = results[0].user_password
const isValid = bcrypt.compareSync(password, hashedPassword)
if (isValid) {
//password matched
req.session.loggedin = true;
req.session.username = username;
res.redirect('./home')
res.end();
} else {
res.send("Invalid username or password")
}
})
})
When user logins even with correct details he/she gets 'Invalid username or password!'.How do I go about this?

using bcrypt for login in nodejs

I'm having a hard time with integrating bcrypt to try to make my login system safe.
I basically get the username, password the user inputs and try to compare it from the hashed password in my db. here's what I have.
const inputUsername = req.body.inputUsername;
const inputPassword = req.body.inputPassword;
var userLogin = "select * from login where USERNAME = ?"
ibmdb.open(ibmdbconnMaster, function(err, conn) {
if (err) return console.log(err);
conn.query(userLogin, [inputUsername], function(err, rows) {
if (err) {
console.log(err)
}
if (rows.length > 0) {
var pass = ""
for (var i = 0; i < rows.length; i++) {
pass = rows[i]['PASSWORD'];
console.log(pass)
bcrypt.compare(inputPassword, hash, function(err, result) {
if (pass == result) {
console.log("this works")
userAuth = true;
res.redirect('/index')
}
})
}
console.log("does not work")
} else {
userAuth = "false";
res.render('login.ejs')
alert('Incorrect username or password. Please try again')
}
conn.close(function() {
console.log('closed the function /login');
});
})
})
what happens right now is I get the error ReferenceError: hash is not defined
not sure how to fix this. thanks in advance
Where have you defined hash? I don't see it in your code.
Here's an example of auth routes that I've used with bcrypt/node/express:
const Users = require("../users/users-model.js");
router.post("/register", (req, res) => {
// Pull the user's credentials from the body of the request.
const user = req.body;
// Hash the user's password, and set the hashed password as the
// user's password in the request.
const hash = bcrypt.hashSync(user.password, 10);
user.password = hash;
Users.add(user)
.then((newUser) => {
const token = generateToken(newUser);
res
.status(201)
.json({ created_user: newUser, token: token, user_id: newUser.id });
})
.catch((err) => {
res.status(500).json({
message: "There was an error adding a user to the database",
err,
});
});
});
router.post("/login", (req, res) => {
const { username, password } = req.body;
Users.findBy({ username })
.first()
.then((user) => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user);
res
.status(200)
.json({
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
token: token,
user_id: user.id,
});
} else {
res.status(401).json({ message: "Invalid Credentials" });
}
})
.catch((err) => {
res.status(500).json(err);
});
});
function generateToken(user) {
const payload = {
userid: user.id,
username: user.username,
};
const options = {
expiresIn: "1h",
};
const token = jwt.sign(payload, secrets.jwtSecret, options);
return token;
}
module.exports = router;

Strange nodejs behaviour when logging in a user

The problem is that it shows that it is successfully logged in (201) without the redirect code, but with it, it shows a 302 error and the email_address is undefined.
What could be the problem here? I still can't come to a conclusion.
The problem may be in the order of the code I guess?
const login = async (req, res, next) => {
const { email_address, password, user_email, user_password}: { email_address: string, password: string, user_email: string, user_password: string } = req.body;
try {
const userWithDetails = 'SELECT * FROM users WHERE email_address = user_email AND password = user_password'; //w form info
if (userWithDetails) {
req.session.loggedin = true; //true
req.session.email_address = email_address; //undefined
console.log(req.session.email_address)
// return res.redirect('./index.html')
}
res.status(201).send('Succesfully signed in');
// res.status(403).send('Password is not correct');
} catch(error) {
res.status(404).send(`User with email ${email_address} not found!`);
}
await next;
};
NEW CODE ***
const login = async (req, res, next) => {
const { email_address, password}: { email_address: string, password: string} = req.body;
const userWithDetails = 'SELECT * FROM users WHERE email_address = ?';
return con.query(userWithDetails, email_address, (err, results) => {
if (err) {
console.error(err);
}
const user = results.find(emailObj => emailObj.email_address === email_address);
if (results && results.length && user.email_address) {
req.session.loggedin = true;
req.session.email_address = email_address;
const matchPassword: boolean = bcrypt.compareSync(password, user.password);
if (matchPassword) {
const token = jwt.sign({ user }, 'aaaa', { expiresIn: '1h'});
res.status(200).send({message: 'Logged in', token: token});
} else {
res.status(403).send('Password is not correct');
}
} else {
res.status(404).send(`User with email ${email_address} not found!`);
}
});
await next;
}
You don't execute your sql query at any point.
You just say :
query = 'select blabla'
if(query){...}
Of course this will always be true. You want to run the query on your database.
Also in your query you don't properly use the variables, see string formatting :
let my_var = `SELECT xxx from xxx where username = '${username}'`
Also please sanitize the parameters to prevent SQL Injection...

How to show data on frontend using Controller in Mysql

I am trying to show data on front end using controller in Angular js but unable to do so I am able to take data from database that is mysql but don't know how to show it on frontend
module.exports = function(app) {
app.post('/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
console.log(password);
if (email && password) {
connection.query('select * from user where email = ? and password = ?', [email, password], function(err, result) {
console.log(result);
if (err) res.send(err);
res.redirect('/dashboard');
});
}
});
}

How to add session and add access token to login in node

I have a login api as follows :
app.post('/login', function (req, res){
email = req.body.email;
password = req.body.password;
if(email && password )
{
console.log(email); //displays the email in the terminal
console.log(password); //displays the password in the terminal
var status = []; //array to output json
//connection.connect(); //mysql connection
connection.query('SELECT username FROM user WHERE email =? and password = ?',[email,password], function (error, rows, fields) {
if(rows.length == 1)
{
passport.serializeUser(function(res, done) {
done(null,res);
});
passport.deserializeUser(function(id, done) {
done(null,res);
});
status.push({username: rows[0].username});
username = rows[0].username;
console.log('sucessful login');
res.end('"status:"\n'+JSON.stringify(status)); //output as JSON
}
if(rows.length == 0)
{
connection.query('select * from temp_users where email = ? and password = ?',[email,password],function(error,rows,fields)
{
status = '';
if(rows.length == 1)
{
status = 'pending';
//res.end('Your Account needs to be verified');
res.end('"status:"'+JSON.stringify(status));
console.log('Your Account needs to be verified.');
}
else
{
status = 'error';
res.end('"status:"'+JSON.stringify(status));
//res.end('no such user.Please create an account');
console.log('no such user.Please create an account');
}
}
);
}
});
}
});
Now what i would like to do is to add a session for every user that logs in and make that session expire after some time.I would also like to have an access token to be inserted to my database once the user logs in.
Any help?
This example does exactly what you are looking for.
node.js express mysql passport