mega-plant/lib/clock-api.ts

23 lines
1.4 KiB
TypeScript
Raw Normal View History

import 'server-only';
import { getSession } from './auth';
import { ClockError } from './clock';
import { clockOriginAllowed } from './clock-origin';
export async function clockAccess(request:Request,options:{multipart?:boolean}={}) {
const session=await getSession();
if(!session)return Response.json({error:'Please sign in.'},{status:401});
if(!session.passwordChanged)return Response.json({error:'Change your starter password first.'},{status:403});
if(request.method==='POST') {
if(!clockOriginAllowed(request.headers))return Response.json({error:'Request origin is not allowed.'},{status:403});
const type=request.headers.get('content-type')||'';
if(!type.startsWith('application/json') && !(options.multipart && type.startsWith('multipart/form-data')))return Response.json({error:'Supply JSON.'},{status:415});
}
return session;
}
export function clockFailure(error:unknown) {
if(error instanceof ClockError)return Response.json({error:error.message},{status:error.status,headers:{'Cache-Control':'no-store'}});
console.error('Clock request failed',error instanceof Error?error.message:'Database unavailable');
return Response.json({error:'Clock service is unavailable. Retry the same confirmation safely.'},{status:503,headers:{'Cache-Control':'no-store'}});
}
export function clockJson(body:unknown) {return Response.json(body,{headers:{'Cache-Control':'private, no-store'}});}