update state management

This commit is contained in:
Fran Jurmanović
2025-02-08 18:34:06 +01:00
parent 01fc6e9feb
commit 3ad4b95656
10 changed files with 93 additions and 86 deletions

View File

@@ -1,14 +1,13 @@
import { authStore } from '$stores/authStore';
import { redirect } from '@sveltejs/kit';
import { get } from 'svelte/store';
import type { RequestEvent } from '../routes/$types';
const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'https://acc-api.jurmanovic.com/v1';
async function fetchAPI(endpoint: string, method: string = 'GET', body?: object) {
const { token } = get(authStore);
async function fetchAPI(endpoint: string, method: string = 'GET', body?: object, hdr?: object) {
const headers = {
'Content-Type': 'application/json',
Authorization: `Basic ${token}`
...(hdr ?? {})
};
const response = await fetch(`${BASE_URL}${endpoint}`, {
@@ -34,4 +33,15 @@ async function fetchAPI(endpoint: string, method: string = 'GET', body?: object)
return response.text();
}
export async function fetchAPIEvent(
event: object,
endpoint: string,
method: string = 'GET',
body?: object
) {
const token = event.cookies.get('token');
return fetchAPI(endpoint, method, body, { Authorization: `Basic ${token}` });
}
export default fetchAPI;

View File

@@ -1,10 +1,11 @@
import fetchAPI from '$api/apiService';
import fetchAPI, { fetchAPIEvent } from '$api/apiService';
import { authStore } from '$stores/authStore';
import type { RequestEvent } from '../routes/$types';
export const login = async (username: string, password: string) => {
export const login = async (event: object, username: string, password: string) => {
const token = btoa(`${username}:${password}`);
authStore.set({ token });
if (!(await checkAuth())) {
event.cookies.set('token', token, { path: '/' });
if (!(await checkAuth(event))) {
{
authStore.set({ token: undefined, error: 'Invalid username or password.' });
return false;
@@ -13,13 +14,13 @@ export const login = async (username: string, password: string) => {
return true;
};
export const logout = () => {
authStore.set({ token: undefined });
export const logout = (event) => {
event.cookies.delete('token', { path: '/' });
};
export const checkAuth = async () => {
export const checkAuth = async (event: object) => {
try {
await fetchAPI('/api');
await fetchAPIEvent(event, '/api');
return true;
} catch (err) {
return false;

View File

@@ -1,21 +1,21 @@
import fetchAPI from "$api/apiService";
import { fetchAPIEvent } from '$api/apiService';
export const getCarModels = async () => {
return fetchAPI("/lookup/car-models");
export const getCarModels = async (event: object) => {
return fetchAPIEvent(event, '/lookup/car-models');
};
export const getCupCategories = async () => {
return fetchAPI("/lookup/cup-categories");
export const getCupCategories = async (event: object) => {
return fetchAPIEvent(event, '/lookup/cup-categories');
};
export const getDriverCategories = async () => {
return fetchAPI("/lookup/driver-categories");
export const getDriverCategories = async (event: object) => {
return fetchAPIEvent(event, '/lookup/driver-categories');
};
export const getSessionTypes = async () => {
return fetchAPI("/lookup/session-types");
export const getSessionTypes = async (event: object) => {
return fetchAPIEvent(event, '/lookup/session-types');
};
export const getTracks = async () => {
return fetchAPI("/lookup/tracks");
export const getTracks = async (event: object) => {
return fetchAPIEvent(event, '/lookup/tracks');
};

View File

@@ -1,43 +1,45 @@
import fetchAPI from '$api/apiService';
import { fetchAPIEvent } from '$api/apiService';
export const getServers = async () => {
return fetchAPI('/server');
export const getServers = async (event: object) => {
return fetchAPIEvent(event, '/server');
};
export const getConfigFiles = async (serverId = '') => {
return fetchAPI(`/server/${serverId}/config`);
export const getConfigFiles = async (event: object, serverId = '') => {
return fetchAPIEvent(event, `/server/${serverId}/config`);
};
export const getConfigFile = async (serverId = '', file = '') => {
return fetchAPI(`/server/${serverId}/config/${file}`);
export const getConfigFile = async (event: object, serverId = '', file = '') => {
return fetchAPIEvent(event, `/server/${serverId}/config/${file}`);
};
export const updateConfig = async (
event: object,
serverId: string,
file: string,
newConfig?: object,
override = false,
restart = true
) => {
return fetchAPI(
return fetchAPIEvent(
event,
`/server/${serverId}/config/${file}?override=${override}&restart=${restart}`,
'PUT',
newConfig
);
};
export const restartService = async (serverId: number) => {
return fetchAPI('/api/restart', 'POST', { serverId });
export const restartService = async (event: object, serverId: number) => {
return fetchAPIEvent(event, '/api/restart', 'POST', { serverId });
};
export const startService = async (serverId: number) => {
return fetchAPI('/api/start', 'POST', { serverId });
export const startService = async (event: object, serverId: number) => {
return fetchAPIEvent(event, '/api/start', 'POST', { serverId });
};
export const stopService = async (serverId: number) => {
return fetchAPI('/api/stop', 'POST', { serverId });
export const stopService = async (event: object, serverId: number) => {
return fetchAPIEvent(event, '/api/stop', 'POST', { serverId });
};
export const getServiceStatus = async (serviceName: number) => {
return fetchAPI(`/api/${serviceName}`);
export const getServiceStatus = async (event: object, serviceName: number) => {
return fetchAPIEvent(event, `/api/${serviceName}`);
};

View File

@@ -1,11 +1,5 @@
<script>
import { logout } from '$api/authService';
import { goto } from '$app/navigation';
function handleLogout() {
logout();
goto('/login');
}
</script>
<aside
@@ -36,13 +30,13 @@
</a>
</li>
<li>
<a
href="#"
onclick={handleLogout}
class="group flex items-center rounded-lg p-2 text-gray-900 hover:bg-gray-100 dark:text-white dark:hover:bg-gray-700"
>
<span class="ms-3">Logout</span>
</a>
<form method="POST" action="/logout">
<button
class="group flex items-center rounded-lg p-2 text-gray-900 hover:bg-gray-100 dark:text-white dark:hover:bg-gray-700"
>
<span class="ms-3">Logout</span>
</button>
</form>
</li>
</ul>
</div>

View File

@@ -1,8 +0,0 @@
import { authStore } from '$stores/authStore';
import type { Handle } from '@sveltejs/kit';
export const init = () => {
// const token = sessionStorage.getItem('token') ?? undefined;
// console.log(token);
// authStore.set({ token });
};

View File

@@ -1,8 +1,16 @@
import { checkAuth } from '$api/authService';
import { redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const load = async () => {
const isAuth = await checkAuth();
export const load = async (event) => {
const isAuth = await checkAuth(event);
if (isAuth) redirect(308, '/dashboard');
redirect(308, '/login');
};
export const actions = {
logout: async (event) => {
event.cookies.delete('token', { path: '/' });
redirect(303, '/login');
}
} satisfies Actions;

View File

@@ -2,24 +2,24 @@ import { checkAuth } from '$api/authService';
import { getServers, restartService, startService, stopService } from '$api/serverService';
import { redirect, type Actions } from '@sveltejs/kit';
export const load = async () => {
const isAuth = await checkAuth();
export const load = async (event) => {
const isAuth = await checkAuth(event);
if (!isAuth) return redirect(308, '/login');
const servers = await getServers();
const servers = await getServers(event);
return { servers };
};
export const actions = {
start: async ({ request }) => {
const id = (await request.formData()).get('id') as string;
await startService(+id);
start: async (event) => {
const id = (await event.request.formData()).get('id') as string;
await startService(event, +id);
},
restart: async ({ request }) => {
const id = (await request.formData()).get('id') as string;
await restartService(+id);
restart: async (event) => {
const id = (await event.request.formData()).get('id') as string;
await restartService(event, +id);
},
stop: async ({ request }) => {
const id = (await request.formData()).get('id') as string;
await stopService(+id);
stop: async (event) => {
const id = (await event.request.formData()).get('id') as string;
await stopService(event, +id);
}
} satisfies Actions;

View File

@@ -1,24 +1,24 @@
import { updateConfig, getConfigFiles } from '$api/serverService';
import type { Actions } from './$types';
import type { Actions, RequestEvent } from './$types';
import { checkAuth } from '$api/authService';
import { getTracks } from '$api/lookupService';
import { redirect } from '@sveltejs/kit';
export const load = async ({ params }) => {
const isAuth = await checkAuth();
export const load = async (event) => {
const isAuth = await checkAuth(event);
if (!isAuth) return redirect(308, '/login');
const config = await getConfigFiles(params.id);
const tracks = await getTracks();
const config = await getConfigFiles(event, event.params.id);
const tracks = await getTracks(event);
return {
id: params.id,
id: event.params.id,
config,
tracks
};
};
export const actions = {
event: async ({ request }) => {
const formData = await request.formData();
event: async (event: RequestEvent) => {
const formData = await event.request.formData();
const id = formData.get('id') as string;
const object: any = {};
formData.forEach((value, key) => {
@@ -32,7 +32,7 @@ export const actions = {
object[key] = value != '' && !Number.isNaN(+value) ? +value : value;
}
});
await updateConfig(id, 'event.json', object, true, true);
await updateConfig(event, id, 'event.json', object, true, true);
redirect(303, '/dashboard');
}
} satisfies Actions;

View File

@@ -4,15 +4,15 @@ import type { Actions } from './$types';
import { redirect } from '@sveltejs/kit';
export const actions = {
login: async ({ request }) => {
const formData = await request.formData();
login: async (event) => {
const formData = await event.request.formData();
const username = formData.get('username') as string;
const password = formData.get('password') as string;
if (!username || !password) {
authStore.set({ error: 'Invalid username or password' });
return;
}
const isAuth = await login(username, password);
const isAuth = await login(event, username, password);
if (isAuth) redirect(303, '/dashboard');
}
} satisfies Actions;