Skip to content

How to properly add admin user to a database?

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);
    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?


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.