2020-11-27 12:10:39 +00:00
|
|
|
module.exports = Self => {
|
|
|
|
/**
|
|
|
|
* Checks if current user has
|
|
|
|
* read privileges over a collection
|
|
|
|
*
|
|
|
|
* @param {object} ctx - Request context
|
|
|
|
* @param {interger} name - Collection name
|
|
|
|
* @param {object} options - Query options
|
|
|
|
* @return {boolean} True for user with read privileges
|
|
|
|
*/
|
|
|
|
Self.hasReadRole = async(ctx, name, options) => {
|
|
|
|
const collection = await Self.findOne({where: {name}}, {
|
|
|
|
include: {
|
|
|
|
relation: 'readRole'
|
|
|
|
}
|
|
|
|
}, options);
|
|
|
|
|
|
|
|
return await hasRole(ctx, collection, options);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if current user has
|
|
|
|
* write privileges over a collection
|
|
|
|
*
|
|
|
|
* @param {object} ctx - Request context
|
|
|
|
* @param {string} name - Collection name
|
|
|
|
* @param {object} options - Query options
|
|
|
|
* @return {boolean} True for user with write privileges
|
|
|
|
*/
|
|
|
|
Self.hasWriteRole = async(ctx, name, options) => {
|
2020-12-11 14:04:55 +00:00
|
|
|
const collection = await Self.findOne({
|
2020-11-27 12:10:39 +00:00
|
|
|
include: {
|
|
|
|
relation: 'writeRole'
|
2020-12-11 14:04:55 +00:00
|
|
|
},
|
|
|
|
where: {name}
|
2020-11-27 12:10:39 +00:00
|
|
|
}, options);
|
|
|
|
|
|
|
|
return await hasRole(ctx, collection, options);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if current user has
|
|
|
|
* read or write privileges
|
|
|
|
* @param {Object} ctx - Context
|
|
|
|
* @param {Object} collection - Collection [read/write]
|
|
|
|
* @param {Object} options - Query options
|
|
|
|
*/
|
|
|
|
async function hasRole(ctx, collection, options) {
|
|
|
|
const models = Self.app.models;
|
|
|
|
const myUserId = ctx.req.accessToken.userId;
|
|
|
|
|
|
|
|
const readRole = collection.readRole() && collection.readRole().name;
|
|
|
|
const writeRole = collection.writeRole() && collection.writeRole().name;
|
|
|
|
const requiredRole = readRole || writeRole;
|
|
|
|
|
2023-01-23 14:24:00 +00:00
|
|
|
const hasRequiredRole = await models.VnUser.hasRole(myUserId, requiredRole, options);
|
|
|
|
const isRoot = await models.VnUser.hasRole(myUserId, 'root', options);
|
2020-11-27 12:10:39 +00:00
|
|
|
|
|
|
|
if (isRoot || hasRequiredRole)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|