60 lines
2.2 KiB
C#
60 lines
2.2 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
using Microsoft.Extensions.Localization;
|
|
using StatiKosev.Data;
|
|
using StatiKosev.Services;
|
|
namespace StatiKosev.Controllers;
|
|
|
|
|
|
[Route("messages")]
|
|
public class PrivateMessageController(
|
|
MessageService messagesService,
|
|
IStringLocalizer<StringValues> strings,
|
|
ILogger<PrivateMessageController> logger) : Controller
|
|
{
|
|
//form post from _MessageMe, redirects back to the page it came from
|
|
[HttpPost("send")]
|
|
[EnableRateLimiting("contact")]
|
|
[ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Send([FromForm] SendPrivateMessageRequest req, [FromForm] string? returnUrl)
|
|
{
|
|
var back = Url.IsLocalUrl(returnUrl) ? returnUrl : "/";
|
|
|
|
if (!ModelState.IsValid)
|
|
{
|
|
TempData["Status"] = strings["MessageInvalid"].Value;
|
|
TempData["StatusType"] = "error";
|
|
return LocalRedirect(back);
|
|
}
|
|
|
|
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
var senderUsername = User.Identity?.Name;
|
|
var userAgent = Request.Headers.UserAgent.ToString();
|
|
|
|
logger.LogInformation("Received private message from {UserId}", userId ?? "anonymous");
|
|
|
|
if (userId is null || senderUsername is null || req.Anonymous)
|
|
await messagesService.SendAnonymousAsync(req.Body, userAgent);
|
|
else
|
|
await messagesService.SendAsUserAsync(req.Body, userId, senderUsername, userAgent);
|
|
|
|
TempData["Status"] = strings["MessageSent"].Value;
|
|
TempData["StatusType"] = "success";
|
|
return LocalRedirect(back);
|
|
}
|
|
|
|
//JSON for the Inbox page (AJAX)
|
|
[HttpGet("")]
|
|
[Authorize(Policy = "AdminOnly")]
|
|
public async Task<IActionResult> Inbox(bool unreadOnly = false) =>
|
|
Ok(await messagesService.GetInboxAsync(unreadOnly));
|
|
|
|
[HttpPost("{id:int}/read")]
|
|
[Authorize(Policy = "AdminOnly")]
|
|
[ValidateAntiForgeryToken] // token comes in the RequestVerificationToken header
|
|
public async Task<IActionResult> MarkRead(int id) =>
|
|
await messagesService.MarkReadAsync(id) == 0 ? NotFound() : NoContent();
|
|
}
|