web/website/node/system-board-access.mjs

27 lines
2.2 KiB
JavaScript

import {clanDeedOperators} from './clan-deeds.mjs';
// Native forum projections are derived from current organisation records on
// every sign-in/identity refresh. Never accept memberships from browser input.
export function projectSystemBoardAccess({clans=[],companies=[],userId,inspectAll=false,moderateAll=false}={}){
const grants=new Map();
if(typeof userId!=='string'||!userId)return {version:1,inspectAll:false,moderateAll:false,organisations:[]};
for(const clan of clans){
if(Number(clan.active)!==1||clan.user_id!==userId||!['owner','officer','member'].includes(clan.clan_role))continue;
grants.set('clan:'+clan.id,{kind:'clan',id:clan.id,read:true,post:true,manage:clan.owner_id===userId&&clan.clan_role==='owner'});
}
for(const company of companies){
if(company.status!=='active'||company.founded_by!==userId&&company.ceo_account_id!==userId)continue;
// Founder access follows the existing Company CP. Current management,
// including scoped moderation, belongs to the appointed CEO.
grants.set('company:'+company.id,{kind:'company',id:company.id,read:true,post:true,manage:company.ceo_account_id===userId});
}
return {version:1,inspectAll:inspectAll===true,moderateAll:moderateAll===true,organisations:[...grants.values()].sort((a,b)=>(a.kind+':'+a.id).localeCompare(b.kind+':'+b.id))};
}
export async function loadSystemBoardAccess(db,user,{inspectAll=false,moderateAll=false}={}){
if(!user?.id)return projectSystemBoardAccess();
const [{results:clans=[]},{results:companies=[]}]=await Promise.all([
db.prepare('SELECT c.id,c.active,c.owner_id,m.user_id,m.clan_role FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id WHERE m.user_id=? AND c.active=1').bind(user.id).all(),
db.prepare('SELECT id,status,founded_by,ceo_account_id FROM corrino_companies WHERE founded_by=? OR ceo_account_id=?').bind(user.id,user.id).all()
]);
const projected=projectSystemBoardAccess({clans,companies,userId:user.id,inspectAll,moderateAll}),operators=await clanDeedOperators(db);for(const [id,users]of operators)if(users.includes(user.id)){const existing=projected.organisations.find(o=>o.kind==='clan'&&o.id===id);if(existing)existing.manage=true;else projected.organisations.push({kind:'clan',id,read:true,post:true,manage:true});}return projected;
}