diff --git a/Aberwyn/Controllers/PushController.cs b/Aberwyn/Controllers/PushController.cs index 9fecf03..2f5a56b 100644 --- a/Aberwyn/Controllers/PushController.cs +++ b/Aberwyn/Controllers/PushController.cs @@ -38,6 +38,36 @@ namespace Aberwyn.Controllers return Ok(new { message = $"Skickade pizzanotiser till {count} användare." }); } + [HttpPost("subscribe-user")] + public async Task SubscribeUser([FromBody] PushSubscription subscription) + { + var user = await _userManager.GetUserAsync(User); + if (user == null) return Unauthorized(); + + var existing = await _context.PushSubscribers + .FirstOrDefaultAsync(s => s.Endpoint == subscription.Endpoint); + + if (existing == null) + { + var newSub = new PushSubscriber + { + Endpoint = subscription.Endpoint, + P256DH = subscription.Keys["p256dh"], + Auth = subscription.Keys["auth"], + UserId = user.Id + }; + _context.PushSubscribers.Add(newSub); + } + else + { + existing.P256DH = subscription.Keys["p256dh"]; + existing.Auth = subscription.Keys["auth"]; + existing.UserId = user.Id; + } + + await _context.SaveChangesAsync(); + return Ok(); + } [HttpPost("subscribe")] public async Task Subscribe([FromBody] PushSubscriptionWithOrder dto) diff --git a/Aberwyn/Views/User/Profile.cshtml b/Aberwyn/Views/User/Profile.cshtml index 6347da9..be43988 100644 --- a/Aberwyn/Views/User/Profile.cshtml +++ b/Aberwyn/Views/User/Profile.cshtml @@ -98,7 +98,7 @@ applicationServerKey: urlBase64ToUint8Array(vapidPublicKey.trim()) }); - await fetch("/api/push/subscribe", { + await fetch("/api/push/subscribe-user", { method: "POST", body: JSON.stringify(sub), headers: { "Content-Type": "application/json" }