React : How to safely display a component according to user role

Viewed 2579

I am trying to display an admin Dashboard in react and Meteor only if the current user is an admin.

I am calling a server method that checks the user permission and rendering the admin component only if this method returns true.

This server call is asynchronous and thus the component is not rendering, usually I manage this asynchronous call with state, but I don't want to expose anything in state here (wouldn't like someone to change the state and access the admin dashboard).

Here is the code:

export default class AdminChecker extends Component {
  isItAdmin() {
    // Get the id of current user
    const userId = Meteor.userId();
    if (userId) {
      // call a server method which returns true if current user is Admin
      Meteor.call('checkAdminId', userId, (err, authorized) => {
        if (err) {
          console.log(err);
          return null;
        }
        return (authorized) ? <AdminDashboard /> : null;
      });
    }
  }
  render() {
    return (
      <div className="admin-temp-container">
        {this.isItAdmin()}
      </div>
    );
  }
}

I think I can have this logic in a parent component and send the result of isItAdmin to adminDashboard as a prop (the adminDashboard component would display information only if its props is true).

But I am insure if this is safe. Could one change the props with Chrome react developer tools or something like that?

Thanks a lot

1 Answers

I think there are two parts to this (and the comments are hinting at both):

First, you should not expect to be able to enforce security on the client. You must implement access control logic on the server (i.e., any API that performs an admin action must check that the user performing the action is an admin).

Once you've done that (and perhaps you already have), then you likely need to use props or state to store whether or not the user is an admin (just like you would store any other data in your app).

The key point is that once you enforce security on the server, then it doesn't really matter if a user manipulates the state to get to the admin dashboard: the server will not let the user view any real data or take any actions anyway.

This is completely unrelated to server-side rendering. You can most certainly build a secure admin dashboard without server-side rendering, as long as the APIs used to fetch the admin data and perform admin actions are implementing their own access control checks.

Related