Search code examples
node.jsjwtkoastrapikoa2

How to extract information from a JWT in node js without any module?


hellow, could you helpme please?

I am trying to create a function to protect a POST and DELETE method.

I have the problem that all authenticated users of my application have the ability to delete the posts of other users if they know the id of that post.

In my table relationship the user has a one to many relationship with the posts and the posts a relationship that each property has a user

I thought the best way to avoid this was to extract the Headers token in some way and compare it with the user id that saves each post

I am using the sqlite database and working with Strapi

in another api use this module in a middleware but I don't know very well how to apply this in satrapi and the documentation is a bit confusing

const jwt = require('jsonwebtoken');

/*==============
verify token
================*/

let verificarToken = (req, res, next) => {

    let token = req.get('token')


    /*res.json({
        ok:true,
        token: token
    })*/

    jwt.verify(token, process.env.SEED_TOKEN, (err, decoded) => {           

        if (err) {
            return res.status(401).json({
                ok: false,
                err: "token invalido"

            });
        }


        req.usuario = decoded.usuario;
        next();
        /* el next ejecuta la siguiente peticion luego de haber pasado el middleware*/
    })
}

Solution

  • You could do the following after fiding the requesting user (as you have found above)

    1. Create a middleware before accessing the delete function.
    2. In that middleware create a function that checks whether the post id belongs to the requesting user.
    3. If yes allow them to access the next function or return 'bad request'.