109 lines
2.4 KiB
TypeScript

import { error, json, text, type Cookies } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { UserApp, User } from '$lib/server/classes/users';
import { SessionApp, Session } from '$lib/server/classes/sessions';
import { AppData } from '$lib/server/classes/appdata';
import { logger } from '$lib/server/utils/logger';
/***********************************************************
*
* Author: Christian Risi 26/06/2025
*
*
*
*
***********************************************************/
export const POST: RequestHandler = async ({ request, locals, cookies }) => {
const req: Request = request
const local: App.Locals = locals
const cookie: Cookies = cookies
const session = local.session
if (session) {
// The user is providing valid credentials
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/403
return error(403, "Forbidden")
}
let userJson: { username: string, password: string }
let tmpJSON: any
try {
tmpJSON = await req.json()
} catch {
return error(400, "Bad Request")
}
if (!tmpJSON.username || !tmpJSON.password) {
return error(400, "Bad Request")
}
userJson = tmpJSON
// If this fails, should be a 400?
let user: User
try {
user = await UserApp.createUser(
userJson.username,
userJson.password
)
} catch {
return error(400, "The user already exists")
}
let newSession
try {
newSession = SessionApp.createSessionFromUserID(
user.userID
)
} catch(err){
logger.debug(`error: ${err}`, "API Register")
return error(500, "Internal Server Error")
}
const sessionCookie = await new AppData(
newSession,
user
).toCookie()
cookie.set(
"session",
sessionCookie,
{
path: "/"
}
)
const res = new Response(
null,
{
status: 201,
statusText: "Created",
}
)
return res
}
export const fallback: RequestHandler = async ({ request }) => {
// TODO: return method not allowed
const res = new Response(
null,
{
status: 405,
statusText: "Method Not Allowed",
headers: {
Allow: "POST"
}
}
)
return res
};