owltide/server/api/auth/account.delete.ts
Hornwitser 753da6d3d4 Refactor to persist and reliably deliver events
Store events that are to be broadcasted in the database, and fetch
events to serve in the /api/event stream to the client from the
database.  This ensures that events are not lost if the operation to
open the stream takes longer than usual, or the client was not connected
at the time the event was broadcast.

To ensure no events are lost in the transition from server generating
the page to the client hydrating and establishing a connection with the
event stream, the /api/last-event-id endpoint is first queried on the
server before any other entities is fetched from the database.  The
client then passes this id when establishing the event stream, and
receives all events greater than that id.
2025-09-20 20:36:37 +02:00

64 lines
1.8 KiB
TypeScript

/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import {
readUsers, readSessions, readSubscriptions,
writeUsers, writeSessions, writeSubscriptions,
nextEventId,
} from "~/server/database";
import { broadcastEvent, cancelAccountStreams } from "~/server/streams";
export default defineEventHandler(async (event) => {
const serverSession = await requireServerSessionWithUser(event);
let users = await readUsers();
// Expire sessions for this user
const expiredSessionIds = new Set<number>();
let sessions = await readSessions();
const nowMs = Date.now();
for (const session of sessions) {
if (
session.successor !== undefined
&& (session.expiresAtMs === undefined || session.expiresAtMs < nowMs)
&& session.accountId === serverSession.accountId
) {
session.expiresAtMs = nowMs;
broadcastEvent({
id: await nextEventId(),
type: "session-expired",
sessionId: session.id,
});
expiredSessionIds.add(session.id);
}
}
cancelAccountStreams(serverSession.accountId);
await writeSessions(sessions);
await deleteCookie(event, "session");
// Remove subscriptions for this user
let subscriptions = await readSubscriptions();
subscriptions = subscriptions.filter(
subscription => !expiredSessionIds.has(subscription.sessionId)
);
await writeSubscriptions(subscriptions);
// Remove the user
const account = users.find(user => user.id === serverSession.accountId)!;
const now = new Date(nowMs).toISOString();
account.deleted = true;
account.updatedAt = now;
await writeUsers(users);
await broadcastEvent({
id: await nextEventId(),
type: "user-update",
data: {
id: account.id,
updatedAt: now,
deleted: true,
}
});
// Update Schedule counts.
await updateScheduleInterestedCounts(users);
})