JWT Verify broke my routes?

I have no idea what the heck is happening anymore. The routes were working perfectly without touching the code, and then it all broke. Now only the POST works, but the DELETE gives me an unauthorized. I am passing the token through the state and sometimes gets
Screen Shot 2020-03-06 at 6.12.08 PM
or jwt not provided.

import { Router } from 'express'
const router = Router()
import knex from '../../knex'
import { verify } from 'jsonwebtoken'
import {} from ('dotenv').config()


// Middleware to check token in header
const jwtVerify = (req, res, next) => {
	verify(req.headers.token, process.env.PASSWORD, (err, _payload) => {
		if (err) {
			err.status = 401
			err.message = `Unauthorized - You are not Chizette!`
			return next(err);
		} else {
			req.payload = _payload
			next()
		}
	})
}

// Middleware to check ID
const checkIdisNum = (req, res, next) => {
  if (isNaN(req.params.id)) {
    let err = new Error(`Id not found`)
    err.status = 400
    throw err
  }
  next()
}

// Read all records in DB
router.get('/', (req, res, next) => {
  knex('chizetteart')
    .orderBy('updated_at', 'desc')
    .orderBy('id')
    .then((rows) => {
      res.json(rows)
    })
    .catch((err) => {
      next(err)
    })
})

// Get one record in DB
router.get('/:id', checkIdisNum, (req, res, next) => {
  knex('chizetteart')
    .where('id',req.params.id)
    .then((rows) => {
      res.json(rows)
    })
    .catch((err) => {
      next(err)
    })
})

// Create one record and post to DB
router.post('/', jwtVerify, (req, res, next) => {
  knex('chizetteart')
    .insert({
      "title": req.body.title,
      "year": req.body.year,
      "medium": req.body.medium,
      "poster": req.body.poster,
      "price": req.body.price
    })
    .returning('*')
    .then((data) => {
      res.json(data[0])
    })
    .catch((err) => {
      next(err)
    })
})

// Edit one record in DB
router.put('/:id', jwtVerify, checkIdisNum, (req, res, next) => {
  knex('chizetteart')
  .where('id', req.params.id)
  .then((data) => {
    knex('chizetteart')
    .where('id', req.params.id)
    .limit(1)
    .update({
      "title": req.body.title,
      "year": req.body.year,
      "medium": req.body.medium,
      "poster": req.body.poster,
      "price": req.body.price
    })
    .returning('*')
    .then((data) => {
      res.json(data[0])
    })
  })
  .catch((err) => {
    next(err)
  })
})

// Delete one record
router.delete('/:id', jwtVerify, checkIdisNum, (req, res, next) => {
  knex('chizetteart')
    .where('id', req.params.id)
    .first()
    .then((row) => {
      if(!row) return next()
      knex('chizetteart')
        .del()
        .where('id', req.params.id)
        .then(() => {
          res.send(`ID ${req.params.id} Deleted`)
        })
    })
    .catch((err) => {
      next(err)
    })
})

export default router

I never touched the code. I’m ready to throw my computer out the window.

Hello!

Can you provide the client code? (the code that requests the information). I think the code you’ve provided is OK, so it may be a problem on the client.

1 Like

Yup, here is it:

// Admin — Create new art
  const postArt = async (title, year, medium, url, price) => {
    const artBody = {
      title: title,
      year: year,
      medium: medium,
      poster: url,
      price: price
    }
    const response = await fetch(`${API}/chizetteart`, {
      method: "POST",
      mode: "cors",
      cache: "no-cache",
      credentials: "same-origin",
      headers: {
        "Accept": "application/JSON",
        "Content-Type": "application/json",
        "token": token
      },
      body: JSON.stringify(artBody)
    })
    if (response.status !== 200) {
      alert(`Unable to create this masterpiece!`)
    } else {
      alert(`Art Created!`)
    }
    setArtList([artBody, ...artList])
  }

  // Admin — Edit art
  const editArt = async (id, title, year, medium, url) => {
    const artBody = {
      title: title,
      year: year,
      medium: medium,
      poster: url
    }

    let newList = artList.map( art => (art.id === id) ? {id, ...artBody} : art )
  
    let response = await fetch(`${API}/chizetteart/${id}`, {
      method: "PUT",
      mode: "cors",
      body: JSON.stringify(artBody),
      headers: {
        "Accept": "application/JSON",
        "Content-Type": "application/json",
        "token": token
      },
    })
    if (response.status !== 200) {
      alert(`Unable to edit this masterpiece!`)
    } else {
      alert(`Edited this masterpiece!`)
    }
    
    setArtList(newList)
  }

  // Admin — Delete art
  const deleteArt = async (id) => {
    let response = await fetch(`${API}/chizetteart/${id}`, {
      method: "DELETE",
      mode: "cors",
      headers: {
        "Accept": "application/JSON",
        "Content-Type": "application/json",
        "token": token
      },
    })
    if (response.status !== 200) {
      alert(`Unable to erase this masterpiece!`)
    } else {
      alert(`Crumbled up and thrown away!`)
    }
    setArtList([...artList])
  }

All of my protected routes I am unauthorized for. Perhaps I’m not passing a valid token now? This code was working for a year and a half. I’m still very stuck. If anyone has an idea, I’m all ears.

Hmm, I’m unable the see the problem :sweat:.

What about the login code and the one that generates the token? Are they OK? Would you be willing to publish your source code so we can test it?

In the mean time, the things you can try:

  1. Check the developer console to see if there are any other errors when the requests are sent (usually pressing F12 or Control + Shift + i with your website open on the browser).
  2. Recheck your the code that’s not shown here but it’s used on the requests. For example, the login path.