Auth rules with Nodejs + Passport + Mongodb

Asked

Viewed 482 times

1

Let’s doubt it. I’m using a blog as an example. I have the Administrator. He does a complete CRUD within the system. Besides it I have the Editor and Reviewer. The Editor creates blog posts but does not publish. And the Reviewer, sees and suggests editing in the post created by the Editor. The Administrator does anything. Creates post, gives permission to the Editor and Reviewer. Deletes, blocks Users. The Editor creates and updates post. And the Reviewer only suggests changes to the post. It’s a user access level system. There are several tutorials on the use of Passport, but none that help in this doubt.

I’m using this base: Passport-Mongo

2 answers

0

When creating the JWT token, you can store information within it, such as the user id, the user name, and the access level him. Having its access level, you can create a middleware that checks whether the access level of that JWT is valid or invalid, and if valid, allows access to that route.

In the code below, I created a middleware that checks whether JWT is valid, and if so, stores its information in req.usuario.

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  jwt.verify(req.headers['x-access-token'], process.env.JWT_SECRET, (err, decodedToken) => {
    if (err) return res.status(401).json({ error: 'Você não tem autorização para continuar!' });

    req.usuario = decodedToken;
    return next();
  });
};

In the code below, I created a middleware that checks the access level of req.usuario.

module.exports = (nivel) => {
  return (req, res, next) => {
    if (!req.usuario.nivel || req.usuario.nivel < nivel) return res.status(401).json({ error: 'Você não tem autorização para continuar!' });
    return next();
  };
};

If you want a full example, I have a repository that I use to study React.js, but I’ve already implemented the authentication part. https://github.com/andreolvr/aprendendo-react

The codes you’re interested in are in server/middleware and app.js, to see how I apply this middleware to routes.

0

JWT does not solve this problem, JWT is a specification RFC 7519 message exchange using JSON, Tokens and how to do this in an encrypted way. What you want is to control user access levels, you can continue to do what you would do with PHP, as you mentioned, and exchange messages between your API and your APP "using" JWT

Browser other questions tagged

You are not signed in. Login or sign up in order to post.