User Authentication with the MEAN Stack - Adding Role Users

Hi,

I created a MEAN stack application.
I set up a user authentication with Passport module following a tutorial available on this website. This works properly.

However, I would like to add admin users and I would like some advice. I thought about adding a parameter in my User model like this:


const userSchema = new Schema({
  _id: {
    type: Schema.Types.ObjectId,
    required: true
  },
  firstname: {
    type: String,
    required: true
  },
  lastname: {
    type: String,
    required: true
  },
  email: {
    type: String,
    unique: true,
    required: true
  },
  admin: {
    type: boolean,
    unique: true,
    required: true
  },
  hash: String,
  salt: String
});

Is it a good idea or there is a better method ?

That would work, but would mean manually checking if a user is an admin before performing certain actions. Also it is not very future-proof in that adding further roles would involve you adding a new field to the database and even more checks when determining who is authorized to do what.

A better approach IMO would be to change your “admin” field to “role” and use an authorization library to explicitly declare which roles may perform which actions. I’d recommend something like CanCan which has a concise and expressive API.

For example (from their docs):

// allow users to view all public posts
allow(User, 'view', Post, {public: true});

// allow users to edit and delete their posts
allow(User, ['edit', 'delete'], Post, (user, post) => post.authorId === user.id);

// allow editors to do anything with all posts
allow(Editor, 'manage', Post);

// allow admins to do anything with everything
allow(AdminUser, 'manage', 'all');

Also, note the difference between authentication (the process of ascertaining that somebody is who they claim to be) and authorization (determining who is allowed to do what).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.