Trying to authenticate password stored in mysql with node.js - mysql

I am trying to authenticate password most of the tutorials i found are with mongodb but i have to do the same with mysql.Just to check if passwords stored in db and user provided password are same i am using compareSync and printing it on console but i see false everytime.
app.post('/register',function(req,res,next){
con.connect();
var username=req.body.username;
var passwordToSave = bcrypt.hashSync(req.body.password);
req.body.password=passwordToSave;
var values=[req.body.username,passwordToSave];
var post={USER_NAME : req.body.username, PASSWORD : passwordToSave};
console.log(passwordToSave);
con.query(insert_sql,post,function(err,result){
if(err){
console.log(err);
}else{
res.json({message : "User successfully registered"});
}
});
con.query('SELECT USER_NAME,PASSWORD FROM USERS WHERE USER_NAME =? ',username,function(err,result,fields){
if(err){
console.log(err);
}else{
console.log(result);
var isPasswordCorrect = bcrypt.compareSync(passwordToSave, result[0].PASSWORD);
console.log(isPasswordCorrect);
}
});

Related

I have a problem with BCRYPT Compare with NodeJs Comparing password from Mysql Database

I used Bcryptjs to encrypt a password stored in mysql database. The Problem I have is the login porcess trying to compare the password in the Mysql Database to the login password.The Error message is what I get below.
(node:3616) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of undefined
The enter code is below.
exports.login = async(req,res) => {
try{
//const email = req.body.email;
//const password = req.body.password;
const {email,password} = req.body;
if(!email || !password){
res.status(400).render('login',{message:'Both Email and Password are required!'});
}
db.query('SELECT * FROM users WHERE email=?', [email], async function(error,results){
console.log(results);
//the problem is the compare
if(!results || !(await bcrypt.compare(password,results[0].password))){
res.status(401).render('login',{message:'Email or Password is incorrect'});
}
});
}catch(err){
console.log(err);
}
}
Thanks for the help.

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

node.js mysql not returning results

I am working with socket.io and node.js developing login system, but getting error while I am authenticating user:
function checkUsername(username){
// console.log("checking username "+username+" in database");
var sql = "SELECT username FROM users where username = ?";
var checkUser;
//execute query
db.query(sql, [username], function (err, result,fields) {
if (err)
console.log(err);
else{
//gets found records length/quantity
checkUser = result.length;
console.log("username "+username+" result: "+checkUser);
return checkUser;
}
});
}
I'm getting undefined in return, in short there is nothing being returned.

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

Simple server handling routes and giving error nodejs mysql

I'm trying to write a simple server using nodejs and have the server ship back different queries and/or custom headers/responses based on the routes. However, in the getUsers() function the error keeps getting hit and printing the 'Error querying' to the console instead of printing the email rows. I know the server is connected fine, because I can return a query when I just use the db and return a query with createConnection only using the second example. Any help spotting the error is greatly appreciated. Thanks.
What I'm trying to get done:
var http = require('http');
var mysql = require('mysql');
var url = require('url');
var util = require('util');
var db = mysql.createConnection({
host : "*********",
user : "*********",
password : "*********",
port : '****',
database : '*********'
});
db.connect(function(err) {
console.log('connected');
if (err)
console.error('Error connecting to db' + err.stack);
});
function getUsers() {
db.query('SELECT * FROM users', function(err, rows, fields) {
if (err)
// changed console.error('Error querying');
console.error(err);
if (rows)
console.log('Rows not null');
for (var i in rows) {
console.log(rows[i].email)
}
});
}
var server = http.createServer(function(req, res) {
console.log(req.url);
if (req.url == '/signup') {
console.log("User signing up");
} else if (req.url == '/signin') {
console.log("User signing in");
} else if (req.url == '/new') {
console.log("User request new game");
getUsers();
}
//res.writeHead(200);
//res.end('Hello Http');
});
server.listen(3000);
// changed and commented out db.end();
What does work with querying the db:
var connection = mysql.createConnection({
host : "********",
user : "********",
password : "********",
port : '****',
database : '********'
});
connection.connect();
var queryString = 'SELECT * FROM users';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Users: ', rows[i].email);
}
});
connection.end();
The code has been updated with the changes, and the problem was I was closing the database. After changing the error logs as was suggested in the comments, this was the error received.
{ [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
I then commented out the
db.end()
and the queries were returned fine.
Thanks for the help.