50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import * as z from "zod"
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
|
|
const body = await readBody(event)
|
|
if (body.new_pw !== body.confirm_new_pw)
|
|
throw createError({status:400, message: "Passwords don't match!"})
|
|
|
|
const session = await getUserSession(event)
|
|
const config = await useRuntimeConfig(event)
|
|
|
|
const schema = z.object({
|
|
old_pw: z.string(),
|
|
new_pw: z.string().min(8, "Min 8 chars"),
|
|
confirm_new_pw: z.string().min(8, "Min 8 chars"),
|
|
})
|
|
|
|
let validated;
|
|
try {
|
|
validated = schema.parse(body); // throws if invalid
|
|
} catch (err: any) {
|
|
// Zod throws a ZodError
|
|
return sendError(event, createError({
|
|
statusCode: 400,
|
|
statusMessage: err.errors?.[0]?.message || 'Invalid input'
|
|
}));
|
|
}
|
|
|
|
// @ts-ignore
|
|
const userId = session.secure?.user_id;
|
|
if (userId == undefined || userId == null)
|
|
throw createError({ status: 401 })
|
|
|
|
const current_r = await fetch(config.fastapi_url + "/me" + '?' +
|
|
new URLSearchParams({ id: userId }))
|
|
if (!current_r.ok)
|
|
if (current_r.status == 404)
|
|
throw createError({status: 404, message: "User doesn't exist"})
|
|
|
|
await $fetch(config.fastapi_url + "/changepw", {
|
|
method: "POST",
|
|
body: {
|
|
user_id: userId,
|
|
old_password: body.old_pw,
|
|
password: body.new_pw
|
|
}
|
|
})
|
|
|
|
})
|