This commit is contained in:
Alex
2025-03-01 12:40:28 +01:00
parent f00e0fa758
commit c6be9d2302

View File

@@ -1,75 +1,76 @@
import { BASE_API_URI } from "$lib/utils/constants"; import { BASE_API_URI } from '$lib/utils/constants';
import { formatError } from "$lib/utils/helpers"; import { formatError } from '$lib/utils/helpers';
import { fail, redirect } from "@sveltejs/kit"; import { fail, redirect } from '@sveltejs/kit';
/** @type {import('./$types').PageServerLoad} */ /** @type {import('./$types').PageServerLoad} */
export async function load({ locals }) { export async function load({ locals }) {
// redirect user if logged in // redirect user if logged in
console.log("loading login page"); console.log('loading login page');
if (locals.user) { if (locals.user) {
console.log("user is logged in"); console.log('user is logged in');
throw redirect(302, "/"); throw redirect(302, '/');
} }
} }
/** @type {import('./$types').Actions} */ /** @type {import('./$types').Actions} */
export const actions = { export const actions = {
/** /**
* *
* @param request - The request object * @param request - The request object
* @param fetch - Fetch object from sveltekit * @param fetch - Fetch object from sveltekit
* @param cookies - SvelteKit's cookie object * @param cookies - SvelteKit's cookie object
* @returns Error data or redirects user to the home page or the previous page * @returns Error data or redirects user to the home page or the previous page
*/ */
login: async ({ request, fetch, cookies }) => { login: async ({ request, fetch, cookies }) => {
console.log("login action called"); console.log('login action called');
const data = await request.formData(); const data = await request.formData();
const email = String(data.get("email")); const email = String(data.get('email'));
const password = String(data.get("password")); const password = String(data.get('password'));
const next = String(data.get("next")); const next = String(data.get('next'));
/** @type {RequestInit} */ /** @type {RequestInit} */
const requestInitOptions = { const requestInitOptions = {
method: "POST", method: 'POST',
credentials: "include", credentials: 'include',
headers: { headers: {
"Content-Type": "application/json", 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
email: email, email: email,
password: password, password: password
}), })
}; };
const res = await fetch(`${BASE_API_URI}/users/login`, requestInitOptions); console.log('API call url:', `${BASE_API_URI}/users/login`);
console.log("Login response status:", res.status); const res = await fetch(`${BASE_API_URI}/users/login`, requestInitOptions);
console.log("Login response headers:", Object.fromEntries(res.headers)); console.log('Login response status:', res.status);
console.log('Login response headers:', Object.fromEntries(res.headers));
if (!res.ok) { if (!res.ok) {
const errorData = await res.json(); const errorData = await res.json();
const errors = formatError(errorData.errors); const errors = formatError(errorData.errors);
return fail(res.status, { errors }); return fail(res.status, { errors });
} }
const responseBody = await res.json(); const responseBody = await res.json();
console.log("Login response body:", responseBody); console.log('Login response body:', responseBody);
// Extract the JWT from the response headers // Extract the JWT from the response headers
const setCookieHeader = res.headers.get("set-cookie"); const setCookieHeader = res.headers.get('set-cookie');
if (setCookieHeader) { if (setCookieHeader) {
const jwtMatch = setCookieHeader.match(/jwt=([^;]+)/); const jwtMatch = setCookieHeader.match(/jwt=([^;]+)/);
if (jwtMatch) { if (jwtMatch) {
const jwtValue = jwtMatch[1]; const jwtValue = jwtMatch[1];
// Set the cookie for the client // Set the cookie for the client
cookies.set("jwt", jwtValue, { cookies.set('jwt', jwtValue, {
path: "/", path: '/',
httpOnly: true, httpOnly: true,
secure: process.env.NODE_ENV === "production", // Secure in production secure: process.env.NODE_ENV === 'production', // Secure in production
sameSite: "lax", sameSite: 'lax',
maxAge: 5 * 24 * 60 * 60, // 5 days in seconds maxAge: 5 * 24 * 60 * 60 // 5 days in seconds
}); });
} }
} }
console.log("Redirecting to:", next || "/"); console.log('Redirecting to:', next || '/');
throw redirect(303, next || "/"); throw redirect(303, next || '/');
}, }
}; };