25 lines
2.8 KiB
JavaScript
25 lines
2.8 KiB
JavaScript
import {identity} from '../node/auth.mjs';
|
|
import {accessFor} from '../node/permissions.mjs';
|
|
import {createClaimSimulation,ClaimCommandError} from '../node/claim-command-service.mjs';
|
|
const json=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
|
export function createClaimHomeBlockRoute(db,settings={},deps={}){
|
|
const simulation=deps.service||createClaimSimulation(),authenticate=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin;
|
|
return async request=>{
|
|
const url=new URL(request.url),command=url.pathname.match(/^\/api\/v1\/claims\/home-blocks\/([a-f0-9-]{36})\/commands$/i);
|
|
if(url.search||(!command&&url.pathname!=='/api/v1/claims/home-blocks'))return json({message:'Not found.'},404);
|
|
if(request.method!==(command?'POST':'GET'))return json({message:'Method not allowed.'},405);
|
|
const user=await authenticate(request);if(!user)return json({message:'Sign in to open your Home Block.'},401);
|
|
if(!(await access(user)).nodes.includes('web.menu.game'))return json({message:'Game access is required.'},403);
|
|
if(settings.CLAIM_WEB_SIMULATION_ENABLED==='false')return json({enabled:false,message:'The Home Block simulation is disabled.'});
|
|
const clan=await db.prepare("SELECT c.id,c.name,i.institution_key FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 AND c.owner_id=?").bind(user.id).first();
|
|
if(!clan||clan.institution_key)return json({enabled:false,message:'A linked owner of an ordinary clan can use this web simulation.'},command?403:200);
|
|
let charter='basic';if(settings.CLAN_KEYS_ENABLED==='true'){const row=await db.prepare('SELECT charter_kind FROM site_clan_charters WHERE clan_id=?').bind(clan.id).first();if(row?.charter_kind==='original')charter='original';}
|
|
const context={userId:user.id,organisationId:clan.id,name:clan.name,kind:'clan',charter};
|
|
try{
|
|
if(!command){const homeBlock=await simulation.read(context);return json({enabled:true,simulation:homeBlock.simulation,homeBlock});}
|
|
if(request.headers.get('origin')!==origin||!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type')||''))return json({message:'Request origin or format rejected.'},403);
|
|
let body;try{body=await request.json();}catch{return json({message:'Invalid command.'},400);}
|
|
return json(await simulation.upgrade(context,command[1],body));
|
|
}catch(error){return json({message:error instanceof ClaimCommandError?error.message:'The Home Block could not be confirmed.'},error instanceof ClaimCommandError?error.status:503);}
|
|
};
|
|
}
|

Staff