forked from unimatrix/web
89 lines
8.8 KiB
JavaScript
89 lines
8.8 KiB
JavaScript
import {identity} from './auth.mjs';
|
|
import {can} from './permissions.mjs';
|
|
import {ORGANISATION,ASSIGNMENT_ROLES,STAFF_SCOPE_TYPES,assignmentLabel} from './organisation-model.mjs';
|
|
import {citizenMemberships} from './citizen-memberships.mjs';
|
|
import {personnelLabel} from './personnel-numbers.mjs';
|
|
|
|
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
|
|
const LEGACY_STAFF=['staff','corestaff','owners','official_account','web_net_admin','web_net_owner','web_network','network_admin','web_dev'];
|
|
const STATUS_SQL="CASE WHEN a.password_hash='!deleted' THEN 'deleted' WHEN a.password_hash='!banned' THEN 'banned' ELSE 'active' END";
|
|
const fields=`a.id,a.username,a.display_name,a.created_at,${STATUS_SQL} AS account_status,
|
|
(SELECT pn.personnel_number FROM directory_personnel pn WHERE pn.user_id=a.id) AS personnel_number,
|
|
(SELECT l.minecraft_name FROM site_game_links l WHERE l.user_id=a.id LIMIT 1) AS minecraft_name,
|
|
(SELECT l.minecraft_uuid FROM site_game_links l WHERE l.user_id=a.id LIMIT 1) AS minecraft_uuid`;
|
|
const placeholders=LEGACY_STAFF.map(()=>'?').join(',');
|
|
const activeStaff=`EXISTS (SELECT 1 FROM org_assignments o WHERE o.user_id=a.id AND o.scope_type IN ('organisation','department','branch') AND o.status='active' AND o.starts_at<=? AND (o.ends_at IS NULL OR o.ends_at>?))`;
|
|
const importedStaff='EXISTS (SELECT 1 FROM staff_source_members s WHERE s.user_id=a.id)';
|
|
const legacyStaff=`(a.role IN (${placeholders}) OR EXISTS (SELECT 1 FROM cp_account_ranks cr WHERE cr.user_id=a.id AND cr.rank_key IN (${placeholders})))`;
|
|
|
|
export function directoryFilters(url,now=Date.now()){
|
|
const context=url.searchParams.get('context')||'users';
|
|
if(!['users','staff'].includes(context))throw new Error('Invalid directory context.');
|
|
const query=(url.searchParams.get('q')||'').trim();
|
|
if(query.length>80)throw new Error('Search must be at most 80 characters.');
|
|
const pageText=url.searchParams.get('page')||'1';
|
|
if(!/^[1-9]\d{0,3}$/.test(pageText))throw new Error('Invalid page.');
|
|
const status=url.searchParams.get('status')||'';
|
|
if(status&&!['active','banned','deleted'].includes(status))throw new Error('Invalid status.');
|
|
const department=url.searchParams.get('department')||'',branch=url.searchParams.get('branch')||'';
|
|
if(context==='users'&&(department||branch))throw new Error('Staff filters require Staff context.');
|
|
const dept=ORGANISATION.find(d=>d.key===department);
|
|
if(department&&!dept)throw new Error('Invalid department.');
|
|
if(branch&&!(dept?dept.branches:ORGANISATION.flatMap(d=>d.branches)).some(b=>b.key===branch))throw new Error('Invalid branch.');
|
|
const where=[],values=[];
|
|
if(context==='staff'){where.push(`(${activeStaff} OR ${importedStaff} OR ${legacyStaff})`);values.push(now,now,...LEGACY_STAFF,...LEGACY_STAFF);where.push('NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)');}
|
|
if(query){where.push('(a.username LIKE ? OR a.id=? OR EXISTS (SELECT 1 FROM site_game_links gl WHERE gl.user_id=a.id AND (gl.minecraft_uuid=? OR gl.minecraft_name LIKE ?)))');const term='%'+query.replace(/[=%_]/g,c=>'='+c)+'%';values.push(term,query,query,term);where[where.length-1]=where.at(-1).replaceAll('LIKE ?',"LIKE ? ESCAPE '='");}
|
|
if(status){where.push(STATUS_SQL+'=?');values.push(status);}
|
|
if(department||branch){
|
|
const keys=branch?[branch]:[department,...dept.branches.map(b=>b.key)];
|
|
where.push(`EXISTS (SELECT 1 FROM org_assignments f WHERE f.user_id=a.id AND f.scope_type IN ('department','branch') AND f.scope_key IN (${keys.map(()=>'?')}) AND f.status='active' AND f.starts_at<=? AND (f.ends_at IS NULL OR f.ends_at>?))`);values.push(...keys,now,now);
|
|
}
|
|
return {context,page:Number(pageText),where:where.length?' WHERE '+where.join(' AND '):'',values};
|
|
}
|
|
function project(row){return {id:row.id,username:row.username,displayName:row.display_name||row.username,personnelNumber:personnelLabel(row.personnel_number),
|
|
status:row.account_status,createdAt:Number(row.created_at),minecraftName:row.minecraft_name||null,minecraftUuid:row.minecraft_uuid||null};}
|
|
|
|
export function createCitizenDirectory(db,{authenticate=identity,authorize=can,clock=Date.now}={}){
|
|
async function assignments(ids,context){
|
|
if(!ids.length)return [];
|
|
const scopeClause=context==='users'?"NOT IN ('organisation','department','branch')":"IN ('organisation','department','branch')";
|
|
const now=clock();
|
|
const {results}=await db.prepare(`SELECT id,user_id,scope_type,scope_key,role_key,source_kind,starts_at,ends_at,version FROM org_assignments WHERE user_id IN (${ids.map(()=>'?')}) AND scope_type ${scopeClause} AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) ORDER BY scope_type,scope_key,role_key`).bind(...ids,now,now).all();
|
|
return results;
|
|
}
|
|
return async request=>{
|
|
if(request.method!=='GET')return reply({message:'This directory endpoint is read-only.'},405);
|
|
const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401);
|
|
if(!await authorize(db,actor,'web.accounts.view'))return reply({message:'Account directory permission required.'},403);
|
|
const assignmentMode=db.organisationAccessEnabled?'active':'preparing';
|
|
const url=new URL(request.url);let filter;try{filter=directoryFilters(url,clock());}catch(e){return reply({message:e.message},400);}
|
|
if(url.pathname==='/api/admin/citizens/dashboard'){
|
|
const counts=await db.prepare("SELECT COUNT(*) total,SUM(password_hash NOT LIKE '!%') active,SUM(password_hash='!banned') banned FROM site_accounts").first();
|
|
const staff=await db.prepare("SELECT COUNT(DISTINCT o.user_id) total FROM org_assignments o JOIN site_accounts a ON a.id=o.user_id LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE o.status='active' AND o.starts_at<=? AND (o.ends_at IS NULL OR o.ends_at>?) AND o.scope_type IN ('organisation','department','branch') AND a.password_hash NOT LIKE '!%' AND a.role<>'official_account' AND COALESCE(p.game_link_exempt,0)=0").bind(clock(),clock()).first();
|
|
const {results:recent}=await db.prepare('SELECT e.action,e.scope_key,e.created_at,a.username actor,p.personnel_number FROM org_assignment_events e LEFT JOIN site_accounts a ON a.id=e.actor_id LEFT JOIN directory_personnel p ON p.user_id=e.actor_id ORDER BY e.created_at DESC,e.id DESC LIMIT 8').all();
|
|
return reply({counts:{users:Number(counts?.total||0),active:Number(counts?.active||0),banned:Number(counts?.banned||0),staff:Number(staff?.total||0),departments:ORGANISATION.length,teams:ORGANISATION.reduce((n,d)=>n+d.branches.length,0)},recent:recent.map(e=>({...e,personnelNumber:personnelLabel(e.personnel_number),personnel_number:undefined})),departments:ORGANISATION});
|
|
}
|
|
if(url.pathname==='/api/admin/citizens/catalogue')return reply({departments:filter.context==='staff'?ORGANISATION:[],roles:Object.fromEntries(Object.entries(ASSIGNMENT_ROLES).filter(([key])=>STAFF_SCOPE_TYPES.includes(key)===(filter.context==='staff'))),assignmentMode,permissionsChanged:false});
|
|
const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i);
|
|
if(match){
|
|
// Staff managers may open a human candidate before their first appointment.
|
|
// The directory list remains staff-only; service accounts are never candidates.
|
|
const candidateGuard=filter.context==='staff'?' AND NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)':'';
|
|
const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${candidateGuard}`).bind(match[1]).first();
|
|
if(!row)return reply({message:'Account not found.'},404);
|
|
const current=await assignments([row.id],filter.context);
|
|
const account={...project(row),assignments:current.map(assignmentLabel)};
|
|
if(filter.context==='users')account.memberships=await citizenMemberships(db,row.id);
|
|
// Staff provenance and legacy staff ranks never leave the Staff view.
|
|
if(filter.context==='staff'){
|
|
const {results}=await db.prepare('SELECT source_name,source_ref,imported_at FROM staff_source_members WHERE user_id=? ORDER BY source_key').bind(row.id).all();
|
|
account.staffSources=results.map(s=>({name:s.source_name,reference:s.source_ref,importedAt:Number(s.imported_at)}));
|
|
}
|
|
return reply({account,context:filter.context,assignmentMode,permissionsChanged:false});
|
|
}
|
|
if(url.pathname!=='/api/admin/citizens')return reply({message:'Not found.'},404);
|
|
const {results}=await db.prepare(`SELECT ${fields} FROM site_accounts a${filter.where} ORDER BY a.username,a.id LIMIT ? OFFSET ?`).bind(...filter.values,26,(filter.page-1)*25).all();
|
|
const rows=results.slice(0,25),current=await assignments(rows.map(a=>a.id),filter.context);
|
|
return reply({accounts:rows.map(row=>({...project(row),assignments:current.filter(a=>a.user_id===row.id).map(assignmentLabel)})),page:filter.page,pageSize:25,hasMore:results.length>25,context:filter.context,assignmentMode});
|
|
};
|
|
}
|

Staff