mega-plant/lib/clock-api.ts

21 lines
1.3 KiB
TypeScript

import 'server-only';
import { getSession } from './auth';
import { ClockError } from './clock';
import { clockOriginAllowed } from './clock-origin';
export async function clockAccess(request:Request) {
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});
if(!request.headers.get('content-type')?.startsWith('application/json'))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'}});}