owltide/server/api/subscribe.post.ts
Hornwitser 52dfde95d1 Tie push subscriptions to current session
If a user logs out from a device the expectation should be that device
no longer having any association with the user's account.  Any existing
push notifications should thefore be removed on server.  For this reason
tie push notifications to a session, and remove them when the session is
deleted.
2025-03-07 15:47:48 +01:00

26 lines
897 B
TypeScript

import { readSubscriptions, writeSubscriptions } from "~/server/database";
import { Subscription } from "~/shared/types/account";
export default defineEventHandler(async (event) => {
const session = await requireAccountSession(event);
const body: { subscription: PushSubscriptionJSON } = await readBody(event);
const subscriptions = await readSubscriptions();
const existingIndex = subscriptions.findIndex(
sub => sub.type === "push" && sub.sessionId === session.id
);
const subscription: Subscription = {
type: "push",
sessionId: session.id,
push: body.subscription
};
if (existingIndex !== -1) {
subscriptions[existingIndex] = subscription;
} else {
subscriptions.push(subscription);
}
await writeSubscriptions(subscriptions);
if (existingIndex !== -1) {
return { message: "Existing subscription refreshed."};
}
return { message: "New subscription registered."};
})