2025-06-30 18:58:24 +02:00
|
|
|
/*
|
|
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
*/
|
2025-05-24 17:53:33 +02:00
|
|
|
import { appendResponseHeader } from "h3";
|
|
|
|
import type { H3Event } from "h3";
|
2025-07-08 15:43:14 +02:00
|
|
|
import type { ApiAccount, ApiSession } from "~/shared/types/api";
|
2025-05-24 17:53:33 +02:00
|
|
|
|
|
|
|
const fetchSessionWithCookie = async (event?: H3Event) => {
|
|
|
|
// Client side
|
|
|
|
if (!event) {
|
|
|
|
return $fetch("/api/auth/session");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Server side
|
|
|
|
const cookie = useRequestHeader("cookie");
|
|
|
|
const res = await $fetch.raw("/api/auth/session", {
|
|
|
|
headers: cookie ? { cookie } : undefined
|
|
|
|
});
|
|
|
|
for (const cookie of res.headers.getSetCookie()) {
|
|
|
|
appendResponseHeader(event, "set-cookie", cookie);
|
|
|
|
}
|
|
|
|
return res._data;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useSessionStore = defineStore("session", () => {
|
|
|
|
const state = {
|
2025-06-11 21:05:17 +02:00
|
|
|
account: ref<ApiAccount>(),
|
2025-05-24 17:53:33 +02:00
|
|
|
id: ref<number>(),
|
|
|
|
push: ref<boolean>(false),
|
|
|
|
};
|
|
|
|
|
|
|
|
const actions = {
|
|
|
|
async fetch(event?: H3Event) {
|
|
|
|
const session = await fetchSessionWithCookie(event)
|
2025-07-08 15:43:14 +02:00
|
|
|
actions.update(session);
|
|
|
|
},
|
|
|
|
update(session?: ApiSession) {
|
2025-05-24 17:53:33 +02:00
|
|
|
state.account.value = session?.account;
|
|
|
|
state.id.value = session?.id;
|
|
|
|
state.push.value = session?.push ?? false;
|
|
|
|
},
|
|
|
|
async logIn(name: string) {
|
|
|
|
const res = await $fetch.raw("/api/auth/login", {
|
|
|
|
method: "POST",
|
|
|
|
body: { name },
|
|
|
|
});
|
|
|
|
await actions.fetch();
|
|
|
|
return `/api/auth/login replied: ${res.status} ${res.statusText}`;
|
|
|
|
},
|
|
|
|
async logOut() {
|
|
|
|
try {
|
|
|
|
await $fetch.raw("/api/auth/session", {
|
|
|
|
method: "DELETE",
|
|
|
|
});
|
|
|
|
await actions.fetch();
|
|
|
|
|
|
|
|
} catch (err: any) {
|
|
|
|
alert(`Log out failed: ${err.statusCode} ${err.statusMessage}`);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2025-07-08 15:43:14 +02:00
|
|
|
appEventSource?.addEventListener("update", (event) => {
|
|
|
|
if (event.data.type !== "connected") {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
actions.update(event.data.session);
|
|
|
|
});
|
|
|
|
|
2025-05-24 17:53:33 +02:00
|
|
|
return {
|
|
|
|
...state,
|
|
|
|
...actions,
|
|
|
|
};
|
|
|
|
});
|