Skip to content

Instantly share code, notes, and snippets.

@Aschen
Created September 18, 2020 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aschen/904d7f168dbd2234e4f1aa12f604b569 to your computer and use it in GitHub Desktop.
Save Aschen/904d7f168dbd2234e4f1aa12f604b569 to your computer and use it in GitHub Desktop.
Restrict index and collection list to user who are allowed to act on it
class KuzzlePlugin {
init (config, context) {
this.pipes = {
'index:afterList': 'restrictIndexes',
'collection:afterList': 'restrictCollections'
};
}
/**
* Pipe to restrict index list
*
* @param {Request} request
*/
async restrictIndexes (request) {
if (this.userIsAdmin(request)) {
return request;
}
const { indexes } =
await this._allowedIndexesAndCollections(request.context.user._id);
if (! indexes.includes('*')) {
request.result.indexes = request.result.indexes.filter(index => {
return indexes.includes(index);
});
}
return request;
}
/**
* Pipe to restrict collection list
*
* @param {Request} request
*/
async restrictCollections (request) {
if (this.userIsAdmin(request)) {
return request;
}
const { collections } =
await this._allowedIndexesAndCollections(request.context.user._id);
if (! collections.includes('*')) {
request.result.collections = request.result.collections.filter(collection => {
return collections.includes(collection.name);
});
}
return request;
}
/**
* Returns the list of indexes and collections allowed for this user
*
* @param {String} userId
*
* @returns {Object} allowed - { indexes, collections }
*/
async _allowedIndexesAndCollections (userId) {
const rights = await this.sdk.security.getUserRights(userId);
return rights.reduce((allowed, { index, collection, value }) => {
if (value === 'allowed') {
if (index) {
allowed.indexes.push(index);
}
if (collection) {
allowed.collections.push(collection);
}
}
return allowed;
}, { indexes: [], collections: []});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment