owltide/server/api/auth/account.delete.ts

63 lines
1.7 KiB
TypeScript
Raw Normal View History

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