2026-01-20 09:02:26 -06:00

77 lines
1.9 KiB
TypeScript

import { define, State } from "../../../utils.ts";
import { Context } from "fresh";
import {
getUserPin as _getUserPin,
setUserPin,
} from "../../../services/userService.ts";
export const handler = define.handlers({
async POST(ctx: Context<State>) {
try {
// Get user ID from session data
const userId = ctx.state.data.user_id;
if (!userId) {
return new Response(
JSON.stringify({ error: "User not authenticated" }),
{
status: 401,
headers: { "Content-Type": "application/json" },
},
);
}
// Parse request body
const body = await ctx.req.json();
const { pin } = body;
// Validate required fields
if (!pin) {
return new Response(
JSON.stringify({ error: "pin is required" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
// Validate pin length (minimum 4 characters)
if (pin.length < 4) {
return new Response(
JSON.stringify({ error: "Pin must be at least 4 characters long" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
// Set user pin in database
const userPin = await setUserPin(userId, pin);
return new Response(
JSON.stringify({
success: true,
user_id: userPin.user_id,
created_on: userPin.created_on,
modified_on: userPin.modified_on,
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
} catch (error) {
console.error("Error setting user pin:", error);
return new Response(
JSON.stringify({ error: "Internal server error" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
});