Created
September 2, 2017 02:07
-
-
Save jonathansamines/af4481893f051c05f67d3adefacb1f87 to your computer and use it in GitHub Desktop.
React Abilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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