Home > Net >  User Roles and rules(permission) access in node.js
User Roles and rules(permission) access in node.js

Time:06-07

I created a node.js application (Bus-ticket-booking app). MongoDB is the database system I'm using. I haven't yet finished the front end. I'm doing API queries with Postman.

For authentication, I'm using JWT. Now I want to add roles and rules for users such as the app's administrator, supervisor, and normal user.

1 -> A user can have many roles assigned to them (admin, supervisor).

2 -> Permissions can be assigned to a role ( Create, Update, delete etc...).

As a result, a user can have one or more roles, and each role can have one or more permissions. A user can use APIs for which he has rights, such as creating data, deleting data, updating data, and so on.

Here is the user schema:

const userSchema = new mongoose.Schema({
  firstname: {
    type: String,
    required: true,
  },
  lastname: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw new Error("Please provide the valid email address");
      }
    },
  },
  password: {
    type: String,
    required: true,
    trim: true,
    minLength: 8,
  },
  phone: {
    type: Number,
    required: true,
    unique: true
  },
  tokens:[{
    token: {
      type: String,
      required:true
    }
  }]
},{
  timestamps:true
});

I'm new to it and have very little knowledge about it.

Is there anyone who can assist me?

CodePudding user response:

You should try to watch a full course on express and mongodb but you would have to add fields in the user schema that specifies if the user has permissions i.e admin: { type: booleen, default: false } then set the booleen to true if you want the user to be admin then create a route for something only admin sould be able to do lets say to delete a user so then in there check if the admin field in user schema is true. If so then user can delete otherwise throw err. it would be really helpful if you were to provide code snippets and other helpful links learn more here: https://stackoverflow.com/help/how-to-ask

edit:

Do keep in mind im using mongodb atlas for the code

Add an admin field (or any role that you want im gonna go with admin here) so change

const userSchema = new mongoose.Schema({
  firstname: {
    type: String,
    required: true,
  },
  lastname: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw new Error("Please provide the valid email address");
      }
    },
  },
  password: {
    type: String,
    required: true,
    trim: true,
    minLength: 8,
  },
  phone: {
    type: Number,
    required: true,
    unique: true
  },
  tokens:[{
    token: {
      type: String,
      required:true
    }
  }]
},{
  timestamps:true
});

to this

const userSchema = new mongoose.Schema({
  admin: {
    type: Booleen,
    default: false,
  },
  firstname: {
    type: String,
    required: true,
  },
  lastname: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw new Error("Please provide the valid email address");
      }
    },
  },
  password: {
    type: String,
    required: true,
    trim: true,
    minLength: 8,
  },
  phone: {
    type: Number,
    required: true,
    unique: true
  },
  tokens:[{
    token: {
      type: String,
      required:true
    }
  }]
},{
  timestamps:true
});

I just added the admin field in the user schema

Then lets say you only want the admin to be able to delete users for that you would have to create a route like this

router.delete("/delete/:id", async (req, res) => {
  try {
    // First find the user admin wants to delete
    const user = await User.findById(req.params.id) // getting id from the id you put in url

    // Make sure the user who wants to delete another user is an admin
    if (user.admin) {
       await user.deleteOne() // This deletes the user
    } else {
       res.status(403).json("You are not allowed to do this action!")
    }
  } catch (error) {
    res.sendStatus(500);
  }
});
  • Related