I want to create function which will changing password. So in first place I have to compare old password with actually user password in db. Here is the problem, I write inside router function but it is not called. Can someone help me, and tell how could I call it to get answer that old password is equall with password user?
router.post('/change-password', function (req, res, next) {
console.log(req.body)
User.comparePassword(req.body.oldPpassword, user.password, function (err, isMatch) {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Invalid password' });
}
});
});
You shouldn't be saving the password in the DB, that is unsafe. You should hash it in node and then save the hashed password to the DB. Then when you want to check a user, you hash the new password they gave you and compare that to the hashed one in the DB. You never, never store unhashed passwords. That is a recipe for disaster.
Libraries like bcrypt make this easy.
(Assume the hashing has been done) I am trying to do an authenticate user function, by comparing an entered password and its hash in my MongoDB collection. This is my the method in my model.js (copied from the bcrypt guide):
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
And my controller.js:
exports.check = function (req, res) {
var email = req.body['email'];
var password = req.body['password'];
PetOwner.findOne({ "email" : email}, 'email', function(err, task) {
if (err)
res.send(err);
if ( task === null ){
res.json(0); // no matching result
console.log("Email is not yet registered");
} else {
task.comparePassword(password, task.password, function(err, isMatch) { //compare password and the already-hashed password in MongoDB
if (err) throw err;
if(isMatch){
res.json(1);
console.log("Found matching password to email");
}
else{
res.json(0);
console.log("Wrong password");
}
});
}
})
};
And when I fetch the check method, the node console prompts the error that the cb in my model.js is not a function. I have tried several workaround but none has worked so far. Is there any way to debug this?
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb)
Your function takes a single parameter so you cannot refer to a context of "this" outside the function, like you do by using "this.password".
If you add the password to compare with as a second parameter like so:
PetOwnerSchema.methods.comparePassword = function(candidatePassword, password2, cb)
You can then just compare the two inside the function as you are trying to do.
Hope it helps
I'm trying to make a simple login but whenever I try to get the hashed password the mongo console throws me this error:
ReferenceError: test is not defined
for some reason every time I insert data it goes into an admin db which I don't create it is there by default:
show dbs
admin 0.000GB
local 0.000GB
this is my connection:
var db = null;
MongoClient.connect("mongodb://localhost:27017/firstApp", function(err, dbconn){
if(!err){
console.log("Connected");
db = dbconn;
}
});
And this is how I try to login (right now is commented because I want to get the hashed password.
app.put('/users/signin', function(req, res, next){
db.collection('users', function(err, usersCollection){
usersCollection.findOne({username: req.body.usern}, function(err, user){
console.log(user.password);
/*bcrypt.compare(req.body.pass, user.password, function(err, result){
if(result) {
return res.send();
} else {
return res.status(400).send();
}
});*/
});
});
});
However when I try that console.log() command, it throws me this:
ReferenceError: user is not defined
PS. I'm learning.
I am getting a bcrypt error stating that data and hash arguments are required, referencing line #44 in my routes.js file. From what I can tell, I am passing that information: the first parameter to bcrypt.compare is the user entered password, and the second is the hashed password retrieved from the db. What am I doing wrong?
bcrypt.compare(req.params.password, user.password, function...
routes.js
'use strict'
var express = require('express');
var router = express.Router();
var User = require('../app/models/user');
//password hashing
var bcrypt = require('bcrypt');
var count = 0;
router.use(function(req, res, next) {
count++;
console.log('API hit count = %s', count);
next();
});
// /users post(create new user) get(specific user)
router.route('/users')
.post(function(req,res) {
var user = new User();
user.username = req.body.username;
user.password = bcrypt.hashSync(req.body.password, 10);
//save the user and checkfor errors
user.save(function(err) {
if (err) {
res.send(err);
} else {
res.json({message: "User created!"});
}
});
})
router.route('/users/:username')
.get(function(req, res) {
var query = {
username: req.params.username,
};
User.findOne(query, function(err, user) {
if (err) {
res.send(err);
} else {
bcrypt.compare(req.params.password, user.password, function(err, res) {
if(err) {
console.log('Comparison error: ', err);
}
})
res.json(user);
}
});
})
bcrypt.compare takes 3 parameters; passwordToCheck, passwordHash, and a callback, respectively. (Check the documentation for examples)
This error means one or both of the first 2 parameters are either null or undefined. Therefore, make sure both of them are passed correctly. (Not as null or undefined)
Why do we face this error?
bcrypt Error: data and hash arguments required
Example:
bcrypt.compare(first, second)
Ans:
because either second key hash password does not exist (null or undefined) or first, which are compared to each other.
I used
const user = await User.find({email: req.body.email}) //which returned all users
//and unless i reference the first user in index 0, i can't pass user.password to the //bcrypt compare method because it's not a string
I changed it to
await User.findOne({email: req.body.email})//from which i can use user.password in the //bcrypt compare method
const passwordMatch = await bcrypt.compare(password, user.password);
Make sure you are giving raw password and hash password. This will return a boolean value.
I was having the same error when I was working with node js and mongoose. It was caused by attribute added to password called select: false in user model.
After remove it, it works.
I had the same error and the problem was a missing await when calling the function that reads from database
the steps for this problem :
1-ensure that the bcrypt function is have awir before it
2- if the problem is still exist ,then the problem is in the database (mongodb),try to create new database
an example:
const match = await bcrypt.compare(password,userValid.password);
if (match) {
res.send("login successful")
}else{
res.send("wrong password")
}
}
I was having the same issue, but I was using the synchronous form of bycrypt.compare(), which is bcrypt.compareSync(), so I changed it to bcrypt.compare() and it works perfectly.
Use
findOne({})
instead of
find()
Try console.log() to view and verify the data.
try {
let match = await bcrypt.compare(password, user.password)
if(!match){
return res.json({mass: "invalid Created"})
}else{
res.send('Wrong password')
}
console.log('success fulli', user)
res.render('pages/auth/login', {title: 'Login In Your Account'})
} catch(e) {
console.log(e)
next(e)
}
The problem also can appear when you forget to add await when loading data from the database.
I got the same error after forgetting to add "await".
let user = User.findOne({ username: req.body.username });
let user = await User.findOne({ username: req.body.username });
I also have this problem i set for password select:false in user model and solved by adding select('+password') to login route
i know all the questions are solved but maybe someone finds this code works for him
const passwordMatch = await bcrypt.compare(password, user.rows[0].s_password);
The name after the dot it's the name you use in your database, it's the field
I'm trying to get some basic Google authentication going with PassportJS.
The amount of information on the web seems rather limited and I keep hitting issues so thought I would try here.
I am using the code from https://github.com/mattgaidica/twitter-mongo with a few modifications to use it for Google OAuth (it doesn't use the Twitter keys, it uses passport-google, passport.authenticate('google', ...)).
I keep ending up with this error: 'Error: failed to serialize user into session'
passport.serializeUser(function(user, done) {
console.log(user); //does not have the fields we created earlier, user.uid does not exist.
done(null, user.uid);
});
My Passport Strategy:
passport.use(new GoogleStrategy({
returnURL: "http://localhost:3000/auth/google/callback"
},
function(identifier, profile, done) {
User.findOne({uid: profile.id}, function(err, user) {
if(user) {
done(null, user);
} else {
var user = new User();
user.provider = "google";
user.uid = identifier;
user.name = profile.displayName;
user.save(function(err) {
if(err) { throw err; }
done(null, user);
});
}
})
}
));
The fields of this other user are not the same as the one originally created, what happened to the other user?
I'm a bit lost as to what is going on here, if anyone could let me know what I'm doing wrong I would be very grateful.
In your query, you use profile.id:
User.findOne({uid: profile.id}, function(err, user) { ... });
But that should be identifier.
Also, you're using the OpenID-version of the Passport Google plug-in, which is rather old (and doesn't even work properly on Node 0.10). I'd suggest you use passport-google-oauth instead.