First of all, I am French, and my English is not very good, I do my best :)
I created local authentication using PassportJs, Mongoose, and Expressjs (v3.x). It works great. When a user logs in, in / account / space I created a form for changing the current password (3 entries: pass, newpass, newpassconfirm). But after that I have no idea how to handle ...
Do I need to create another LocalStrategy passport to find my user and call the setPassword function declared in my user scheme? Can I possibly perform this operation without the use of passports ..? If possible, how can I access the user database?
Here is my code for my authentication that works.
My / POST login (/routes/user.js)
app.post('/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
req.session.pseudo = user.pseudo;
return res.redirect('/');
});
})(req, res, next);
});
My passport script (/script/passport.js)
passport.use('local-login', new LocalStrategy({
usernameField : 'pseudo',
passwordField : 'pass',
passReqToCallback : true
}, function (req, pseudo, pass, done) {
Users.findOne({ 'pseudo': pseudo }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, req.flash('loginMessage', 'Cet utilisateur n\'existe pas.'));
}
if (!user.verifyPassword(pass)) {
return done(null, false, req.flash('loginMessage', 'Mot de passe incorrect.'));
}
return done(null, user);
});
}));
My user schema (/models/db_Users.js)
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var usersSchema = mongoose.Schema({
pseudo: String,
pass: String,
admin: Boolean,
},
{
collection: 'Users'
});
usersSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
usersSchema.methods.verifyPassword = function(password) {
return bcrypt.compareSync(password, this.pass);
};
module.exports = mongoose.model('Users', usersSchema);
/ changepass POST where I have problems (/routes/users.js)
app.post('/changepass' , function (req, res, next) {
res.redirect('/account');
});
Here you can find the whole project if you have questions about the structure of my application: https://github.com/tibaldev/docu
Thank you for your help!