What is the best way to assign specific tasks to various user roles?

In my management system, users can register and manage the platform using CRUD operations. I want to restrict the privilege of adding, updating, and deleting other users only to the admin role. If a user is not an admin, they should only be able to use the search function. However, the currentAccount (active user) stored in sessionStorage lacks information about the user's role:

{id: 1, password: "111111", type: "0", userName: "admin"}

There is no indication of the user's role included in the current storage setup as shown here:

(user.type === "0" ? "Normal User" : "Administrator")
I am utilizing the above line to display the user's role on the browser. The user class implemented in Java initially looks like this:

public class User implements Serializable {
    private int id;
    private String userName;
    private String password;
    private String type;
    ----------
    ----------
    ----------
    ----------
}

The structure of my add function is as follows:

function addUser() {
   popWindow("add_user.html", "add user");
}

This is how my delete function is set up:

function deleteUser(id) {
      let form = document.querySelector("#queryForm");
      let formData = new FormData(form);
      formData.append("action", DELETE);
      formData.append("ids", id);
      sendPost("/SMS/user", formData2Url(formData), handleDelete);
}


function handleDelete() {
      search();
}

function search() {
      let form = document.querySelector("#queryForm");
      let formData = new FormData(form);
      formData.append("action", QUERY);
      sendPost("/SMS/user", formData2Url(formData), handleQuery);
}

Here is how my update function is structured:

function updateUser(user) {
   sessionStorage.setItem("user2Delete", JSON.stringify(user));
   popWindow("update_user.html", "update user");
}

I am considering iterating through a list of users, locating the user within the currentAccount object, and retrieving their type. However, this approach does not seem effective. Is there a more optimal method to achieve this?

Answer №1

Utilizing Decorators can be likened to enveloping your function within another one. By using decorators, you have the ability to verify if the user has admin privileges. If yes, then execute the function; if not, do nothing. This is useful when you have a class and need certain properties to be read-only.

class Oatmeal extends Porridge {
  @readOnly viscosity = 20;
  // (you can also put @readOnly on the line above the property)

  constructor(flavor) {
    super();
    this.flavor = flavor;
  }
}

The decorator @readonly would appear as follows:

function readOnly(target, key, descriptor) {
  return {
    ...descriptor,
    writable: false,
  };
}

For more insight into Decorators, check out this informative resource: https://blog.logrocket.com/understanding-javascript-decorators/

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

Can you explain how to convert a 32-bit floating point number from a Buffer to a JSON string in NodeJS while maintaining the original precision?

Given a buffer with single precision float numbers (32 bits, little endian), the goal is to create a JSON string holding those numbers while maintaining their original values without any loss of precision. The challenge lies in the fact that when a value ...

Establishing the bottom limit for the vertical axis on a column chart with the Visualization Google API

I am currently working on implementing the Google Chart API alongside AngularJS. I attempted to adjust the min property of the vertical axis for my column chart to 0 using the following code: var dataMois = CaDuMois.query(function(){ $scope.comparat ...

Tips for incorporating Javascript in an innerHTML inline css situation

I'm just starting to learn about html5 and php. I'm curious about how to incorporate javascript into my existing code. Currently, I have data from a database displayed in an HTML table. My goal is to align the output of the last cell more toward ...

The point in the vector data is incorrectly positioned on the map in OpenLayers

I am looking to display a world map using the default OpenLayers WMS, along with a single point on it that will have interactive events like onhover. Below is my code snippet: var options = { projection: ...

In React, what is the process for passing a callback argument from a child component to a parent component?

Currently, I am going through the React tutorial on https://reactjs.org/tutorial/tutorial.html and making good progress. However, there is one aspect that I find confusing. Here is the complete code (codepen: https://codepen.io/gaearon/pen/EmmOqJ?editors=0 ...

What is the solution for handling nested promises in Node.js?

I am currently using the node-fetch module for making API calls. I have a function that handles all the API requests and returns both the status code and the response body. The issue I'm facing is that when returning an object with the response data, ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

wiping out a column in Excel spreadsheets with the help of Node.js or its corresponding node modules

I've attempted various approaches without success. Can you provide guidance on deleting and adding columns within an Excel sheet using Node.js? ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

What is the best way to arrange a collection of string values in an array?

Just started learning Java and I successfully wrote code to sort numbers, but now I'm struggling to convert it to sort strings. Can someone please explain the simplest method to sort strings in alphabetical order? ...

WebSocket connection established on port 8888, while the web server is running on port 80 - incompatible to merge the two services

Here is some node.js server-side code that involves watching a file and sending modifications to the browser: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') a ...

Error message: Element is not able to receive focus due to an

Here is the code snippet for the input field: <span ng-if="cell.state != 'edit_mode'" class="ng-scope"> <span ng-class="{'with-right-padding' : cell.input_type === 'auto_complete'}" class="value-cell ng-binding"& ...

JavaScript - Marking selected text: What are the options?

I am looking to implement a feature in JavaScript (without jQuery) that will allow me to highlight selected text with control points or markers (left and right). These markers should function similar to those on mobile phones, allowing me to extend the sel ...

What is the best way to automatically adjust a panel's width and height based on the user's screen resolution?

My page is connected to a masterpage. Within this page, I have an update panel that contains an ASP.NET panel. The panel includes a gridview displaying data from the database. Currently, I have set a fixed width and height for the panel. However, if the u ...

Guide on linking navigation to various buttons on the Angular menu

I am looking to enhance the functionality of my left menu buttons by adding a navigation path to each one (excluding the main menu). The menu items' names are received as @Input. I have set up a dictionary mapping all the items' names to their r ...

Is there a way in Javascript to save the inner HTML of an element in a cache so that it can be re-rendered after the page is refreshed

Is there a way to cache part of a webpage on the client side using JavaScript/jQuery? Does this method have any limitations in terms of the amount of data that can be cached? How can I access this cache after refreshing the page in order to re-render it? ...

"Utilize the parent field while iterating through a for expression in JSL

Greetings, I am facing a challenging issue while trying to use jslt for JSON transformation. The input JSON data appears as follows: { "user_id": "001", "friends": [{ "friend_id": "002" ...

Modify the nested object's two layers using the designated ID

In my Mother Model, there is a fixed structure where I manipulate cards on three array levels: starter, intermediate, and advanced. { cards: { starter: [], intermediate: [], advanced: [ {Object}, {Object}, {Object} ] }, } The objects withi ...

The length of the Array is accurate

Hey there! I'm facing an interesting challenge in my second semester of object oriented programming. For my first project in my intro to java course, I need to create a Date class that calculates the days elapsed from January 1st of the year. I have t ...

Pass a variable to PHP using AJAX

I am currently facing an issue with sending an input value to PHP via AJAX. I am attempting to generate a datatable based on user input. Below is the code snippet: <input class="form-control" id="id1" type="text" name="id1"> My JavaScript code: & ...