Created
March 15, 2017 19:58
-
-
Save jcgertig/1b2539902eea78a6cfd3aeb740701c5f to your computer and use it in GitHub Desktop.
React Pundit
This file contains hidden or 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
export default function checkCommentPolicy(action, comment, user) { | |
switch (action) { | |
case 'delete': | |
case 'edit': | |
return comment.user.id === user.id; | |
case 'create': | |
return user.role === 'user'; | |
default: | |
return false; | |
} | |
}; |
This file contains hidden or 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 checkCommentPolicy from './CommentPolicy'; | |
import { toUpper } from 'lodash'; | |
export const meetsPolicy = (type, action, obj, user) => { | |
if (user.role === 'admin') { return true; } | |
switch (toUpper(type)) { | |
case 'COMMENT': | |
return checkCommentPolicy(action, obj, user); | |
default: | |
return false; | |
} | |
} |
This file contains hidden or 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
require('./styles.css'); | |
import React, {Component, PropTypes} from 'react'; | |
import { connect } from 'react-redux'; | |
import { meetsPolicy } from 'policies'; | |
class VisibleToUser extends Component { | |
render() { | |
let { children, hasUser, type, value, user, action } = this.props; | |
if (hasUser && meetsPolicy(type, action, value, user)) { | |
return children; | |
} | |
return (<span style={{ display: 'none' }}></span>); | |
} | |
static displayName = 'VisibleToUser'; | |
static propTypes = { | |
children: PropTypes.any.isRequired, | |
type: PropTypes.string.isRequired, | |
value: PropTypes.any.isRequired, | |
action: PropTypes.string.isRequired, | |
}; | |
} | |
export default connect((state) => ({ | |
user: state.session.user, | |
hasUser: typeof state.session.user !== 'undefined' | |
}))(VisibleToUser); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment