CanCan (or CanCanCan) for Redux
redux-cancan
is an authorization library for Redux which restricts what routes a given user is allowed to access.
All permissions are defined in a single location (the ability
file).
This is tested with React Router v4.
Installation
Using yarn:
$ yarn add redux-cancan
Using npm:
$ npm install redux-cancan
Example
Define the ability
file.
const auth: user = store; if user // protected routes // public routes return '/login' '/signup';;
Initialize in a file where Redux store is created.
...;;...const store = ; ;...
You can use canManage()
function to check whether or not current user can access certain routes.
...;;...const AppBar = { let navMenuItems = ; if navMenuItems; if navMenuItems; return <div> <span>Timezone App</span> navMenuItems <button>Log out</button> </div> ;};...
BONUS: You can also authorize React Router history object like this.
;;...Component { const history authorizeUser = thisprops; history; } ... const mapStateToProps = {}; const mapDispatchToProps = { if ! ownPropshistory; }; mapStateToProps mapDispatchToPropsApp;
API
initCanCan(reduxStore, ability[, f0fRoute])
reduxStore: Object
(required) - Redux store object.ability: Object
(required) - theability
file module, typically used withrequire()
.f0fRoute: String
(deafult: '/404') - the route that should be ignored while checking authorization.
canManage(route)
route: String
(required) - route string to check