Auth rules with NodeJS + Passport + MongoDB [closed]

1

Let's doubt it. I am using a blog as an example. I have the Administrator. It makes a full CRUD inside the system. In addition to 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, from permission to Editor and Reviewer. Delete, block Users. The editor creates and updates post. And the Reviewer only suggests changes in the post. It is 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 database: passport-mongo

    
asked by anonymous 18.11.2016 / 17:26

2 answers

0

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

    
18.11.2016 / 19:34
0

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

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

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 the user.

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 an example, complete, I have a repository that I use to study React.js, but I've already implemented the authentication part. link

The codes that interest you are in server / middleware and app.js, to see how I apply this middleware in the routes.

    
19.11.2016 / 03:02