2

I am posting product only if user is Admin, everything is perfect, but unfortunately I am getting "done is not a function" when checking isRevoked token of user. Am I doing anything wrong to check if the user is Admin or not?

I am using express-jwt(7.7.5).

//app.js - File

app.use(authJwt());
app.use(errorHandler);
var { expressjwt: jwt } = require("express-jwt");
const { User } = require("../models/user");

function authJwt() {
    const secret = process.env.secret
    const api = process.env.API_URL;
    return jwt({
        secret,
        algorithms: ['HS256'],
        isRevoked: isRevoked,
    }).unless({
        path: [
            { url: /\/api\/v1\/products(.*)/, methods: ['GET', 'OPTIONS'] },
            { url: /\/api\/v1\/categories(.*)/, methods: ['GET', 'OPTIONS'] },
            `${api}/users/login`,
            `${api}/users/register`,
        ]
    })
}


async function isRevoked(req, payload, done) {
        console.log(payload);
        if (payload.isAdmin == false) {
            console.log('Not Admin');
            done(null, true);
        }
        console.log('Admin');
        done();

}


module.exports = authJwt;
function errorHandler(err, req, res, next) {

    if (err.name === 'UnauthorizedError') {
        // jwt authentication error
        return res.status(400).json({ status: false, message: "User not Authorized" });
    }

    if (err.name === 'ValidationError')
        //Validation error 
        return res.status(401).json({ message: err })

    // default to 500 server error
    console.log("Error Handler = ",err);
    return res.status(500).json({message : err.message});
}

module.exports = errorHandler;
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

3

According to the fine manual, an isRevoked function should accept two arguments and return a Promise. There's no third done argument:

async function isRevoked(req, payload) {
  console.log(payload);
  if (payload.isAdmin == false) {
    console.log('Not Admin');
    return true;
  }
  console.log('Admin');
  return false;
}
robertklep
  • 198,204
  • 35
  • 394
  • 381
1

here is a better way to know if the user is admin or not.

You can try this:

async function isRevoked(req, token) {
  if (token.payload.isAdmin == false) {
    return true;
  }
  return false;
}

or this too, both work for me:

async function isRevoked(req, token){
  if (!token.payload.isAdmin) {
    return true;
  }
}
Danyspb
  • 11
  • 2
0

This is my solution for 'isRevoked' function with TypeScript:

expressjwt({
    secret: SECRET_JWT,
    algorithms: [
        'HS256'
    ],
    isRevoked: (req, token) =>
    {
        let tokenPayload: JwtPayload = <JwtPayload>token!['payload']
        console.log(`Admin : ${tokenPayload['isAdmin']}`)
        return !tokenPayload['isAdmin']
    })
Aref
  • 23
  • 3