forked from unimatrix/web
29 lines
3.8 KiB
JavaScript
29 lines
3.8 KiB
JavaScript
import {identity} from '../node/auth.mjs';
|
|
import {accessFor} from '../node/permissions.mjs';
|
|
import {ELECTIONS} from './public/political-catalog.mjs';
|
|
export function directoryQuery(url){
|
|
const q=(url.searchParams.get('q')||'').trim(),election=url.searchParams.get('election')||'',status=url.searchParams.get('status')||'',page=Number(url.searchParams.get('page')||0);
|
|
if(q.length>100||election&&!ELECTIONS.some(e=>e.id===election)||!['','upcoming','voting','closed'].includes(status)||!Number.isInteger(page)||page<0||page>10000)throw Error('Invalid search filters.');
|
|
return {q,election,status,page};
|
|
}
|
|
export function createElectionDirectory(db,{authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now}={}){return async request=>{
|
|
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
|
if(request.method!=='GET')return reply({message:'Read-only directory.'},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:'Player access required.'},403);
|
|
let filters;try{filters=directoryQuery(new URL(request.url));}catch(error){return reply({message:error.message},400);}
|
|
const where=["a.status='submitted'","u.password_hash NOT LIKE '!%'"],args=[],now=clock();
|
|
if(filters.q){where.push("(LOWER(u.username) LIKE ? ESCAPE '!' OR LOWER(COALESCE(u.display_name,'')) LIKE ? ESCAPE '!' OR LOWER(a.motivation) LIKE ? ESCAPE '!' OR LOWER(COALESCE(p.bio,'')) LIKE ? ESCAPE '!')");const term='%'+filters.q.toLowerCase().replace(/[!%_]/g,'!$&')+'%';args.push(term,term,term,term);}
|
|
if(filters.election){const e=ELECTIONS.find(e=>e.id===filters.election);where.push('a.kind=? AND a.faction=?');args.push(e.kind,e.faction);}
|
|
// Keep retired offices in the historical ledger, outside the new election directory.
|
|
where.push('('+ELECTIONS.map(e=>{args.push(e.kind,e.faction);return '(a.kind=? AND a.faction=?)';}).join(' OR ')+')');
|
|
const phase="CASE WHEN a.election_start>? THEN 'upcoming' WHEN r.status='open' AND r.closes_at>? THEN 'voting' ELSE 'closed' END";
|
|
const from=` FROM political_applications a JOIN site_accounts u ON u.id=a.user_id LEFT JOIN site_profiles p ON p.user_id=u.id LEFT JOIN political_election_rounds r ON r.kind=a.kind AND r.faction=a.faction AND r.election_start=a.election_start AND NOT EXISTS(SELECT 1 FROM political_election_rounds newer WHERE newer.kind=r.kind AND newer.faction=r.faction AND newer.election_start=r.election_start AND newer.round_number>r.round_number) WHERE ${where.join(' AND ')}`;
|
|
if(filters.status){where.push(`${phase}=?`);args.push(now,now,filters.status);}
|
|
const filteredFrom=from+(filters.status?` AND ${phase}=?`:'');
|
|
try{
|
|
const count=await db.prepare('SELECT COUNT(*) AS total'+filteredFrom).bind(...args).first();
|
|
const rows=await db.prepare(`SELECT a.id,a.public_id,a.kind,a.faction,a.election_start,a.motivation,u.username,u.display_name,p.bio,${phase} AS phase,r.id AS round_id,r.status AS round_status,r.opens_at,r.closes_at,EXISTS(SELECT 1 FROM political_round_candidates c WHERE c.round_id=r.id AND c.application_id=a.id) AS in_round`+filteredFrom+' ORDER BY a.election_start DESC,a.kind,a.faction,u.username,a.id LIMIT 24 OFFSET ?').bind(now,now,...args,filters.page*24).all();
|
|
return reply({applications:rows.results.map(r=>({id:r.id,publicId:r.public_id,kind:r.kind,faction:r.faction,start:new Date(Number(r.election_start)).toISOString(),username:r.username,name:r.display_name||r.username,bio:r.bio||'',motivation:r.motivation,phase:r.phase,round:r.round_id?{id:r.round_id,status:r.round_status,opensAt:Number(r.opens_at),closesAt:Number(r.closes_at),eligible:!!Number(r.in_round)}:null})),total:Number(count.total),page:filters.page,pageSize:24});
|
|
}catch{return reply({message:'The voting directory is temporarily unavailable.'},503);}
|
|
};}
|

Staff