How to properly add admin user to a database?

Viewed 267

Let's say I have an endpoint for posting new users with a logic like this:

    ...
    user = new User(_.pick(req.body, ['name', 'email', 'password', 'isAdmin']));
    const salt = await bcrypt.genSalt(10);
    user.password = await bcrypt.hash(user.password, salt);

    await user.save();

    const token = user.generateAuthToken();
    ...

This would work but now of course every user could set the isAdmin flag. Another way would be adding admin users manually to the database but this is probably not the best way.

Is there a recommended way to solve this problem?

2 Answers

You can do as below:

Step 1 : Create one superadmin manually give isAdmin = 2

Step 2 : Above created superadmin can only add/register sub admin, give isAdmin = 1

Step 3: And last, from normal regostration, you can give isAdmin = 0

so isAdmin = 2 (superadmin), isAdmin = 1 (subadmin) and isAdmin = 0 (normal user)

Note: 2,1 value for isAdmin is my suggestion, you can change if you want as per your requirements.

As @Devsi Odedra mentionned, you can add a superadmin user (say level 0) manually in your database, or using JS script (node initDb.js for example).

Then, whenever a user wants to add another user, you can just check that he is not adding a user with same privileges, that each user can only add a user with n + 1. This way, the superadmin user will on be able to add users with a level >= 1, and so on.

Related