Files
yt2mp3/server/routes/login.post.ts
2026-01-20 17:40:49 +00:00

70 lines
1.9 KiB
TypeScript

import * as z from "zod"
export default defineEventHandler(async (event) => {
const conf = useRuntimeConfig()
const body = await readBody(event)
console.log(body)
const schema = z.object({
email: z.email('Invalid email'),
password: z.string('Password is required').min(8, 'Must be at least 8 characters'),
remember: z.boolean().optional()
})
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'
}));
}
const is_https = await getRequestProtocol(event) == "https"
//console.log(is_https)
if ( !body.email || !body.password )
throw createError({ statusCode: 400, statusMessage: "Bad form. Use e-mail and password" })
//console.log(body)
const req = await fetch(conf.fastapi_url + "/login",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: body.email,
password: body.password,
})
}
)
if (!req.ok) throw createError({ statusCode: req.status })
else {
const body = await req.json();
await setUserSession(event,{
user: {
name: body.first_name,
surname: body.last_name,
email: body.email
},
secure: {
user_id: body.id
}
},
{
maxAge: (body.rembember) ? 60 * 60 * 24 * 7 : undefined,
cookie: {
secure: is_https,
sameSite: is_https ? 'none' : 'lax'
}
})
console.log(await getUserSession(event))
return;
}
})