NodeJS 为什么用户方法的模式不起作用

i7uq4tfw  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(94)

当我更新密码时,它就完成了。但该模式中使用的方法并不奏效。

// route file
route.put("/update-password", auth_middleware, update_password);

// userController file
const update_password = asyncHandler(async (request, response) => {
    try {
        const { id } = request.user;
        const { password } = request.body;
        validateMongodbId(id);
        const findUser = await user_model.findById(id);
        createPasswordResetToken()
        if (password) {
            findUser.password = password;
            const updateUser = await findUser.save();
            response.json(updateUser);
        }
    } catch (err) {
        throw new Error(`Errorrrrrrrrrrrrrrrrrr: ${err}`)
    }
})

// This is all the code in the schema file
const mongoose = require("mongoose");
const { genSaltSync, hashSync, compareSync } = require("bcrypt");
const crypto = require('crypto');
// Schema
const schema_user = new mongoose.Schema(
  {
    firstName: {
      type: String,
      required: true,
    },
    lastName: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    mobile: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    block: {
      type: Boolean,
      default: false,
    },
    role: {
      type: String,
      default: "user",
    },
    cart: {
      type: Array,
      default: [],
    },
    address: [{ type: mongoose.Schema.Types.ObjectId, ref: "Address" }],
    wishlist: [{ type: mongoose.Schema.Types.ObjectId, ref: "Product" }],
    refreshToken: {
      type: String,
    },
    passwordChangedAt: {type: mongoose.SchemaTypes.Date},
    passwordResetToken: {type: String},
    passwordResetExpires: {type: mongoose.SchemaTypes.Date},
  },
  {
    timestamps: true,
  }
);

// Hashing Password
schema_user.pre("save", function (next) {
  if (!this.isModified("password")) next();
  const salt = genSaltSync();
  this.password = hashSync(this.password, salt);
  next();
});

// comper password
function comparePassword(raw, hash) {
  return compareSync(raw, hash);
}

schema_user.methods.createPasswordResetToken = async function () {
  try {
    const resteToken = crypto.randomBytes(32).toString("hex");
    this.passwordResetToken = crypto
      .createHash("sha256")
      .update(resteToken)
      .digest("hex");
    this.passwordResetExpires = Date.now() + 10 * 60 * 1000; // 10 دقائق
    
    console.log(this.passwordResetToken);
    console.log(resteToken);

    return resteToken;
  } catch (err) {
    throw new Error(`Errorrrrrrrrrr: ${err}`)
  }
}

// Model
const user_model = mongoose.model("User_Authenticat", schema_user);
module.exports = {
  user_model,
  comparePassword,
  createPasswordResetToken,
};

字符串
创建允许用户更新密码的路径。一切都很好,但是方案中的这个方法createPasswordResetToken的问题根本不起作用。
我确实希望这些属性被保存在数据库中的passwordChangedAt: Date, passwordResetToken: String, passwordResetExpires: Date,,但这并没有发生.
如何使createPasswordResetToken方法起作用,并在用户更新密码时将这些字段passwordChangedAt passwordResetToken passwordResetExpires保存在数据库中

dojqjjoe

dojqjjoe1#

要修复此问题并确保更新密码时执行 createPasswordResetToken 方法,需要在特定用户示例上调用该方法,而不是作为独立函数调用。
以下是如何修改update_password路由处理程序以使其工作:

const update_password = asyncHandler(async (request, response) => {
try {
const { id } = request.user;
const { password } = request.body;
validateMongodbId(id);
const findUser = await user_model.findById(id);

if (password) {
  findUser.password = password;
  const resetToken = findUser.createPasswordResetToken(); // Call the method on the user instance
  await findUser.save(); // Save the updated password and the generated reset token
  response.json({ message: 'Password updated successfully', resetToken });
 }
 } catch (err) {
throw new Error(`Errorrrrrrrrrrrrrrrrrr: ${err}`);
}
});

字符串
在更新后的代码中,我们在findUser示例上调用createPasswordResetToken方法,然后将user对象与更新后的密码和生成的重置令牌一起保存到数据库中。

相关问题