18 lines
2.1 KiB
JavaScript
18 lines
2.1 KiB
JavaScript
import {identity} from '../node/auth.mjs';import {accessFor} from '../node/permissions.mjs';
|
|
import {readClanDeed,publicDeed,appointClanDynasty,DeedError} from '../node/clan-deeds.mjs';
|
|
export function createClanDeedRoute(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u)}={}){return async request=>{
|
|
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store'}}),url=new URL(request.url),id=url.pathname.split('/').at(-1);
|
|
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id)||url.search)return reply({message:'Choose a valid clan.'},400);
|
|
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
|
|
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:'Game access required.'},403);
|
|
try{
|
|
if(request.method==='GET'){
|
|
const deed=await readClanDeed(db,id,{includePolitics:true}),owner=deed.owner?.id===user.id,heir=deed.heir?.id===user.id;
|
|
if(!owner&&!heir)return reply({message:'Deed management is restricted to its Ruler and Heir.'},403);
|
|
return reply({deed:publicDeed(deed),canAppoint:owner&&deed.root===id&&!deed.clan.institution_key,canAppointArms:owner&&deed.root===id,canAppointHeir:deed.keyed,consortCandidates:owner?deed.consortCandidates.filter(m=>m.id!==user.id).map(m=>({username:m.username,clanId:m.clan_id})):[],candidates:owner?deed.candidates.filter(m=>m.id!==user.id).map(m=>({username:m.username,clanId:m.clan_id})):[]});
|
|
}
|
|
if(request.headers.get('origin')!==origin||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'Request origin or format rejected.'},403);
|
|
const raw=await request.text();if(raw.length>2048)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Invalid appointment.'},400);}
|
|
return reply(await appointClanDynasty(db,user,id,input));
|
|
}catch(error){if(error instanceof DeedError)return reply({message:error.message},error.status);throw error;}
|
|
};}
|

Staff