,

Day 5: Mastering MERN Stack CRUD – Updating Password API in an Employee Management System

Posted by


In Day 5 of our Advanced MERN Stack CRUD series, we will be focusing on creating an API for updating a user’s password in our Employee Management System. This API will allow users to securely change their passwords whenever they need to.

To get started with this tutorial, make sure you have already set up your MERN stack project and have a basic understanding of CRUD operations and API development in Node.js.

Step 1: Update Password API Endpoint
First, we need to create a new API endpoint in our Node.js server for updating the user’s password. Create a new route in your server.js file that listens for PATCH requests to /api/users/:id/password. This endpoint will require the user’s ID in the URL and the new password in the request body.

app.patch('/api/users/:id/password', async (req, res) => {
  try {
    const { id } = req.params;
    const { newPassword } = req.body;

    // Update user's password in the database
    const user = await User.findById(id);
    user.password = await bcrypt.hash(newPassword, 10);
    await user.save();

    res.status(200).json({ message: 'Password updated successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

In this code snippet, we are first extracting the user’s ID from the URL parameters and the new password from the request body. We then retrieve the user from the database using the ID, hash the new password using bcrypt, and save the updated user back to the database. Finally, we send a success message back to the client.

Step 2: Test the Update Password API Endpoint
To test our new API endpoint, we can use an API testing tool like Postman. Send a PATCH request to http://localhost:5000/api/users/:id/password with the user’s ID in the URL and a JSON body containing the new password.

{
  "newPassword": "newpassword123"
}

If everything is set up correctly, you should receive a response with a status code of 200 and a message saying "Password updated successfully".

Step 3: Securing the Update Password API
It is essential to secure our password update API to prevent unauthorized access. You should implement authentication and authorization mechanisms to ensure that only the user who owns the account can change the password.

One way to do this is by adding middleware to verify the user’s identity before allowing them to update their password.

const verifyToken = (req, res, next) => {
  const token = req.header('Authorization');

  if (!token) {
    return res.status(401).json({ error: 'Unauthorized access' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

app.patch('/api/users/:id/password', verifyToken, async (req, res) => {
  // API code goes here...
});

In this code snippet, we are adding a verifyToken middleware function that checks for a valid JWT token in the request header. If the token is present and valid, we decode it and attach the user’s information to the request object. We then call the next() function to allow the request to proceed to the password update API code.

Step 4: Conclusion
In this tutorial, we have learned how to create an API for updating a user’s password in our Employee Management System. We have implemented a secure endpoint that allows users to change their passwords safely. Remember to always secure your APIs to protect sensitive user data and prevent unauthorized access.

I hope this tutorial was helpful and that you were able to follow along successfully. Stay tuned for Day 6, where we will cover more advanced CRUD operations in our MERN stack application. Happy coding!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@codeviseofficial
3 months ago

ASSALAM O ALAIKUM doston video short ha par important ha kion ka bohat sa logon ko update password wali api main problem ati ha to ham na har cheez ko acha sa samjha ha aur video choti ha to lazmi puri daikhna. Aur un sab bhaion ka shukria jo hamara content ko pasand kar ta hain aur ham sa kuch naya seekh ta hain.