This repository has been archived on 2021-04-30. You can view files and clone it, but cannot push or open issues or pull requests.
blazing-workshop/BlazingPizza.Server/NotificationsController.cs
2020-12-17 16:52:43 +01:00

44 lines
1.4 KiB
C#

using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace BlazingPizza.Server
{
[Route("notifications")]
[ApiController]
[Authorize]
public class NotificationsController : Controller
{
private readonly PizzaStoreContext _db;
public NotificationsController(PizzaStoreContext db)
{
_db = db;
}
[HttpPut("subscribe")]
public async Task<NotificationSubscription> Subscribe(NotificationSubscription subscription)
{
// We're storing at most one subscription per user, so delete old ones.
// Alternatively, you could let the user register multiple subscriptions from different browsers/devices.
var userId = GetUserId();
var oldSubscriptions = _db.NotificationSubscriptions.Where(e => e.UserId == userId);
_db.NotificationSubscriptions.RemoveRange(oldSubscriptions);
// Store new subscription
subscription.UserId = userId;
_db.NotificationSubscriptions.Attach(subscription);
await _db.SaveChangesAsync();
return subscription;
}
private string GetUserId()
{
return HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
}
}
}