Change password using expressjs mongoose passport-local

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 // permet de passer l'objet req dans le callback
}, 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');

// Schema de la collection User
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) {
    //console.log(req.body.pass, req.body.newpass, req.body.newpassconfirm);

    // Should I call another passport LocalStrategy to acces to my User and set the new password here ?

    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!

+4
source share
2 answers

/models/db_Users.js

// bcrypt middleware
usersSchema.pre('save', function(next){
    var user = this;

    //check if password is modified, else no need to do anything
    if (!user.isModified('pass')) {
       return next()
    }

    user.pass = bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
    next()
})

Inside your routes /users.js

var User = require('mongoose').model('Users')

app.post('/changepass' , function (req, res, next) {
     if (newpass !== newpassconfirm) {
        throw new Error('password and confirm password do not match');
     }

     var user = req.user;

     user.pass = newpass;

     user.save(function(err){
         if (err) { next(err) }
         else {
             res.redirect('/account');
         }
     })
});
+3
source

You can try something like this

app.post("/update/userid", function(req, res) {
    var userid = req.params.id
    var username = req.session.passport.user
    var newPass = req.body.password
    console.log(username, userid)
    User.findByUsername(username).then(function(sanitizedUser) {
        if (sanitizedUser) {
            sanitizedUser.setPassword(newPass, function() {
                sanitizedUser.save();
                res.send('password reset successful');
            });
        } else {
            res.send('user does not exist');
        }
    }, function(err) {
        console.error(err);
    })
})
0
source

Source: https://habr.com/ru/post/1542753/


All Articles