krekto
krekto

Reputation: 1487

How do i check if user is admin using jwt on sailsjs

I'm using the sailsjs framework on my server side and angularjs on my front end to build a SPA and using jsonwebtoken to do token authentication. My user api has the information: name: string, email: email, admin: Boolean, which are the information I use to generate the token and send to the front end save in localstorage. My question is: how could I do to verify (check if the token is valid already is ready and everything is working) if the user is admin on my server-side?

Thank you in advance.

Below my current policy to check the token on the server-side

module.exports = function(req, res, next) {
  var token;

  if (req.headers && req.headers.authorization) {
    var parts = req.headers.authorization.split(' ');
    if (parts.length == 2) {
      var scheme = parts[0],
        credentials = parts[1];

      if (/^Bearer$/i.test(scheme)) {
        token = credentials;
      }
    } else {
      return res.json(401, {
        err: 'Format is Authorization: Bearer [token]'
      });
    }
  } else if (req.param('token')) {
    token = req.param('token');
    // We delete the token from param to not mess with blueprints
    delete req.query.token;
  } else {
    return res.json(401, {
      err: 'No Authorization header was found'
    });
  }

  sailsTokenAuth.verifyToken(token, function(err, token) {
    if (err) {
      console.log('ERR estou em tokenauth policies');
      return res.json(401, {
        err: 'The token is not valid'
      });

    }

    req.token = token;

    next();

  });
};

Upvotes: 0

Views: 1809

Answers (1)

paulogdm
paulogdm

Reputation: 1801

Do 3 policies:

  • SetJwt: `req.

    sailsTokenAuth.verifyToken(token, function(err, token) {
       if (err) {
          console.log('ERR estou em tokenauth policies');
          return res.json(401, {
             err: 'The token is not valid'
          });
       } else req.token = token
    }
    
  • isAdmin:

    if (req.auth === ADMIN_LEVEL) next()
    else res.forbidden()
    
  • isUser:

    if (req.auth === USER_LEVEL) next()
    else res.forbidden()
    

Your policies:

 someControllerMethod: [setJwt, isAdmin]

Of course you need to add an int or even a flag isadmin in your database for this to work. And the token needs to hold this information!

Upvotes: 2

Related Questions