116 lines
2.6 KiB
TypeScript
116 lines
2.6 KiB
TypeScript
import { error, json, redirect, 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';
|
|
import { DEBUG } from '$lib/server/utils/constants';
|
|
|
|
/***********************************************************
|
|
*
|
|
* 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 (!DEBUG) {
|
|
return redirect(307, "api/program/register")
|
|
}
|
|
|
|
console.log(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
|
|
}; |