Skip to content

Instantly share code, notes, and snippets.

@jonathansamines
Created September 2, 2017 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathansamines/af4481893f051c05f67d3adefacb1f87 to your computer and use it in GitHub Desktop.
Save jonathansamines/af4481893f051c05f67d3adefacb1f87 to your computer and use it in GitHub Desktop.
React Abilities
import { withAbility, provideSession } from ‘react-can’;
import SimpleMenu from ‘simple-menu’;
const entryAbilities = {
canWrite(session, props) {
return session.user.role === ‘ADMIN’;
},
canRead(session, props) {
return false;
}
};
const AppWithAbilities = provideSession({
getSession: (context) => return context.user;
abilities: {
entry: entryAbilities
}
});
// With this approach, the execution context is retrieved by using the props
// information received from with generated HOC
// Those props are also provided to the renderUnAuthorized option
// so that you can provide with some custom information on rejection
const UserWithWritePermissions = withAbility(SimpleMenu, {
can: ‘write entry’,
renderUnAuthorized(props, context) {
return (
<UnAuthorized
message=“Sorry, you are not authorized to view this information :)” />
);
}
});
// With this approach the execution context is provided with any argument which is possible to provide to the the injected can function
const Component = withAbility((props) => {
const { can } = props;
return (
<section>
<UserMenu
isEnabled={can(‘write entry’)} />
{
can(‘write entry’, props) ?
<UserMenu />
<UnAuthorized
message=“Sorry, you are not authorized to view this information :)” />
}
<UserWithWritePermissions
anything=“will be passed to the ability evaluator” />
</section>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment