Files
SGF/scripts/sgf-single-http.mjs
2026-11-11 09:00:17 +02:00

9 lines
1.7 KiB
JavaScript

import assert from 'node:assert/strict';
export async function session(profile,module){
const jar=new Map();const send=async(path,options={})=>{const response=await fetch('http://127.0.0.1:8085'+path,{...options,redirect:'manual',headers:{Accept:'application/json',Cookie:[...jar].map(([k,v])=>k+'='+v).join('; '),...options.headers}});for(const cookie of response.headers.getSetCookie()){const [pair]=cookie.split(';'),at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));}return response;};
let response=await send('/sgf',{headers:{Accept:'text/html'}});assert.equal(response.status,200);const html=await response.text();const csrf=html.match(/name="_token" value="([^"]+)"/)?.[1];assert(csrf);
response=await send('/sgf/entrar',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({_token:csrf,profile,module_id:module})});assert.equal(response.status,302,'approved profile/module entry');
response=await send('/api/session');assert.equal(response.status,200);const identity=await response.json();assert.equal(identity.context.module_id,module);assert.equal(identity.context.company.id,2);assert.equal(identity.context.unit.id,2);
return {identity,get:(path,options={})=>send(path,{...options,headers:{'X-SGF-Context':identity.context.token,...options.headers}}),command:async(path,body,key=crypto.randomUUID())=>{const r=await send(path,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-TOKEN':identity.csrf_token??identity.csrf??csrf,'X-SGF-Context':identity.context.token,'Idempotency-Key':key},body:JSON.stringify(body)});const text=await r.text();let value;try{value=JSON.parse(text);}catch{value={message:'Non-JSON response'};}return {status:r.status,value};}};
}