Managing user permissions in your React app

Sergii Stotskyi
Feb 5, 2018 · 5 min read
Image for post
Image for post
if (user.role === ADMIN || user.auth && post.author === user.id) {
<button onClick={this.deletePost.bind(this)}>Delete</button>
}
if (ability.can('delete', post)) {
<button onClick={this.deletePost.bind(this}>Delete</button>
}

Demo App

Image for post
Image for post
  • a user can update or delete only todos which are assigned to him (“me” option in dropdown).

Defining user permissions

First of all, lets define our user permissions in a file src/config/ability.js.

Checking Permissions in React

At first, you may think that integration will be quite easy: just import created ability, addifs around some components in render function and we are done. That may work but only until you don’t change ability rules.

  • on which accepts subject (subject can be either a string or an object).
  • ability.update([{ subject: 'all', actions: 'manage' }]) to get full access to manage everything;
  • ability.rules to get a list of current abilities;
  • for more information about possible options and how to configure ability please read in official documentation and/or ask questions in gitter chat.

Wrap-up

With that, we have a really nice way of managing user permissions in a React app.

{ (user.role === ADMIN || user.auth && todo.assignee === user.id) &&
<button onClick={this.deleteTodo.bind(this}>Delete</button> }
Image for post
Image for post

Interested in integration with another framework?

CASL has complementary packages for major frontend frameworks, check the articles below:

DailyJS

JavaScript news and opinion.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store