title: Creating a middleware function to check if user role is equal to 'Admin'
body: <p>I'm creating a blog using the latest MEAN Stack technologies. A logged in user can create a new user with the roles 'admin' and 'moderator.</p>
  
  <p><a href="https://i.stack.imgur.com/Qr5jL.png" rel="nofollow noreferrer">Creating a new user with an admin role or moderator role</a></p>
  
  <p>This route is protected and currently, only a logged in user can access it. Here is the middleware for checking if the user is authenticated or not.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//check_auth.js
  
  const jwt = require('jsonwebtoken');
  
  module.exports = (req, res, next) =&gt; {
    try {
      const token = req.headers.authorization.split(' ')[1];
      jwt.verify(token,  'my_jwt_secret');
      next();
    } catch (error) {
      res.status(401).json({ message: 'Auth failed!'});
    }
  
  
  };</code></pre>
  </div>
  </div>
  </p>
  
  <p>I apply this middleware to protect unauthorized access to some of my routes. I want to create a similar middleware in which I check if the user is an administrator or not. So I can apply this middleware on the route for creating users, so only an authorized user and a user who has the role of 'admin' can create a new user.</p>
  
  <p>I think this can help in creating the middleware. When a user logs in the id, email, and role is stored in the jwt.  </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>router.post("/login", (req, res, next) =&gt; {
    let fetchedUser;
    User.findOne({ email: req.body.email })
      .then(user =&gt; {
        if (!user) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        fetchedUser = user;
        return bcrypt.compare(req.body.password, user.password);
      })
      .then(result =&gt; {
        if (!result) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        const token = jwt.sign(
          { email: fetchedUser.email, userId: fetchedUser._id, role: fetchedUser.role },
          "my_jwt_secret",
          { expiresIn: "1h" }
        );
        res.status(200).json({
          token: token,
          expiresIn: 3600
        });
      })
      .catch(err =&gt; {
        return res.status(401).json({
          message: "Auth failed"
        });
      });
  });</code></pre>
  </div>
  </div>
  </p>
  
  <p>The whole code can be found in my GitHub repository: <a href="https://github.com/rajotam/Eleven" rel="nofollow noreferrer">https://github.com/rajotam/Eleven</a></p>