MC/website/node/postbank-api.mjs

28 lines
2.4 KiB
JavaScript

import {identity} from './auth.mjs';
import {PostbankService} from './postbank-service.mjs';
import {createPostbankAuthority} from './postbank-authority.mjs';
import {POSTBANK_CONTRACTS} from './postbank-contract.mjs';
export function createPostbankApi(central,bank,settings={},deps={}){
const auth=deps.authenticate||(request=>identity(request,central)),authority=deps.authority||createPostbankAuthority(central),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const service=bank?new PostbankService(bank,authority,deps):null;
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
return async request=>{
const url=new URL(request.url),path=url.pathname;
const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401);
if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503);
if(url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
if(request.method==='GET'&&['/api/bank/overview','/api/bank/client','/api/bank/accounts'].includes(path)){
try{return reply(await service.overview(user));}catch{return reply({message:'The bank could not confirm the current records. Reload the workspace.'},503);}
}
if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:POSTBANK_CONTRACTS});
if(path==='/api/bank/activate'){
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const text=await request.text();if(text.length>3000)return reply({message:'Request too large.'},413);
let body;try{body=JSON.parse(text);}catch{return reply({message:'Select your package again.'},400);}
try{return reply(await service.activate(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'Activation failed. Return to the package selection and try again.',returnTo:'package_selection'},error.status||503);}
}
return reply({message:'This bank function is not implemented yet. No request was forwarded to the old game bank.',state:'planned'},501);
};
}