I firmly believe in free software. The application I'm making here have capabilities that I've not seen in any system. It presents itself as an opportunity to collaborate on a tool that serves the people rather than corporations. Whose incentives are to help people rather, not make the most money. And whose terms ensure that these freedoms and incentives cannot be taken back or subverted. I license this software under the AGPL.
65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import { appendResponseHeader } from "h3";
|
|
import type { H3Event } from "h3";
|
|
import type { ApiAccount } from "~/shared/types/api";
|
|
|
|
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 = {
|
|
account: ref<ApiAccount>(),
|
|
id: ref<number>(),
|
|
push: ref<boolean>(false),
|
|
};
|
|
|
|
const actions = {
|
|
async fetch(event?: H3Event) {
|
|
const session = await fetchSessionWithCookie(event)
|
|
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}`);
|
|
}
|
|
},
|
|
};
|
|
|
|
return {
|
|
...state,
|
|
...actions,
|
|
};
|
|
});
|