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

Looping through items with ng-repeat and creating a submenu with M

When constructing a menu from a JSON file with submenus using the JQuery.mmenu plugin, I encountered an issue when trying to implement the submenu structure with ng-repeat. The raw HTML approach worked perfectly, but as soon as I introduced ng-repeat to dy ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

Unique loading animations are assigned to each individual page within the Next.js framework

Is there a way to have unique loading animations for each of my website pages during the loading process? How can I achieve this? I've attempted to put the loading component on the page component directly, but it doesn't seem to work: //Page com ...

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

CSS :hover activates only when the mouse is in motion

Looking at a simple example I put together: HTML <div id="sample"></div> CSS #sample { width:400px; height:400px; background-color:green; display:none; } #sample:hover{ background-color:red; } It's a hidden DIV tha ...

AngularJS and Ionic Framework - Click on a specific row to interact with it

I am struggling to open a new page when an item is touched in my HTML code. Despite trying multiple times, I can't seem to make it work and I'm at a loss as to why. Below is the snippet of my HTML: <!DOCTYPE html> <html> <hea ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

The consistency of values remains constant throughout all Ajax requests

I am presenting the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ...

Managing the layout with React Native Flexbox to evenly distribute items

Check out this React Native Demo I put together featuring Santa images being added and removed in a Flexbox. Bunch of Santas I noticed that when there are more than 3 Santas, the layout shifts to the left. I'm curious about how to keep the Santas ce ...

Guide on retrieving the content type field value in Drupal and transferring it to a JavaScript file

In my custom Drupal theme, I have included a field for a SoundCloud URL with the machine name (field_soundcloud_url_). I am attempting to use a JavaScript file that will function based on the value of this variable. However, it seems to not be working as e ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

I am currently working on coding a function that will search an array to determine if a specific item is present. If the item is found, a variable will be set to true;

So, I have this array of prices for various items like bread, apple, noodles, beef, milk, and coke. const prices = [ ["bread", 20], ["apple", 50], ["noodles", 100], ["beef", 40], ["milk", 32], ["coke", 25], ]; And here's the JavaScript co ...

A Guide on Accessing Promise Results in AngularJS

In my code, I am using a controller to retrieve information from SharePoint. While debugging, I noticed that the value of data.d.UserProfileProperties.results[115].Value is what I need to display in the view. However, I am struggling to extract that value ...

The output of jquery's val() function will not show the actual value

Is it proper to use html() for setting content in non-form elements like divs? This question has come up a few times, which I wasn't aware of. I've been working on setting a value after fetching comments through a $.ajax call. When I check the v ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

Prevent the href from navigating to the next page when a doubleclick event listener is triggered

In my project, I am using an anchor tag that redirects to another page. However, if the user double clicks on it, I want to prevent the default behavior and stop the redirection. <a href="{location}">My Link</a> element.addEventListen ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', &apos ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...