Skip to content

Instantly share code, notes, and snippets.

@jcgertig
Created March 15, 2017 19:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jcgertig/1b2539902eea78a6cfd3aeb740701c5f to your computer and use it in GitHub Desktop.
Save jcgertig/1b2539902eea78a6cfd3aeb740701c5f to your computer and use it in GitHub Desktop.
React Pundit
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;
}
};
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;
}
}
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