Files
StatiKosev/Controllers/PrivateMessageController.cs
T

35 lines
1.2 KiB
C#

using StatiKosev.Services;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using StatiKosev.Data;
using StatiKosev.Logging;
namespace StatiKosev.Controllers;
[Route("messages")]
public class PrivateMessageController(MessageService messagesService, ILogger<PrivateMessageController> logger) : ControllerBase
{
[HttpPost("send")]
[EnableRateLimiting("contact")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Send(SendPrivateMessageRequest req, CancellationToken ct)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var userAgent = Request.Headers["User-Agent"].ToString();
if (userId == null)
await messagesService.SendAnonymousAsync(req.Body, userAgent);
else
{
var senderUsername = User.FindFirstValue(userId);
if (senderUsername is null)
{
logger.LogWarning("User {UserId} has no name claim", userId);
return Unauthorized();
}
await messagesService.SendAsUserAsync(req.Body, userId, senderUsername, userAgent);
}
return Accepted();
}
}