Search code examples
node.jstypescriptmongoosejwtexpress-jwt

JWT admin role checking in nodeJS


How can I check whether the data modification (on the site) was created by user Or by admin?

I'm using JWT, nodeJS, typescript (and postman for testing)

This is my "get all user" method:

UserSchema:

export const userSchema = new Schema({
 username: { type: String, required: true, unique: true },
 firstName: { type: String, required: true },
 lastName: { type: String, required: true },
 email: { type: String, required: true, unique: true },
 password: { type: String, required: true },
 isAdmin: { type: Boolean }
}

UserRoute:

    public getAll = async (req: any, res: any) => {
    try {
        const users = await User.find({}).exec();
        res.status(200).json(users);
    } catch (err) {
        res.status(400).json(err);
    }
}

Should I just extend it with a condition?

let user = await User.findById(req.params.id).exec();
if(user.isAdmin)
{
     //CODE
}
else
{
    res.status(400).json(err);
}

Or there is any better implementation for this? Thanks


Solution

  • You can use Implemented code as Middleware.

    Instead of:

    in your user class:

    public IsAdmin(req: any, res: any, next: any) {
      //CODE GOES HERE 
    }
    

    in your route file:

    instead of this:

    app.get("/alluser", getall);
    

    write this:

    app.use(User.IsAdmin);
    app.get("/alluser", User.IsAdmin, User.getall);
    

    app.use() provide the middleware will be called.