用猫鼬快递散列密码更新 [英] Hashed password update with mongoose express

查看:66
本文介绍了用猫鼬快递散列密码更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经审查了许多关于此事的讨论,但似乎没有一个对我有帮助.

I have reviewed many discussions on this matter but none seems helpful to me.

我正在使用mongoose 5.5来保存用户数据,如下所示:

I am using mongoose 5.5 to save user data as shown below:

我的模式如下:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");

const userSchema = Schema({

  userName: {
    type: String
  },
  firstName: {
    type: String
  },
  surName: {
    type: String
  },
  password: {
    type: String,
    required: true
  }
});

userSchema.pre('save', async function(next){

try {
  if(!this.isModified('password')){
      return next();
  }
  const hashed = await bcrypt.hash(this.password, 10);
  this.password = hashed;

} catch (err) {
    return next(err);
  }
});

module.exports = user;

我的注册码如下:

exports.register = async (req, res, next) => {

try {
    const user = await db.user.create(req.body);
    const {id, username} = user;
    res.status(201).json({user});

} catch (err) {
    if(err.code === 11000){
        err.message ='Sorry, details already taken';
    }
    next(err);
  }
};

登录代码如下:

exports.login = async (req, res, next) => {

try {
    const user = await db.user.findOne({username: req.body.username});
    const valid = await user.comparePasswords(req.body.password);

    if(valid){

        const token = jwt.sign({id, username}, process.env.SECRET);
        res.json({id, username, token});
    }
    else{
        throw new Error();
    }        

} catch (err) {
    err.message = 'Invalid username/password';
    next(err);
  } 
};

注册和登录效果很好,我的挑战是更新密码.我想将当前密码与用户提供的密码(例如登录名)进行比较,如果有效,则更新新密码.

Registration and login works well, my challenge is updating a password. I would like to compare current password with what user provides (like in login), if it is valid then update new password.

类似这样的东西:

exports.changepass = async (req, res, next) => {
    const user = await db.user.findOne({username: req.body.username});
    const valid = await user.comparePasswords(req.body.password);

    if(valid){

           " ?? update password and hash ?? "
    }
    else{
        throw new Error();
    }       

}

请忠告

推荐答案

如果您使用的是 findOneAndUpdate()进行更新,请尝试使用 pre("findOneAndUpdate")中间件,以类似于 pre("save")的方式修改密码.每当您使用Model.findOndAndUpate()更新模型时,都会调用pre("findOneAndUpdate")中间件.

If you're using findOneAndUpdate() to update, try using the pre("findOneAndUpdate") middleware to modify the password similar to your pre("save"). The pre("findOneAndUpdate") middleware will be called everytime you use Model.findOndAndUpate() to update your models.

您可以使用 updateOne() pre("updateOne")

示例:

// userSchema--------------------
...
userSchema.pre('save', async function (next) {
    try {
        if (!this.isModified('password')) {
            return next();
        }
        const hashed = await bcrypt.hash(this.password, 10);
        this.password = hashed;
    } catch (err) {
        return next(err);
    }
});

userSchema.pre('findOneAndUpdate', async function (next) {
    try {
        if (this._update.password) {
            const hashed = await bcrypt.hash(this._update.password, 10)
            this._update.password = hashed;
        }
        next();
    } catch (err) {
        return next(err);
    }
});

// changepass--------------------
...
if(valid){

    //" ?? update password and hash ?? "
    const result = await db.user.findOneAndUpdate(
        { username: req.body.username },
        { password: req.body.newPassword },
        { useFindAndModify: false }
    ); 
}

这篇关于用猫鼬快递散列密码更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