Vulcan/packages/vulcan-core/lib/modules/containers/withAccess.js

37 lines
1.1 KiB
JavaScript
Raw Normal View History

2017-12-30 10:52:11 +09:00
import React, { PureComponent } from 'react';
import { withCurrentUser } from 'meteor/vulcan:core';
import { withRouter } from 'react-router';
import Users from 'meteor/vulcan:users';
export default function withAccess (options) {
2018-01-25 18:12:32 +09:00
2017-12-30 10:52:11 +09:00
const { groups, redirect } = options;
2018-01-02 13:05:34 +09:00
// we return a function that takes a component and itself returns a component
2017-12-30 10:52:11 +09:00
return WrappedComponent => {
class AccessComponent extends PureComponent {
// if there are any groups defined check if user belongs, else just check if user exists
2018-01-25 18:12:32 +09:00
canAccess = currentUser => {
2018-09-11 18:08:29 +02:00
return groups ? Users.isMemberOf(currentUser, groups) : currentUser;
2017-12-30 10:52:11 +09:00
}
// redirect on constructor if user cannot access
constructor(props) {
super(props);
if(!this.canAccess(props.currentUser) && typeof redirect === 'string') {
2017-12-30 10:52:11 +09:00
props.router.push(redirect);
}
}
2018-01-25 18:12:32 +09:00
2017-12-30 10:52:11 +09:00
render() {
2018-01-25 18:12:32 +09:00
return this.canAccess(this.props.currentUser) ? <WrappedComponent {...this.props}/> : null;
2017-12-30 10:52:11 +09:00
}
}
AccessComponent.displayName = `withAccess(${WrappedComponent.displayName})`;
return withRouter(withCurrentUser(AccessComponent));
}
}