3
I’m starting now with Nodejs and am following a password authentication tutorial. However, I’m not being able to call the method that compares passwords. In my model, I have this structure:
var UsuarioSchema = new Schema({
login: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
UsuarioSchema.pre('save', function(next){
var user = this;
if(this.isModified('password') || this.isNew){
bcrypt.genSalt(10, function(err, salt){
if(err){
return next(err);
}
bcrypt.hash(user.password, salt, function(err, hash){
if(err){
return next(err);
}
user.password = hash;
next();
});
});
}
else{
return next();
}
});
UsuarioSchema.method.verificaSenha = function (password, cb){
bcrypt.compare(password, this.password, function(err, isMatch){
if(err){
return cb(err);
}
cb(null, isMatch);
});
}
module.exports = mongoose.model('Usuario', UsuarioSchema);
And on the route, where I do the POST, this:
router.post('/api/admin', function(req, res){
Usuario.findOne({
login: req.query.login
}, function(err, user){
if(err){
res.json({sucesso: false, mensagem: 'Autenticação falhou. Usuário nao encontrado'});
}
else{
user.verificaSenha(req.query.password, function(err, misMatch){
if(isMatch && !err){
var token = jwt.encode(user, config.secret);
res.json({sucesso: true, mensagem: 'JWT: ' + token});
}
else{
res.send({sucesso: false, mensagem: 'Autenticação falhou. Senha inválida'});
}
});
}
});
});
Only when I do the POST, it returns me an error saying that "user.checkNow" is not a function. How could I solve this problem? Thank you