'How can I make my admin page (for removing users from DB) not display other users in the list if they have an admin role?
I am making an admin page that lists all current users in the database of my web application. I am trying to make it so that users with the role admin, do not appear in the list, essentially preventing admins from removing other admins. How can I accomplish this? This is my code:
BoardAdmin.jsx:
import React, {useState, useEffect} from 'react';
import UserService from '../../services/user.service';
import './styles/BoardAdmin.css';
const BoardAdmin = () => {
const [content, setContent] = useState('');
const [users, setUsers] = useState([]);
useEffect(() => {
UserService.getAdminBoard().then(
(response) => {
setUsers(response.data);
// console.log(response.data);
},
(error) => {
const _content =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
setContent(_content);
}
);
}, []);
return (
<div className='page'>
<header className='jumbotron'>
<div className='column-names'>
<p className='user-id-column'>User ID</p>
<p className='username-column'>Username</p>
{/* <p>User Role</p> */}
<p className='user-email-column'>Email</p>
</div>
{users.map((user) => (
<ul className='user-list'>
<li class='user'>
<div>
<div class='info'>
<span class='user-id'>{user.id}</span>
<span class='name'>{user.username}</span>
<span class='role'>{user.role}</span>
<span class='email'>{user.email}</span>
<img class='remove' src='https://i.imgur.com/CemzWSg.png' />
</div>
</div>
<div class='expand'></div>
</li>
</ul>
))}
</header>
</div>
);
};
export default BoardAdmin;
I can access the users role if I check the state with an auth file of mine with const { user: currentUser } = useSelector((state) => state.auth); and if (currentUser) { setShowAdminBoard(currentUser.roles.includes("ROLE_ADMIN"));. Can anyone help me figure out how I can accomplish this? Does it need to be done on the backend? Any help would be appreciated, and I will include more code if it is necessary.
Solution 1:[1]
You would need to filter out users with that role when rendering them in your JSX.
// Assuming that "ROLE_ADMIN" is the unwanted role
{users.filter(user => user.role !== "ROLE_ADMIN").map((user) => (
<ul className='user-list'>
<li class='user'>
...
Security note: it is recommended to handle this on the backend of your application, as anything performed on the client can be manipulated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
