I'm starting now with NodeJs and I'm following a password authentication tutorial. However, I can not call the method that compares the 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'});
}
});
}
});
});
But when I do POST, it returns me an error saying that "user.states" is not a function. How could you solve this problem? Thanks