Report this

What is the reason for this report?

In node.js, how to assign admin role for user who registers first and rest of them should be different?

Posted on September 24, 2020

There should be two models Users and User_Roles. First time when user registers, the User_Roles table should contain value as admin for that user and for rest of them it should be different. with support of node.js?



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hello,

There are many ways to implement this in Node.js, and the exact details will depend on your specific setup. For the purpose of this example, let’s assume that you are using Express.js and a MongoDB database with Mongoose as the Object Data Modeling (ODM) library. This example also assumes that you are using bcrypt for password hashing and jsonwebtoken for generating auth tokens.

Firstly, you need to define your User and User_Role schemas in Mongoose.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: String,
  password: String,
  role: { type: Schema.Types.ObjectId, ref: 'Role' }
});

const RoleSchema = new Schema({
  name: String
});

const User = mongoose.model('User', UserSchema);
const Role = mongoose.model('Role', RoleSchema);

module.exports = { User, Role };

In your registration endpoint, you could check if there is any user in the database. If there are no users, you assign the new user an admin role. Otherwise, you give them a different role.

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { User, Role } = require('./models');

const router = express.Router();

router.post('/register', async (req, res) => {
  const { username, password } = req.body;

  // Check if user already exists
  const existingUser = await User.findOne({ username });
  if (existingUser) {
    return res.status(400).send('User already exists');
  }

  // Check if this is the first user
  const users = await User.find();
  let role;
  if (users.length === 0) {
    // This is the first user. Assign them the admin role
    role = await Role.findOne({ name: 'admin' });
  } else {
    // This is not the first user. Assign them a different role
    role = await Role.findOne({ name: 'user' });
  }

  // If no roles were found, return an error
  if (!role) {
    return res.status(500).send('Role not found');
  }

  // Hash the password
  const hashedPassword = await bcrypt.hash(password, 10);

  // Create the new user
  const user = new User({ username, password: hashedPassword, role: role._id });
  await user.save();

  // Generate an auth token
  const token = jwt.sign({ id: user._id, role: role.name }, 'your_jwt_secret');

  res.json({ token, username, role: role.name });
});

module.exports = router;

This example assumes that the roles ‘admin’ and ‘user’ already exist in the Role collection of your MongoDB database. You can create these roles manually or include a script in your server initialization code to ensure these roles exist.

Best,

Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.