Created
December 25, 2019 10:07
-
-
Save MatteoGioioso/a6682bd7955625ddb23ce7998c198751 to your computer and use it in GitHub Desktop.
Access control component for Reactjs
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 { connect } from "react-redux"; | |
/** | |
* Insert here all the roles | |
*/ | |
const roles = loggedUserId => ({ | |
rootAccount: { | |
static: ["profile:create", "profile:read", "profile:update"], | |
dynamic: { | |
"profile:delete": ownerId => !Boolean(ownerId) | |
} | |
}, | |
subAccount: { | |
dynamic: { | |
"profile:read": userId => userId === loggedUserId | |
} | |
} | |
}); | |
function getRole(rootAccountUserId) { | |
if (rootAccountUserId) { | |
return "subAccount"; | |
} else { | |
return "rootAccount"; | |
} | |
} | |
function AccessControl({ | |
loggedUserId, | |
rootAccountUserId, | |
allowed, | |
notAllowed, | |
action, | |
dynamicRoleData | |
}) { | |
function can() { | |
const permissions = roles(loggedUserId)[getRole(rootAccountUserId)]; | |
if (!permissions) { | |
// role is not present in the rules | |
return false; | |
} | |
const staticPermissions = permissions.static; | |
if (staticPermissions && staticPermissions.includes(action)) { | |
// static rule not provided for action | |
return true; | |
} | |
const dynamicPermissions = permissions.dynamic; | |
if (dynamicPermissions) { | |
const permissionCondition = dynamicPermissions[action]; | |
if (!permissionCondition) { | |
// dynamic rule not provided for action | |
return false; | |
} | |
return permissionCondition(dynamicRoleData); | |
} | |
return false; | |
} | |
return can() ? allowed(loggedUserId) : notAllowed(loggedUserId); | |
} | |
function mapStateToProps(state) { | |
return { | |
loggedUserId: state.authentication.user.attributes["custom:profileId"], | |
rootAccountUserId: state.authentication.user.attributes["custom:parentId"] | |
}; | |
} | |
export default connect(mapStateToProps)(AccessControl); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment