Closed ankur1163 closed 2 years ago
I had the same problem. Try this. is written in the Readme
// Load hash from your password DB. bcrypt.compareSync("B4c0/\/", hash); // true bcrypt.compareSync("not_bacon", hash); // false
@ankur1163 It may take time, if you are generating the salt with higher lengths, can you test generating salt with 10
as the length of the salt const salt = await bcrypt.genSalt(10);
like this. Try this, if it is working or not.
I have generated this. I am certainly not the most beautiful variant, but it works for me!
The email and username are unique in the database. With me there will be a maximum of 10 users anyway. Therefore I do not check if the user already exists!
/**
* POST insert new User
*/
router.post('/', reqAndResHandler.verifyToken, (req, res) => {
if (!req.body.username || !req.body.password || !req.body.email) {
return res.json({message: 'No fields'});
}
const Promise = reqAndResHandler.ckeckTockenIsValid(req, res);
Promise.then(function (authData) {
bcrypt.hash(req.body.password, 10).then(password => {
req.body.password = password
db.insert(req.body).into(query.DB_USERS)
.then(function (data) {
res.send(data);
}).catch(function (err) {
res.send(err.message)
});
}).catch(function (err) {
res.send(err.message);
})
})
});
/**
* Token only valid one houers after login
*/
router.post('/login', (req, res, next) => {
if (!req.body.username || !req.body.password) {
return res.json({message: 'No fields'});
}
const {username, password} = req.body;
let user = {};
db.select().from(query.DB_USERS)
.where({[query.WHERE_USER_USERNAME]: username})
.then(function (data) {
user = data.find((user => {
return user
}));
const correctPW = bcrypt.compareSync(password, user.password);
if (user && correctPW) {
jwt.sign({ username: username, email: user.email , user_id: user.user_id}, 'secretKey', {expiresIn: '10h'}, (err, token) => {
res.json({token})
})
} else {
res.sendStatus(401)
}
}).catch(function (err) {
res.send(err.message)
});
});
´´´
I hope this helps you a little. :-)
OP is checking the first argument of the callback, not the second. According to the docs the first argument indicates if there was an error. The library works as expected, and this issue can be closed.
bcrypt compare function isnt working Here's my code
When i sign up. it does store correct hashed password. I bring hashed password from db . But compare always return false. Can someone help me out?