T
T
takoyklasnii2019-10-17 14:02:01
JSON Web Token
takoyklasnii, 2019-10-17 14:02:01

How to make middleware jwt?

When registering, I have the following code:

const userRegistration = (req, res) => {
  try {
    if (req.body && req.body.login) {
      User.findOne({ where: { login: req.body.login } }).then(r => {
        if (r === null) {
          const hashedPassword = bcrypt.hashSync(req.body.password, 10);
          const token = jwt.sign({ login: req.body.login }, "secret", {
            expiresIn: "1h"
          });
          User.create({
            login: req.body.login,
            username: req.body.username,
            password: hashedPassword,
            role: "user"
          }).then(() => {
            res.json({
              status: true,
              user: {
                login: req.body.login,
                username: req.body.username,
                token: token,
                role: "user"
              },
              message: "User was created!"
            });
          });
        } else {
          res.json({
            message: "Body data already taken!"
          });
        }
      });
    } else {
      res.json({
        message: "Body request is incorrect!"
      });
    }
  } catch (error) {
    res.json({
      message: error
    });
  }
};

I am getting a jwt token.
Here is my middleware:
const ProtectedRoute = (req, res, next) => {
  let token = req.headers["x-access-token"] || req.headers["authorization"];
  if (token) {
    if (token.substr(0, 6) === "Bearer") {
      token = token.slice(7, token.length);
    }
    jwt.verify(token, secret, (err, decoded) => {
      console.log(decoded);
      req.login = decoded;
      next();
    });
  } else {
    res.json({
      message: "Invalid token!"
    });
  }
};

Do I need to make a request to bd in the middleware and check if there is such a user?
Should I write down all the data (login, username, password) and generate a token and then check the data in the middleware in the same way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2019-10-17
@Nc_Soft

Yes, it's better to check the existence of the user in the middleware.
And it’s better to switch to async / await, otherwise you won’t look at noodles from promises without tears.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question