19 lines
2.2 KiB
JavaScript
19 lines
2.2 KiB
JavaScript
import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
|
|
import {createPoliticalSuccession} from './political-succession.mjs';import {PUBLIC_OFFICES} from './public-government.mjs';
|
|
export function createPoliticalActions(central,{enabled=false,origin='https://cp.dunerealms.com',clock=Date.now,authenticate=r=>identity(r,central),access=u=>accessFor(central,u)}={}){
|
|
const service=createPoliticalSuccession(central,{clock}),reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store'}});
|
|
return async request=>{try{
|
|
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:'Player access required.'},403);
|
|
const url=new URL(request.url);if(url.search)return reply({message:'Identity overrides are not accepted.'},400);
|
|
if(request.method==='GET'&&url.pathname==='/api/politics/my-offices'){
|
|
const terms=(await central.prepare("SELECT id,kind,faction,office,starts_at,expires_at FROM political_office_terms WHERE user_id=? AND outcome='winner' AND starts_at<=? AND expires_at>? ORDER BY starts_at DESC").bind(user.id,clock(),clock()).all()).results;
|
|
return reply({terms:terms.map(term=>({...term,officeKey:PUBLIC_OFFICES.find(o=>o.kind===term.kind&&o.faction===term.faction)?.key||null})),resignationAvailable:enabled});
|
|
}
|
|
if(request.method!=='POST'||url.pathname!=='/api/politics/resign')return reply({message:'Not found.'},404);
|
|
if(!enabled)return reply({message:'Office succession is unavailable. Your office was not changed.'},503);
|
|
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
|
|
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
|
|
const raw=await request.text();if(raw.length>2048)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid resignation.'},400);}
|
|
return reply(await service.resign(user,body));
|
|
}catch(error){return reply({message:error.status?error.message:'Office action not confirmed. Refresh to check the current record.'},error.status||503);}};
|
|
}
|

Staff