Files
social-media/backend/src/Socialize.Api/Modules/Notifications/Handlers/MarkNotificationAsRead.cs

45 lines
1.4 KiB
C#

using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using Socialize.Api.Data;
using Socialize.Api.Infrastructure.Security;
using Socialize.Api.Modules.Notifications.Data;
namespace Socialize.Api.Modules.Notifications.Handlers;
public class MarkNotificationAsReadHandler(
AppDbContext dbContext,
AccessScopeService accessScopeService)
: EndpointWithoutRequest
{
public override void Configure()
{
Post("/api/notifications/{id}/read");
Options(o => o.WithTags("Notifications"));
}
public override async Task HandleAsync(CancellationToken ct)
{
Guid id = Route<Guid>("id");
NotificationEvent? notificationEvent = await dbContext.NotificationEvents.SingleOrDefaultAsync(candidate => candidate.Id == id, ct);
if (notificationEvent is null)
{
await SendNotFoundAsync(ct);
return;
}
Guid currentUserId = User.GetUserId();
bool canReadRecipientNotification = notificationEvent.RecipientUserId == currentUserId;
if (!canReadRecipientNotification && !accessScopeService.CanAccessWorkspace(User, notificationEvent.WorkspaceId))
{
await SendForbiddenAsync(ct);
return;
}
notificationEvent.ReadAt = notificationEvent.ReadAt ?? DateTimeOffset.UtcNow;
await dbContext.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}