Last active
January 19, 2021 23:50
-
-
Save runeb/524fdab1123a3278590f66e22690ab46 to your computer and use it in GitHub Desktop.
Custom control over Desk pane menu items based on user group membership
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 React, { | |
useEffect, useState | |
} from 'react' | |
import DefaultPane from '@sanity/components/lib/panes/DefaultPane' | |
import client from 'part:@sanity/base/client' | |
const CustomPane = (props) => { | |
const [groups, setGroups] = useState([]) | |
useEffect(() => { | |
// Get the current users groups. | |
// NOTE: The user will need read access to the "system.group" documents in | |
// order to figure out which groups they are a part of. If they don't have | |
// access to read those documents, we can never determine membership, so all | |
// relevant groups should be given the 'read' grant for type 'system.group' | |
client.fetch('* [_type == "system.group" && $identity in members] {_id}') | |
.then(groups => setGroups(groups.map(g => g._id))) | |
}, []) | |
// Default is to show no menu items, until we can inspect the | |
// roles (groups) the user is a part of. | |
let menuItems = [] | |
if (groups.length) { | |
// In this example, we check if the user is a member of a | |
// specific group with _id '_.groups.administrator'. | |
if (groups.includes('_.groups.administrator')) { | |
// Since the user is a part of this group, use the standard menuItems, | |
// which will include "Create new…" | |
menuItems = props.menuItems | |
} else { | |
// Filter out any actions you don't want to expose to the users who | |
// do not match the group check above. This can be the standard Create New | |
// action (item with intent.type === 'create'), but could also be initial | |
// value template actions etc. Inspect and adjust the code as needed. | |
menuItems = props.menuItems.filter(item => { | |
if (item.intent) return item.intent.type !== 'create' | |
return true | |
}) | |
} | |
} | |
return <DefaultPane {...props} menuItems={menuItems} /> | |
} | |
CustomPane.propTypes = DefaultPane.propTypes | |
CustomPane.defaultProps = DefaultPane.defaultProps | |
export default CustomPane |
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
// Add this to the 'parts' array in sanity.json | |
{ | |
"implements": "part:@sanity/components/panes/default", | |
"path": "./pane.js" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment