Add function to return allowed operations in a given context

This commit is contained in:
D. Berge
2025-07-12 23:58:56 +02:00
parent 7c6d3fe5ee
commit 1295ec2ee3
4 changed files with 64 additions and 7 deletions

View File

@@ -0,0 +1 @@
../../../../../server/lib/organisations/operations.js

View File

@@ -1,6 +1,6 @@
const { setSurvey, pool } = require('../connection');
const { vessel } = require('../vesel');
const { access } = require('../../organisations');
const { access, operations } = require('../../organisations');
const { ALERT, ERROR, WARNING, NOTICE, INFO, DEBUG } = require('DOUGAL_ROOT/debug')(__filename);
// Cache the per-project organisations access here
@@ -62,15 +62,23 @@ async function orgAccess (userOrgs, pid, operation) {
return access(userOrgs, itemOrgs, operation);
}
/** Check to which operations the user has access to in the
* project given by 'pid`.
*
* If `pid` is `null`, check against vessel access.
*/
async function allowedOperations (userOrgs, pid) {
const itemOrgs = pid === null
? await vesselOrganisations()
: await projectOrganisations(pid);
return operations(userOrgs, itemOrgs);
}
/*
* Filter an array of objects by organisation access to a given operation
*/
function orgFilter (userOrgs, list, operation, fn = (item) => item.organisations ) {
console.log("orgFilter");
console.log("userOrgs", userOrgs);
console.log("list", list);
console.log("operation", operation);
console.log("fn", fn);
return list.filter ( (item) => access(userOrgs, fn(item), operation) );
}
@@ -79,5 +87,6 @@ module.exports = {
projectOrganisations,
vesselOrganisations,
orgAccess,
allowedOperations,
orgFilter
};

View File

@@ -1,3 +1,4 @@
module.exports = {
access: require('./access.js')
access: require('./access.js'),
operations: require('./operations.js'),
};

View File

@@ -0,0 +1,46 @@
/** List the operations to which the user has access
*
* @a userOrgs is the user's organisations
* @a itemOrgs is the item's organisations
*
*/
function operations (userOrgs = {}, itemOrgs = {}) {
// console.log("userOrgs", userOrgs);
// console.log("itemOrgs", itemOrgs);
const ops = [];
for (const userOrg in userOrgs) {
for (const operation in userOrgs[userOrg]) {
if (userOrg in itemOrgs) {
// Found an organisation in common between user and project
// (there might be many)
if (itemOrgs[userOrg][operation] == true && userOrgs[userOrg][operation] == true) {
ops.push[operation];
}
}
}
}
if ("*" in userOrgs) {
// Aha! A wildcard user
// Return true if at least one organisation grants access
// to this operation
// console.log("Checking via wildcard");
for (const operation in userOrgs["*"]) {
if (Object.values(itemOrgs).some( org => org[operation] )) {
ops.push(operation);
}
}
}
return ops;
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = operations; // CJS export
}
// ESM export
if (typeof exports !== 'undefined' && !exports.default) {
exports.default = operations; // ESM export
}