使用nodejs和mongodb atlas生成的代码验证电子邮件

问题描述 投票:0回答:1

这是我的研究项目,我是Stack AT Mongodb,当用户收到生成的代码并将其放在用户文档编辑的我的客户端上时,他无法登录,因为bcrypt不一样!或者用户文档已删除

这里是注册请求

addUserForManager: async (req, res) => {

    try {
      const { user_name, user_email, user_password, user_phone, user_address } =
        req.body;

    
      function generateValidationCode() {
        return Math.random().toString(36).substring(2, 8).toUpperCase();
      }


      const validationCode = generateValidationCode()

      const mailOptions = {
        from: 'hanidanial2019@gmail.com',
        to: user_email,
        subject: `Hello, ${user_name}!`, 
        html: `
        <html>
          <body style="text-align: center;">
            <h1>Welcome to Our Customer</h1>
            <p>Thank you for joining our customer community!</p>
            <p>Your validation code: <strong  style="font-size: 24px; ">${validationCode}</strong></p>
          </body>
        </html>
      `,
      };


  const new_model = new Model({
        user_name,
        user_email,
        user_password,
        validationCode:validationCode,
        user_phone: user_phone || "",
        user_address: user_address || "",
      });

      await new_model.save();
      sendEmail(mailOptions)

      // return success message
      return res.status(200).json({
        success: true,
        message: `success to add new ${controler_name}`,
      });
    } catch (error) {
      return res.status(500).json({
        message: `error in add ${controler_name}`,
        error: error.message,
      });
    }
  }

这是handleValidcode

async (req,res)=>{

    
  const {email, verificationCode} = req.body  
    console.log(email, verificationCode)
      try {
        const user = await Model.findOne({ user_email: email, validationCode: verificationCode });
    
        if (user) {
          // Mark the email as validated
          user.isEmailValidated = true;
          user.createdAt = Date.now()

          await user.save();
          console.log('Email validation successful.');

          return res.status(201).json({
            message: `The Validation is done Successfully `,
          });


        } else {
          console.error('Email validation failed: Invalid code or email.');
          return false;
        }
      } catch (error) {
        console.error('Error verifying email:', error);
        return false;
      }
    },

  
  updateUserByIdForManager: async (req, res) => {
    try {
      const id = req.params.user_id;

      if(req.body.user_name == ''){
        delete req.body.user_name
      }
      if(req.body.user_email == ''){
        delete req.body.user_email
      }
      if(req.body.user_password == ''){
        delete req.body.user_password
      }
      if(req.body.user_phone == ''){
        delete req.body.user_phone
      }
            
      const user = await Model.findById(id)
      
      Object.assign(user,req.body)

      const updateUser = await user.save();

      // await Model.findByIdAndUpdate(id, req.body).exec();

      return res.status(200).json({
        success: true,
        message: `success to update ${controler_name} by id`,
        updateUser
      });
    } catch (error) {
      return res.status(500).json({
        message: `error in update ${controler_name} by id`,
        error: error.message,
      });
    }
  },
};

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const Schema = mongoose.Schema;

const user_schema = new Schema({
  user_name: {
    type: String,
    required: true,
    unique: false,
  },

  user_email: {
    type: String,
    unique: true,
    lowercase: true,
    required: true,
  },

  user_password: {
    type: String,
    required: true,
  },

  user_phone: {
    type: String,
    match: /^([0]\d{1,3}[-])?\d{7,10}$/,
  },

  user_address: {
    city: {
      type: String,
      trim: true,
    },
    street: {
      type: String,
      trim: true,
    },

    building: {
      type: String,
      trim: true,
    },

    appartment: {
      type: String,
      trim: true,
    },
  },
  user_cart: {
    type: mongoose.Types.ObjectId,
    ref: "carts",
  },

  user_orders: [
    {
      order: {
        type: mongoose.Types.ObjectId,
        ref: "Orders",
      },
    },
  ],

  validationCode: String,

  isEmailValidated: {
    type: Boolean,
    default: false, 
  },

  createdAt: {
    type: Date,
    expires: "60m",
    default: Date.now,
  },

  tokens: [{ type: Object }],
});

user_schema.pre("save", async function (next) {
  try {
    const hash = await bcrypt.hash(this.user_password, 15);
    this.user_password = hash;
    next();
  } catch (error) {
    next(error);
  }
});

module.exports = mongoose.model("Users", user_schema);

如果 15 分钟内未提供代码,我该怎么做才能删除用户! 如果用户提供代码,我不需要删除用户文档

我尝试通过发送用户生成的代码来验证用户电子邮件,然后用户将其发送回服务器,然后他就可以开始了!

问题是当他验证并且用户无法再次登录并且文档从 mongodb 中删除时 **或者 ** bcrypt 无法比较两个密码,总是出现错误

node.js reactjs mongodb nodemailer bcrypt
1个回答
0
投票

您无法将旧的 Bcrypt 哈希值与新的 bcrypt 哈希值进行比较。 Bcrypt 总是为相同的文本返回一个新的哈希值。为了将新哈希与新文本进行比较,您需要使用

bcrypt.compare
函数。

为此,首先您需要删除用于保存时进行哈希处理的预保存代码,并对请求本身进行哈希处理。手动将哈希添加到您的第一个请求中。然后,在您第二次请求验证验证码时,请使用 bcrypt.compare。这将需要两个参数。第一个是原始文本(密码),第二个是数据库针对用户返回的密码哈希值。

const bcrypt = require('bcrypt');

async function comparePasswords(newText, hashedPassword) {
  try {
    // Use bcrypt.compare to check if the new text matches the old hashed password
    const match = await bcrypt.compare(newText, hashedPassword);

    if (match) {
      console.log('Password matches.');
      return true;
    } else {
      console.log('Password does not match.');
      return false;
    }
  } catch (error) {
    // Handle any errors that may occur during the comparison
    console.error(error);
  }
}

// Example usage:
const hashedPassword = 'hashed_password_here'; // Replace with the actual hashed password from Db
const newText = 'new_text_to_compare'; // Raw password

comparePasswords(newText, hashedPassword);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.