Step 8

Let's update the server/routes/notes.js file and add the following middleware:

const checkToken = async (req, res, next) => {
  const { authorization } = req.headers;
  const [_, token] = authorization.trim().split(" ");
  const valid = await verifyToken(token);
  if (!valid) {
    return res.status(403).json({
      message:
        "You are not authorized to access this resource.",
    });
  }
  req.user = decodeToken(token);
  next();
};

Notice how the checkToken function attaches the user data to req.user.

Next, update the routes to use this middleware!

- router.get("/api/notes", async (req, res) => {
+ router.get("/api/notes", checkToken, async (req, res) => {
    // No change is made to the body!
  });

- router.get("/api/notes/:id", async (req, res) => {
+ router.get("/api/notes/:id", checkToken, async (req, res) => {
    // No change is made to the body!
  });

- router.post("/api/notes", async (req, res) => {
+ router.post("/api/notes", checkToken, async (req, res) => {
    // No change is made to the body!
  });

- router.delete("/api/notes/:id", async (req, res) => {
+ router.delete("/api/notes/:id", checkToken, async (req, res) => {
    // No change is made to the body!
  });

- router.put("/api/notes/:id", async (req, res) => {
+ router.put("/api/notes/:id", checkToken, async (req, res) => {
    // No change is made to the body!
  });