Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_ADMIN1 role?

It's important to note that users can have multiple roles simultaneously. As shown in the examples below, each user has the ROLE_USER role, but they may also have ROLE_ADMIN1, ROLE_ADMIN2, or both.

{
         "name": "Jack",
         "fname": "Daniel",
         "roles": [
           "ROLE_USER"
         ]
       }


       {
         "name": "Laly",
         "fname": "Dom",
         "roles": [
           "ROLE_USER",
           "ROLE_ADMIN1"
         ]
       }


       {
         "name": "Admini",
         "fname": "Strator",
         "roles": [
           "ROLE_USER",
           "ROLE_ADMIN2"
         ]
       }<br><br;            {
         "name": "Admini",
         "fname": "Strator",
         "roles": [
           "ROLE_USER",
           "ROLE_ADMIN1",               
           "ROLE_ADMIN2" 
           ]
       }

This is what my HTML looks like:

<ion-item class="item-stable animsvdj" ng-click="toggleGroup(group)" ng-class="{active: isGroupShown(group)}">
      <i class="icon" ng-class="isGroupShown(group) ? 'ion-android-contacts' : 'ion-android-contacts'"></i>
        Category
    </ion-item>
    <ion-item class="item-accordion menu-border" ng-show="isGroupShown(group)" ui-sref="menu.disponibilites" menu-close=""><i class="ion-ios-calendar-outline menu-icon"></i>   Category 1</ion-item>

    <!-- This section should only be visible to admins -->
    <ion-item class="item-accordion menu-border" ng-show="isGroupShown(group)" ui-sref="menu.organiseVisite" menu-close=""><i class="ion-ios-time-outline menu-icon"></i>   Category 2</ion-item>
    <!-- This section should only be visible to admins -->

    <ion-item class="item-accordion menu-border" ng-show="isGroupShown(group)" ui-sref="menu.trouverUnJeune" menu-close=""><i class="ion-ios-eye-outline menu-icon"></i>   Category 3</ion-item>

In my controller:

.controller('menuCtrl', function($scope, $state, $http, $ionicHistory, AppService) {
            $scope.group = [];
            $scope.toggleGroup = function(group) {
              if ($scope.isGroupShown(group)) {
                $scope.shownGroup = null;
              } else {
                $scope.shownGroup = group;
              }
            };
            $scope.isGroupShown = function(group) {
              return $scope.shownGroup === group;
            };

      })

Thank you for your help!

Answer №1

One effective approach to managing this logic is by handling it at the backend level.

By sending the token, the backend team can verify the role from the token itself and retrieve data based on the user's permissions to ensure data security.

If you're not concerned about these precautions, you could apply client-side filtering like so:

$scope.adminData = [];
$scope.data = [{data:'some user data',roll:'user'},{data:'some admin data',roll:'admin'}]
data.filter(function(currentValue, index, arr){
if(currentValue.roll == "admin"){
$scope.adminData.push(currentValue);
}
})

Then display the adminData array in your view if the logged-in user has admin permission.

In this scenario, I recommend implementing the logic within your component for easier maintenance and a cleaner interface.

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

Retrieving the data from an Angular website using a curl command

Currently, I am facing an issue with my Angular 2 application running on Google Earth. The problem arises as Google Earth uses an outdated version of Chrome that is not compatible with Angular 2. To tackle this obstacle, I need to find a way to initiate th ...

Transform a PNG image with transparency into a JPEG file using imagemagick

Consider utilizing the imagemagick npm module for your image manipulation needs. In the task of converting a .png file with a transparent background to a .jpeg with a white background, you may encounter challenges. Here is an example: const ImageMagick ...

Persist the checkbox value in the database and update the status of the label accordingly

I need a checkbox for user preference selection that is stored in a MySQL database for constant availability. The label should change to "Enabled" when the checkbox is selected and vice versa. Upon saving (submitting) the page, an alert message should disp ...

How to prevent table row from highlighting on hover in Angular Bootstrap

In my project, I have a table that showcases various details and allows users to select certain rows. Some of these rows have child rows which can also be selected. The requirement is for the parent rows to be selectable only if they do not have any child ...

The asterisk path is not processed by the Node command

Within my Test/Automation folder, I have multiple test cases such as a.js, b.js, c.js, and more. Currently, I am utilizing WebdriverJs Selenium to run these tests. To execute all the tests within the folder, I use the following command: node Test/**/*.js ...

Loading an Angular app causes Chrome devtools to freeze

Currently, I am facing some unusual behavior in my rather large Angular (1.5) application. When I have Chrome DevTools open while loading the app, the CPU usage of that particular tab shoots up to 100%, causing the app to take a minute or more to load. Add ...

unable to retrieve data using ajax

Having some trouble with my ajax code that is supposed to print values: success: function(returndata) { $('#first').html("<div id='first' class='progress-bar progress-bar-primary' role='progressbar' aria-valu ...

Having trouble updating a MongoDB array through a RESTful API PUT request

I'm brand new to the MEAN stack and recently completed a tutorial. I've been working on enhancing a simple application that utilizes a RESTful API to update a MongoDB. Currently, I'm using a PUT statement to modify specific parts of my colle ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

The MUI classes in my React project differ between the local and live versions, creating inconsistency in styling

I've encountered a discrepancy in the Mui classes used in my React project between the local and live versions. For instance: Localhost MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeSmall MuiButton-textSizeSmal ...

Using AJAX to load a PHP file in CodeIgniter is a great way to

I'm a beginner in the world of web development and I need help with loading my PHP file containing HTML content to update the span element. My framework of choice is CodeIgniter. Every time I try, I encounter an error. Below is my JavaScript code: ...

Encountering the error message "Angular module not found" after transitioning to webpack

Transitioning from pure Javascript scripts to webpack for my project is the current challenge. Our html file, game.html, contains the following: <html> ... <script src="bundle.js"></script> ... <div ng-app="visualizerA ...

Dividing the ZMQ socket from the express app.js by integrating with mongodb

Currently, I am working on an Express application that is responsible for gathering data sent from a remote machine through ZMQ and then updating a MongoDB database with this information. The data updates are transmitted every 5 minutes in the form of enc ...

Deletion of component with setTimeout in React Class Component

I have a notification feature that disappears after a certain delay when rendered. The issue arises when attempting to cancel this automatic removal using clearTimeout, as it doesn't seem to work. See below class Notify extends React.Component { ...

li experiencing a background width problem due to extended text

Check out this code snippet with a problem In the image below, you can see that the background of the li element with more text is larger compared to the others. It's important to note that the <ul> is scrollable. I've experimented with va ...

Is there a way to incorporate the 'window' into middleware when using Express?

I am using middleware to retrieve data from a cookie with the help of vue-cookies. try { if (window.$cookies.get('region')) { res.setHeader('Set-Cookie', [ `region=${window.$cookies.get('region')};pat ...

Encountering a problem with passing parameters in AngularJS routes

I'm looking to extract a parameter from a URL within an angularjs controller: http://localhost:53315/Employee/{parameter}#/info This is the relevant section of my angularjs code: $routeProvider .when('/info', { controller ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

Utilizing ThemeProvider in a Different Component in React

In my App.js file, I have a function that toggles between light and dark mode themes: import { createTheme, ThemeProvider } from '@mui/material/styles' import Button from '@mui/material/Button' import Header from './components/Head ...