28 lines
2.8 KiB
JavaScript
28 lines
2.8 KiB
JavaScript
import {identity} from './auth.mjs';
|
|
import {accessFor} from './permissions.mjs';
|
|
import {clanDeedAuthority,clanDeedOperators} from './clan-deeds.mjs';
|
|
import {clanEmblemUrl} from '../control-panel/clan-emblems.mjs';
|
|
const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
|
|
export function clanWorkspaceAccess({id,ownerId,parentId,rootId,role,canManage,userId}){
|
|
const inherited=canManage&&ownerId!==userId&&(!!parentId||rootId!==id);
|
|
return {controlMode:inherited?'parent':ownerId===userId?'owner':role||'deed',hasParent:!!parentId,
|
|
capabilities:{manage:canManage,boards:!!role,mail:['owner','officer'].includes(role)||canManage&&!inherited,politics:!parentId&&canManage}};
|
|
}
|
|
export function createClanWorkspace(db,{authenticate=request=>identity(request,db),access=user=>accessFor(db,user)}={}){return async request=>{
|
|
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}),url=new URL(request.url);
|
|
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
|
|
if([...url.searchParams.keys()].some(k=>k!=='clan')||url.searchParams.getAll('clan').length>1||url.searchParams.has('clan')&&!uuid(url.searchParams.get('clan')))return reply({message:'Choose a valid clan.'},400);
|
|
const user=await authenticate(request);if(!user)return reply({message:'Sign in first.'},401);
|
|
if(!(await access(user)).nodes?.includes('web.menu.game'))return reply({message:'Clan access required.'},403);
|
|
const link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();if(!link?.minecraft_uuid)return reply({clans:[],selected:null});
|
|
const own=await db.prepare('SELECT clan_id,clan_role FROM site_clan_members WHERE user_id=? AND minecraft_uuid=?').bind(user.id,link.minecraft_uuid).first();
|
|
const operators=await clanDeedOperators(db),ids=[...new Set([...(own?[own.clan_id]:[]),...[...operators].filter(([,users])=>users.includes(user.id)).map(([id])=>id)])];
|
|
const clans=[];
|
|
for(const id of ids){const authority=await clanDeedAuthority(db,user.id,id),deed=authority.deed;if(!deed||!authority.canManage&&own?.clan_id!==id)continue;
|
|
const role=own?.clan_id===id?own.clan_role:null,c=deed.clan;
|
|
clans.push({id,name:c.name,tag:c.tag,emblem:clanEmblemUrl(id),role,canManage:authority.canManage,...clanWorkspaceAccess({id,ownerId:deed.owner?.id,parentId:authority.hasParent?(c.parent_clan_id||'parent'):null,rootId:deed.root,role,canManage:authority.canManage,userId:user.id})});
|
|
}
|
|
clans.sort((a,b)=>a.name.localeCompare(b.name));const selected=url.searchParams.get('clan')||own?.clan_id||clans[0]?.id||null;
|
|
if(selected&&!clans.some(c=>c.id===selected))return reply({message:'This clan is not available to your account.'},404);
|
|
return reply({clans,selected});
|
|
};}
|

Staff