skip to Main Content

This is my project for the study and I am Stack AT Mongodb when user receive the generated code and put it on my client side the user doc edited and then he can’t log in because the bcrypt is not the same ! or the user doc deleted

here the SignUp Request

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: '[email protected]',
        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,
      });
    }
  }

and here is the 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);

what should i do to delete the user if the code not provided by 15 min !
and if the user provide the code i dont need to delete the user doc

Im trying to make validation on user e-mail by sending the user generated code then the user send it back to server and he is ready to go !

the problem is when he validated and user can’t login in again and the doc deleted from mongodb
**or **
the bcrypt can’t compare two password always getting false

2

Answers


  1. you can’t compare old Bcrypt hash with new bcrypt hash. Bcrypt always returns a new hash for same text. In order to compare new hash with new text, you need to use bcrypt.compare function.

    For this, firstly you need to remove the pre save code for hashing on saving and do the hashing on the request itself. Add hashing to your signup request manually.

    Then on your second request to validate the verification code use bcrypt.compare. This will take two parameters. First one will be raw text (Password), and the second one will be the password hash returned from the database against the user.

    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
    
    async comparePasswords(newText, hashedPassword);
    
    Login or Signup to reply.
  2. Dont delete the user document, when the user tries to login with same email update old code. And resend new code.
    And also use bcrypt.compare as @Mr Khan

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search