0

这是authentication我输入的护照代码passport.js

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

passport.serializeUser(function (user, done) {
  done(null, user._id);
});

passport.deserializeUser(function (id, done) {
  User.findOne({_id: id}, function (err, user) {
    done(err, user);
  })
});

passport.use(new LocalStrategy({
    usernameField: 'email'
  },
  function (username, password, done) {
    User.findOne({email: username}, function (err, user) {
      if (err) return done(err);
      if (!user) {
        return done(null, false, {
          message: 'Incorrect username or password'
        });
      }
      if (!user.validPassword(password)) {
        return done(null, false, {
          message: 'Incorrect username or password'
        });
      }

      return done(null, user);
    })
  }
));

这是Schema code我以 mongoose 查询的形式和使用salt方式存储密码:hashmongoDB

var mongoose = require('mongoose');
var crypto = require('crypto');

var userSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true
  },
  name: {
    type: String,
    required: true
  },

  hash: String,
  salt: String
 
});

userSchema.methods.setPassword = function(password) {
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
};

userSchema.methods.validPassword = function(password) {
  var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
  return this.hash === hash;
};

module.exports = mongoose.model('User', userSchema);

这是路线的auth.js代码:Login

   var express = require('express');
    var router = express.Router();
    var passport = require('passport');
    var mkdirp = require('mkdirp');
    
    var nodemailer = require('nodemailer');
    var config = require('../config');
    var transporter = nodemailer.createTransport(config.mailer);
    
    
    
    router.route('/login')
      .get(function(req, res, next) {
        res.render('login', { title: 'Login your account'});
      })
      .post(passport.authenticate('local', {
        failureRedirect: '/login'
      }), function (req, res) {
      res.redirect('/profile');
})

下面是password change route我正在尝试execute的可能不起作用的。我认为我需要在用户成功更改密码时将hashandsalt值更新到数据库中,但我不知道该怎么做。请帮忙!!!!!!!!!!!!!!!

 router.post('/api/changePassword', function(req,res,next){
      req.checkBody('oldPass', 'Empty Password').notEmpty();
      req.checkBody('newPass', 'Password do not match').equals(req.body.confirmPass).notEmpty();

      var errors = req.validationErrors();
      if (errors) {
        console.log("Errors hain bhai");
        console.log(errors);
        res.render('settingsClient', {
          oldPass: req.body.oldPass,
          newPass: req.body.newPass,
          confirmPass:req.body.confirmPass,
          errorMessages: errors
        });
      }
      else {

       User.findOne({id: req.user.id}, function (err, data) {
         console.log("came inside api changePassword else condition inside User.findOne");
         if (err) {
          console.log(err);
         }
         else {
       data.setPassword(req.body.newPass, function(err,datas){
         if(datas) {
         data.save(function (err,datass) {
          if (err) {
            res.render('settingsClient', {errorMessages: err});
          } else {
            console.log("Hash and Salt saved");
          }
        });
      }
      else {
        console.log("setPassword error"+ err);
      }
       });
    }
      })
    }
    })

它不工作/不将密码值更新到数据库中。我可能会做的可能原因和错误是什么?

4

1 回答 1

0

是的!所以我从 setPassword 中删除了回调函数,并尝试使用 promises 方式/路由来解决这个查询:在这里我发布了现在工作正常的解决方案。

 User.findOne(userObj).then(function(sanitizedUser) {
               if (sanitizedUser) {
                 console.log("sanitizedUser.hash = "+ sanitizedUser.hash);
                   sanitizedUser.setPassword(req.body.newPass);
                       console.log("Password going to be changed successfully now")
                       sanitizedUser.save(function (err,data) {
                         if (err) {
                           res.render('register', {errorMessages: err});
                         } else {
                           console.log("Password changed successfully");
                           res.send('Password reset successful');
                         }
                       });

               } else {
                   res.send('user does not exist');
               }
           }, function(err) {
               console.error(err);
           });
于 2020-10-28T10:20:37.640 回答