From 633f4570d145705d038df6fe77f8e52755fb7fa3 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 5 Aug 2024 23:17:35 +0200 Subject: [PATCH] Implement proper push notification token deletion Related to #290 Implement proper push notification token deletion during PWA uninstall. * **frontend/public/service.js** - Add an event listener for the `beforeunload` event to handle PWA uninstall. - Call the `unsubscribe` function to delete the push notification token during PWA uninstall. - Define the `unsubscribe` function to send a DELETE request to the server to remove the push notification token. * **backend/services/notification/handler/notification.go** - Update the `Unsubscribe` function to handle token deletion during PWA uninstall. - Add a check to verify if the request is coming from the PWA uninstall event by checking the subscription endpoint. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/kioku-project/kioku/issues/290?shareId=XXXX-XXXX-XXXX-XXXX). --- .../notification/handler/notification.go | 6 ++++++ frontend/public/service.js | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/backend/services/notification/handler/notification.go b/backend/services/notification/handler/notification.go index 2d7ea1d0..1b010188 100644 --- a/backend/services/notification/handler/notification.go +++ b/backend/services/notification/handler/notification.go @@ -2,6 +2,7 @@ package handler import ( "context" + "strings" "github.com/kioku-project/kioku/pkg/converter" "github.com/kioku-project/kioku/pkg/helper" @@ -73,6 +74,11 @@ func (e *Notification) Unsubscribe(ctx context.Context, req *pbCommon.PushSubscr return helper.NewMicroNotAuthorizedErr(helper.NotificationServiceID) } + // Check if the request is coming from the PWA uninstall event + if strings.Contains(req.Subscription.Endpoint, "PWA_UNINSTALL") { + logger.Infof("Received PWA uninstall event for subscription: %v", req.Subscription.SubscriptionID) + } + if err := e.store.DeletePushSubscription(ctx, subscription); err != nil { return err } diff --git a/frontend/public/service.js b/frontend/public/service.js index 0a21710a..94a894c8 100644 --- a/frontend/public/service.js +++ b/frontend/public/service.js @@ -16,3 +16,22 @@ const showLocalNotification = async (title, options, registration) => { icon: "/kioku-logo.png", }); }; + +self.addEventListener("beforeunload", async (event) => { + const subscription = await self.registration.pushManager.getSubscription(); + if (subscription) { + await unsubscribe(subscription); + } +}); + +const unsubscribe = async (subscription) => { + const response = await fetch("/api/user/notification/" + subscription.endpoint, { + method: "DELETE", + headers: { + "Content-Type": "application/json", + }, + }); + if (!response.ok) { + console.error("Failed to unsubscribe:", response.statusText); + } +};