MC/website/node/company-workspace.mjs

13 lines
1.4 KiB
JavaScript

import {identity} from './auth.mjs';
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
export function createCompanyWorkspace(db,{authenticate=request=>identity(request,db)}={}){return async request=>{
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Company CP.'},401);
const params=new URL(request.url).searchParams,id=params.get('company');
if([...params.keys()].some(k=>k!=='company')||params.getAll('company').length>1||id!==null&&!uuid.test(id))return reply({message:'Choose a valid company.'},400);
const {results=[]}=await db.prepare('SELECT c.id,c.slug,c.name,c.description,c.status,c.founded_by,c.ceo_account_id,a.username ceo_name,f.username founder_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id LEFT JOIN site_accounts f ON f.id=c.founded_by WHERE c.founded_by=? OR c.ceo_account_id=? ORDER BY c.name LIMIT 100').bind(user.id,user.id).all();
const companies=results.map(({founded_by,ceo_account_id,...company})=>({...company,role:founded_by===user.id?'Founder':'CEO'}));
if(id&&!companies.some(c=>c.id===id))return reply({message:'This company is not available to your account.'},404);
return reply({companies,selected:id||companies[0]?.id||null});
};}