
/** Check whether the user has access to the required operation
 * @a userOrgs is the user's organisations
 * @a projectOrgs is the project's organisations
 * @a operation is the desired operation (read, write, etc.)
 *
 * @return `true` is user has access to `operation` through
 * a common organisation, `false` otherwise.
 */
function access (userOrgs = {}, projectOrgs = {}, operation = undefined) {
	// console.log("userOrgs", userOrgs);
	// console.log("projectOrgs", projectOrgs);
	// console.log("operation", operation);

	for (const userOrg in userOrgs) {
		if (userOrg in projectOrgs) {
			// Found an organisation in common between user and project
			// (there might be many)
			if (projectOrgs[userOrg][operation] == true && userOrgs[userOrg][operation] == true) {
				// For this one, the project grants the required operation
				// access to the organisation, and the organisation grants the
				// required operation access to the user, so authorisation is
				// given.
				// console.log("Access granted via organisation", userOrg, projectOrgs[userOrg][operation], userOrgs[userOrg][operation]);
				return true;
			}
		}
	}
	if ("*" in userOrgs) {
		// Aha! A wildcard user
		// Return true if at least one organisation grants access
		// to this operation
		// console.log("Checking via wildcard");
		return (Object.values(projectOrgs).some( org => org[operation] ))
	}
	return false;

}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = access; // CJS export
}

// ESM export
if (typeof exports !== 'undefined' && !exports.default) {
    exports.default = access; // ESM export
}
