Not a valid BCrypt hash. error is occuring - mysql

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

Related

How i display username after login successful with set cookies using angular nodejs mysql

My login.component.ts file
How to set cookies in the code to display the username.
login Submit(){
console.log(this.userLogin.value)
this.service.LoginData(this.userLogin.value).subscribe((res)=>{
console.log(res)
this.userLogin.reset()
this.successmsg = res.message
this.Username = this.cookieService.set('username', this.Username)
})
}
I am trying to display the username but it only see me undefined.
api service file
LoginData(data:any):Observable<any>{
return this.http.post(`http://localhost:3000/login`,data)
}
dashboard(){
return this.http.get('http://localhost:3000/dashboard')
}
NodeJS file using MySQL database
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
const query = `SELECT * FROM user WHERE username = '${username}' AND password = '${password}'`;
db.query(query, (error, result) => {
if (error) {
console.log('Error querying database:', error);
res.status(500).send('Error querying database');
} else if (result.length === 0) {
console.log('Invalid username or password');
res.status(401).send('Invalid username or password');
} else {
console.log('Login successful');
res.status(200).send({
message: 'Login successful',
username: username
});
}
});
res.cookie('username',`${username}`)
});

bcrypt nodejs - null error when trying to login with comparing hashed password from the database

I created a basic register and login page connected to local mysql - that collects email, username and password (password gets hashed with bcrypt) and stores them in database.
Yet when i am trying to log in I get an error that says just : null + (console log saying password + else2 so i know which line got called)
This is login.js file
exports.login = (req, res) => {
console.log(req.body);
let email = req.body.email;
let password = req.body.password;
let username = req.body.username;
//if it finds username and email matching login credentials it will check for password
db.query('SELECT username, email, password FROM users WHERE username = ? AND email = ?', [username, email], function (error, results) {
if (error) {
res.send({
"code": 400,
"failed": "error ocurred"
});
}
//results[0].password means the password of the user that was found.
// it should compare plain password with the encrypted password in database
//and redirect to the /profile page if the password are a match.
if (results.length > 0) {
bcrypt.compare(password, results[0].password, function (error, answer) {
if (error) {
console.log(password +'if1')
console.log("comparing gone wrong", error);
return res.render('login', {
message3: 'Comparing error - please try again later'
});
}
if (answer) {
console.log(password + 'if 2')
res.redirect("/profile");
console.log("login successfull!");
}
else {
console.log(password + ' else2', error)
return res.render('login', {
message3: 'User or password or email is wrong'
});
}
});
} else {
console.log(password + 'else3')
return res.render('login', {
message3: 'User or password or email is wrong'
});
}
});
};
I will also put the register.js file if that will help with anything.
exports.register = (req, res) => {
console.log(req.body);
const { username, email, password, passwordConfirm } = req.body;
db.query('SELECT email FROM users WHERE email = ?', [email], async (error, result) => {
if(error) {
console.log(error);
}
if( result.length > 0 ) {
return res.render('register', {
message: 'That email is already in use'
})
} else if( password !== passwordConfirm) {
return res.render('register', {
message: 'That passwords do not match'
});
}
let hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', {username: username, email: email, password: hashedPassword }, (error, result) => {
if(error) {
console.log(error);
} else {
console.log(result);
return res.render('register', {
message2: 'User Registered!'
});
}
})
});
}
Well, now I know why finding an answer online was so hard.
The code is right, the problem was in my database, I previously allowed for 50 Varchar password (but hashing it makes it longer, and it was getting cut), after I changed it to 128 chars it works perfectly with the new users that now register and login under the new broader restrictions.

User always getting failure redirected using passport?

