owltide/stores/session.ts
Hornwitser aaa2faffb1 Implement register and login with Telegram
Add the concept of authentication methods that authenticate an account
where using the telegram login widget is one such method.  If a login is
done with an authentication method that's not associated with any
account the session ends up with the data from the authentication
method in order to allow registering a new account with the
authentication method.

This has to be stored on the session as otherwise it wouldn't be
possible to implement authentication methods such as OAuth2 that takes
the user to a third-party site and then redirects the browser back.
2025-07-09 15:34:57 +02:00

79 lines
2 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, ApiSession } 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>(),
authenticationProvider: ref<string>(),
authenticationName: ref<string>(),
id: ref<number>(),
push: ref<boolean>(false),
};
const actions = {
async fetch(event?: H3Event) {
const session = await fetchSessionWithCookie(event)
actions.update(session);
},
update(session?: ApiSession) {
state.account.value = session?.account;
state.authenticationProvider.value = session?.authenticationProvider;
state.authenticationName.value = session?.authenticationName;
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}`);
}
},
};
appEventSource?.addEventListener("update", (event) => {
if (event.data.type !== "connected") {
return;
}
actions.update(event.data.session);
});
return {
...state,
...actions,
};
});