Is there a way to limit tasks for different roles, such as admin and users, in an express.js application

In my current project, I have implemented two main roles:

  • Admin
  • User

One of the requirements in my project is to restrict certain tasks for users. For example, only the admin should be able to add new users. However, I am facing an issue where even when logged in as a user, I can still post content. I need to find a solution to this problem. Can anyone provide assistance? My tech stack includes Express.js on the server side, MongoDB for database management, and Angular.js on the client side.

Below is a snippet of my code:

Add User Function:

exports.adduser = function(req, res) {
    delete req.body.roles;

    var user = new User(req.body);
    var message = null;
    // Add missing user fields
    user.provider = 'local';
    user.displayName = user.firstName + ' ' + user.lastName;
    user.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
       // Send mail to user
       agenda.now('New_User_Create_Notify', {data:user.username});
       res.jsonp(user);
        }
    });
};

Route:

app.route('/auth/adduser').post(users.adduser);

Answer №1

in case you've set user roles

you can implement this within the adduser function

if(req.body.roles.indexOf("admin") == -1){
return res.status(403).send({
                message:"user doesn't have required permission"
            });
}else{
   user.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
       //send an email to the user
agenda.now('New_User_Create_Notify', {data:user.username});
res.jsonp(user);

  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Why are double curly brackets used in the JSX syntax of React?

In the tutorial on react.js, a specific usage of double curly braces is highlighted: <span dangerouslySetInnerHTML={{ __html: rawMarkup }} /> Building on this, in the second tutorial titled "Thinking in react" found in React documentation: <sp ...

Generating a dropdown menu in HTML using JSON entities

I am attempting to populate an HTML Select element with data retrieved from JSON. Below is a simplified version of the JSON object: {"Group1": "TestGroup1", "Group2" : "TestGroup2", "TotGroups" : "2"} To achieve this, I am using JQuery and AJAX for fetch ...

Applying left and right margins in Bootstrap container for better spacing

I am in search of a container that adjusts its width based on the page size like Bootstrap containers do, while also maintaining gaps between the container and the edges of the page when it becomes very small. Currently, the container occupies the entire ...

Issue encountered when setting up initial build for application using .NET Core 2.0 and Angular - Unable to locate python, resulting in JavaScript Runtime Error

Operating on VS 2017 and .NET Core 2 with Windows 7. Recently embarked upon creating a new application in .NET Core 2.0 and Angular utilizing these specific instructions. Currently running the most recent editions of node and npm : node -v > v10.1.0 np ...

What is the best way to retrieve values from a multi-dimensional array?

I am working with Angular and have an array named testUsers that contains sample data as shown below: this.testUsers = [ {email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94a5d4f2f5fff1baf7fbf9">[email pr ...

Using jQuery AJAX to Redirect to a 404 Page in Case the Load Method Encounters Failure

My website utilizes AJAX to load all pages using the jQuery load method. I modified this tutorial to work with Wordpress. The issue I am facing now is that when the load method encounters an error (such as a 404 due to a broken link), the AJAX transition ...

What is the best way to ensure that the React useEffect hook is triggered only once following a state change

I am brand new to the world of React hooks and I'm facing a specific challenge. Imagine that we have two states, state1 and state2, and we are using the useEffect hook to call asyncFn1 and update state1. My goal now is to wait for a change in state1 ...

Using JavaScript switch statements to make function calls

While attempting to create an HTML code, I have encountered a roadblock in my coding process. function generateText(elements, type) { for (var i = 0; i<elements.length; i++) { alert(elements[i]); switch (elements[i]) { case "p": ...

Attempting to execute npm install for an Odin project task, encountered the error "Module not Found". // A new error has surfaced, continue reading below

Trying to run npm install for the Odin Project JavaScript Fundamentals Part 4 lesson has been quite a challenge. Initially, upon forking and cloning the repository and running npm install as per the instructions, I encountered a permission error. However, ...

Incorrect calculation of offsetWidth occurs in presence of special characters within text

I'm currently trying to determine the width of a specific text in my scenario. Below is a simple example of my code: var text = "Country <textinbrackets> and some following text"; var textObj = document.createElement('text'); $(textOb ...

Incorporating Bower into an Express project

I recently discovered the Bower scene and decided to integrate it into my current Express project. Following the instructions, I installed it and created the necessary .bowercc and bower.json files. I then added a Bootstrap skin, which also included jQuery ...

Different approach to generating a promise using q

When it comes to creating a promise in Kris Kowal's q library, most developers are familiar with using var defer = Q.defer();, along with calling defer.resolve(); and/or defer.reject() to return defer.promise. However, upon further examination of the ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Sort the objects in the array based on a specific property

Object A contains the following: [{grade:1},{grade:2},{grade:3}] up to 100th. How can I map the existing data (referred to as Object B) onto them? [ {grade:1,name:'alice',address:{poscode:123},tel:324} {grade:5,name:'wonder',address ...

Web page containing information from IPv6 and IPv4 sources exclusively

Is it possible to have an HTML5 page accessible through both IPv4 and IPv6, while only allowing CSS style and JavaScript from other domains via IPv4? Unfortunately, it seems that this setup does not function properly for pure IPv6 connections. Will th ...

The process of converting a string containing a list of object properties into separate objects using JavaScript

I am trying to transform the following string into actual objects. It seems that JSON.parse is not functioning as expected because all the properties are grouped together in a single string instead of being separate. This text string is retrieved from an A ...

The axios method remains dormant even after submitting the form in React

When working with a form that allows file uploads, I encountered an issue where adding the type="submit" attribute to my 'upload' button prevented the axios method in handleSubmit from being called. However, if I remove the type="s ...

Transferring data from Node.js (Express) server to iOS App using Swift 3

I'm currently working on implementing a login system for my iOS mobile app. I've set up a request to my Node.js server using Swift 3: @IBAction func loginBtn(_ sender: UIButton) { //created NSURL let requestURL = NSURL(string: loginURL) ...

The event handler is not defined and is failing to recognize in the React context

Currently, as I delve into the realm of learning React, I find myself facing a perplexing issue regarding the mysterious undefined state of this event handler. Why is it behaving in such an enigmatic manner? const Login = () => { handleSubmit = (e) ...