No matter what I change the user login will keep redirecting to failure instead of success. I don't know if I'm missing something or if I did something wrong. I tried to read the documentation for passport but, I found it pretty confusing. Here is my github link if you need to see the rest of the code. The node files are in app.js and passport-config.js.The sign up part of the website is working. https://github.com/gego144/to-do-list-website/tree/main
const customFields = {
usernameField: 'email',
passwordField: 'password'
}
const verifyCallback = (username, password, done) => {
user_exists = userName_Checker(username), function (err, user) {
if (err) { return done(err); }
if (userName_Checker(username) == false) {
console.log('wrong user');
return done(null, false, { message: 'Incorrect username.' });
}
if (password_finder(username, password)) {
console.log('wrong pass');
return done(null, false, { message: 'Incorrect password.' });
}
console.log('wtf');
return done(null, user);
};
;
}
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// function that checks to see if the users email is in the database
function userName_Checker(email_name){
var sql = "select * from info where email = ?";
var user_email = [[email_name]];
db.query(sql, [user_email],function (err,result){
if (err) throw err;
var not_unique = result.length;
if(not_unique == 0){
return false;
}
else{
return true;
}
}
)}
// function that checks to see if the password in the database matches with the email
function password_finder(email_name, pass){
var sql = "SELECT password FROM info WHERE email = ?";
var user_email = [[email_name]];
db.query(sql, [user_email],function (err,result){
if (err) throw err;
bcrypt.compare(result, pass, function(err, res){
if(err){ throw err};
if(res){
return true;
}
else{
return false;
}
})
}
)}
My post method in my other file.
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect:'/index.html',
failureFlash: true
}))
Edit 1.
I just want to mention that the console.logs you see in verify Callback all don't log anything for some reason too.
The problem might be in the serialization logic.
In passport.serializeUser, you are passing in the whole user object, but when deserializing you are passing the id
Though I am not using SQL, the logic should be similar.
So the code should be something like this:
// Session
// Pass in user id => keep the session data small
passport.serializeUser((id, done) => {
done(null, id);
});
// Deserialize when needed by querying the DB for full user details
passport.deserializeUser(async (id, done) => {
try {
const user = await User_DB.findById(id);
done(null, user);
} catch (err) {
console.error(`Error Deserializing User: ${id}: ${err}`);
}
});
// Export the passport module
module.exports = (passport) => {
passport.use(new LocalStrategy({ usernameField: 'email', }, async (email, password, done) => {
try {
// Lookup the user
const userData = await User_DB.findOne({ email: email, }, {
password: 1, }); // Return the password hash only instead of the whole user object
// If the user does not exist
if (!userData) {
return done(null, false);
}
// Hash the password and compare it to the hash in the database
const passMatch = await bcrypt.compare(password, userData.password);
// If the password hash does not match
if (!passMatch) {
return done(null, false);
}
// Otherwise return the user id
return done(null, userData.id);
} catch (err) {
passLog.error(`Login Error: ${err}`);
}
}));
};
These options for passport seems to malfunction a lot or exhibit weird behaviors, so I suggest you handle the redirection logic like in my controller.
{ successRedirect: '/good',
failureRedirect: '/bad' }
Login controller logic:
(I am omitting the code here for session storage and made some modifications, but this code should work for what you need)
const login = (req, res, next) => {
//Using passport-local
passport.authenticate('local', async (err, user) => {
//If user object does not exist => login failed
if (!user) { return res.redirect('/unauthorized'); }
//If all good, log the dude in
req.logIn(user, (err) => {
if (err) { return res.status(401).json({ msg: 'Login Error', }); }
// Send response to the frontend
return res.redirect('/good');
});
});
})(req, res, next);
};
The actual route:
// Import the controller
const {login} = require('../controllers/auth');
// Use it in the route
router.post('/auth/login', login);

Not able to compare my database password and input field password

My input password and database password are same then also function is returning false. Here compare method is not working properly.I am getting false in return everytime while I am providing correct password.
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query('SELECT * FROM dataa WHERE username = ?',[username], function (error, rows, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(rows.length >0){
console.log(bcrypt.compareSync(password, rows[0].password));
if(bcrypt.compareSync(password, rows[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"
});
}
}
});
})
You might be having more than one username in your database which match it up with the username your are giving so it will try and match it with the first one but the password would be a different one ..

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