DEV Community

Cover image for Secure Todos Rest APIs with JWT Authentication
Aneeqa Khan
Aneeqa Khan

Posted on

Secure Todos Rest APIs with JWT Authentication

Table of Contents

For this series, I'm following an excellent video tutorial from Traversy Media

Introduction

In our ongoing journey to fortify the security of our application, we revisit the protect middleware introduced in our previous blog. This middleware, a key component in safeguarding our routes, ensures that only authenticated users can access the todos functionality. In this post, we'll dive into the integration of this middleware within the todoRoutes.js file.

Integrate Protect Middleware

We'll use the protect middleware we created in the previous blog to secure the todos routes.
In the todoRoutes.js file, we'll import it and use it like this.

...
const { protect } = require("../middleware/authMiddleware");

router.route("/").get(protect, getTodos).post(protect, setTodo);
router.route("/:id").put(protect, updateTodo).delete(protect, deleteTodo);

...
Enter fullscreen mode Exit fullscreen mode

Set User Todo

Previously we added a function setTodo in todosController but it only saved todos in the database without any user.
Now we want to store todos respective to the user.

const setTodo = asyncHanlder(async (req, res) => {
  // ... existing logic
  const todo = await Todo.create({
    text: req.body.text,
    user: req.user.id, // associating the todo with the logged-in user 
  });
  // ... remaining logic
});
Enter fullscreen mode Exit fullscreen mode

Get User Todos

To get only current logged-in user todos, we'll add this line to the getTodos function in todosController.

const getTodos = asyncHanlder(async (req, res) => {
  const todos = await Todo.find({ user: req.user.id });
  res.status(200).json(todos);
});
Enter fullscreen mode Exit fullscreen mode

Update and Delete User Todo

Next, we are securing the Update and Delete Todos function so that only a user can update and delete their own Todos.
We'll paste these lines in both functions after checking for todos and before updating and removing them.

...
const User = require("../models/userModel");
// ... existing logic
  const user = await User.findById(req.user.id);

  // check for user
  if (!user) {
    res.status(401);
    throw new Error("User not found");
  }

  // make sure the logged in user matches the todo user
  if (todo.user.toString() !== user.id) {
    res.status(401);
    throw new Error("User not authorized");
  }
// ... remaining logic
Enter fullscreen mode Exit fullscreen mode

In the above code, we are getting the logged-in user and throwing an error if it doesn't match with the todos user.

Connect with me

Top comments (0)