Created
September 18, 2020 12:01
-
-
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
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
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