如何在ExpressJS中使用本地护照策略和密码更改密码?

时间:2020-10-24 20:54:19

标签: express mongoose-schema passport-local change-password saltedhash

下面是我正在尝试的代码:index.js,并且根据salthash更改密码时,它不起作用。(将它们保存在数据库中)我一直在获取错误未定义为setPassword。我也认为我也犯了代码错误。我想要使​​用'route来更改密码的确切passport-local' Strategy代码。

PS 。我也能够成功注册用户并登录。我只想让他选择更改密码。

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

   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);
          }
           });
        }
          })

这是 Models (user.js),用于在用户注册时以哈希和盐的形式保存密码。

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);

0 个答案:

没有答案