This commit is contained in:
2025-06-08 19:49:32 +02:00
parent 482285abf6
commit 7a8bcca0ef
5 changed files with 59 additions and 11 deletions

4
src/app.d.ts vendored
View File

@@ -3,7 +3,9 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
interface Locals {
token?: string,
}
// interface PageData {}
// interface PageState {}
// interface Platform {}

1
src/lib/auth.ts Normal file
View File

@@ -0,0 +1 @@
export const AUTH_COOIKIE_NAME: string = 'auth-token' as const;

View File

@@ -0,0 +1,30 @@
import { PUBLIC_BACKEND_URL } from '$env/static/public';
import { AUTH_COOIKIE_NAME } from '$lib/auth';
import { error } from '@sveltejs/kit';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ fetch, cookies }) => {
let token = cookies.get(AUTH_COOIKIE_NAME);
if (token != null) {
return {
token
};
}
const response = await fetch(`${PUBLIC_BACKEND_URL}/auth`);
if (!response.ok) {
return error(response.status);
}
token = await response.text();
cookies.set(AUTH_COOIKIE_NAME, token, {
path: '/',
secure: true
});
return {
token
};
};

View File

@@ -2,11 +2,17 @@
import '../app.css';
import { ModeWatcher } from 'mode-watcher';
import { ChatSocket } from '$lib/socket';
import { onMount } from 'svelte';
import { onMount, type Snippet } from 'svelte';
import { browser } from '$app/environment';
import { setMessageStore } from '$lib/message.svelte';
import type { LayoutServerData } from './$types.js';
let { children } = $props();
interface Props {
children: Snippet;
data: LayoutServerData;
}
let { children, data } = $props();
let socket;
@@ -14,7 +20,7 @@
onMount(() => {
if (browser) {
socket = new ChatSocket('ws://localhost:3000/ws', store);
socket = new ChatSocket(`ws://localhost:3000/ws?token=${data.token}`, store);
}
});
</script>

View File

@@ -1,14 +1,23 @@
import type { Actions } from '@sveltejs/kit';
const BACKEND_URL: string = 'http://127.0.0.1:3000' as const;
import { fail, type Actions } from '@sveltejs/kit';
import { PUBLIC_BACKEND_URL } from '$env/static/public';
import { AUTH_COOIKIE_NAME } from '$lib/auth';
export const actions = {
'send-message': async ({request, fetch}) => {
'send-message': async ({ request, fetch, cookies }) => {
const authToken = cookies.get(AUTH_COOIKIE_NAME);
if (authToken == null) {
return fail(400);
}
const formData = await request.formData();
const response = await fetch(`${BACKEND_URL}/message`, {
const response = await fetch(`${PUBLIC_BACKEND_URL}/message`, {
method: 'POST',
body: formData,
headers: {
authorization: `Bearer ${authToken}`
},
body: formData
});
},
}
} satisfies Actions;