89 lines
2.3 KiB
TypeScript
89 lines
2.3 KiB
TypeScript
import { define, State } from "../../../utils.ts";
|
|
import { Context } from "fresh";
|
|
import { getUser, updateUser } from "../../../services/userService.ts";
|
|
import { User } from "../../../db/interfaces.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 { encrypted_data } = body;
|
|
|
|
// Validate input
|
|
if (typeof encrypted_data !== "string") {
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: "encrypted_data is required and must be a string",
|
|
}),
|
|
{
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
// Get existing user
|
|
const existingUser = await getUser(userId) as User;
|
|
if (!existingUser) {
|
|
return new Response(
|
|
JSON.stringify({ error: "User profile not found" }),
|
|
{
|
|
status: 404,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
// Update user with encrypted data
|
|
const updatedUser = await updateUser(userId, {
|
|
encrypted_data,
|
|
});
|
|
|
|
if (!updatedUser) {
|
|
return new Response(
|
|
JSON.stringify({ error: "Failed to update user profile" }),
|
|
{
|
|
status: 500,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
// Return success response
|
|
return new Response(
|
|
JSON.stringify({
|
|
success: true,
|
|
message: "User encrypted data updated successfully",
|
|
}),
|
|
{
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
} catch (error) {
|
|
console.error("Error updating user profile:", error);
|
|
return new Response(
|
|
JSON.stringify({ error: "Internal server error" }),
|
|
{
|
|
status: 500,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
},
|
|
});
|