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.
This commit is contained in:
Hornwitser 2025-07-09 15:21:39 +02:00
parent 2d6bcebc5a
commit aaa2faffb1
14 changed files with 357 additions and 8 deletions

View file

@ -51,7 +51,13 @@ export async function clearServerSession(event: H3Event) {
deleteCookie(event, "session");
}
export async function setServerSession(event: H3Event, account: ServerUser) {
export async function setServerSession(
event: H3Event,
account: ServerUser | undefined,
authenticationProvider?: "telegram",
authenticationSlug?: string,
authenticationName?: string,
) {
const sessions = await readSessions();
const runtimeConfig = useRuntimeConfig(event);
await clearServerSessionInternal(event, sessions);
@ -60,6 +66,9 @@ export async function setServerSession(event: H3Event, account: ServerUser) {
const newSession: ServerSession = {
access: account?.type ?? "anonymous",
accountId: account?.id,
authenticationProvider,
authenticationSlug,
authenticationName,
rotatesAtMs: now + runtimeConfig.sessionRotatesTimeout * 1000,
discardAtMs: now + runtimeConfig.sessionDiscardTimeout * 1000,
id: await nextSessionId(),
@ -68,6 +77,7 @@ export async function setServerSession(event: H3Event, account: ServerUser) {
sessions.push(newSession);
await writeSessions(sessions);
await setSignedCookie(event, "session", String(newSession.id), runtimeConfig.sessionDiscardTimeout)
return newSession;
}
async function rotateSession(event: H3Event, sessions: ServerSession[], session: ServerSession) {
@ -78,6 +88,7 @@ async function rotateSession(event: H3Event, sessions: ServerSession[], session:
const newSession: ServerSession = {
accountId: account?.id,
access: account?.type ?? "anonymous",
// Authentication provider is removed to avoid possibility of an infinite delay before using it.
rotatesAtMs: now + runtimeConfig.sessionRotatesTimeout * 1000,
discardAtMs: now + runtimeConfig.sessionDiscardTimeout * 1000,
id: await nextSessionId(),
@ -172,6 +183,8 @@ export async function serverSessionToApi(event: H3Event, session: ServerSession)
return {
id: session.id,
account,
authenticationProvider: session.authenticationProvider,
authenticationName: session.authenticationName,
push,
};
}