Files

105 lines
4.1 KiB
C#
Raw Permalink Normal View History

using System.Security.Claims;
2026-10-28 14:22:27 +02:00
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
2026-10-28 13:23:35 +02:00
using Microsoft.Extensions.Localization;
using StatiKosev.Data;
2026-10-28 13:23:35 +02:00
using StatiKosev.Services;
namespace StatiKosev.Controllers;
2026-10-28 11:10:46 +02:00
[Route("messages")]
2026-10-28 13:23:35 +02:00
public class PrivateMessageController(
MessageService messagesService,
2026-10-28 14:24:41 +02:00
NtfyNotifier ntfy,
2026-10-28 13:23:35 +02:00
IStringLocalizer<StringValues> strings,
2026-10-28 14:22:27 +02:00
IConfiguration config,
2026-10-28 13:23:35 +02:00
ILogger<PrivateMessageController> logger) : Controller
{
2026-10-28 13:23:35 +02:00
//form post from _MessageMe, redirects back to the page it came from
[HttpPost("send")]
[EnableRateLimiting("contact")]
2026-10-28 13:23:35 +02:00
[ValidateAntiForgeryToken]
public async Task<IActionResult> Send([FromForm] SendPrivateMessageRequest req, [FromForm] string? returnUrl)
{
2026-10-28 11:10:46 +02:00
var back = Url.IsLocalUrl(returnUrl) ? returnUrl : "/";
if (!ModelState.IsValid)
{
2026-10-28 13:23:35 +02:00
TempData["Status"] = strings["MessageInvalid"].Value;
2026-10-28 11:10:46 +02:00
TempData["StatusType"] = "error";
return LocalRedirect(back);
}
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
2026-10-28 11:10:46 +02:00
var senderUsername = User.Identity?.Name;
var userAgent = Request.Headers.UserAgent.ToString();
logger.LogInformation("Received private message from {UserId}", userId ?? "anonymous");
2026-10-28 14:24:41 +02:00
var anonymous = userId is null || senderUsername is null || req.Anonymous;
if (anonymous)
await messagesService.SendAnonymousAsync(req.Body, userAgent);
else
2026-10-28 14:24:41 +02:00
await messagesService.SendAsUserAsync(req.Body, userId!, senderUsername!, userAgent);
ntfy.Notify("New message",
$"{(anonymous ? "Anonymous" : senderUsername)}: {req.Body[..Math.Min(req.Body.Length, 200)]}",
"envelope");
2026-10-28 13:23:35 +02:00
TempData["Status"] = strings["MessageSent"].Value;
2026-10-28 11:10:46 +02:00
TempData["StatusType"] = "success";
return LocalRedirect(back);
}
2026-10-28 13:23:35 +02:00
2026-10-28 14:22:27 +02:00
//password form on the /Inbox page; the admin has no account, only AdminPassword in appsettings.json
[HttpPost("login")]
[EnableRateLimiting("admin-login")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm] string? password)
{
var adminPassword = config["AdminPassword"];
//empty AdminPassword = nobody gets in; hashing both sides gives a constant-time compare of equal-length values
var ok = !string.IsNullOrEmpty(adminPassword) && !string.IsNullOrEmpty(password) &&
CryptographicOperations.FixedTimeEquals(
SHA256.HashData(Encoding.UTF8.GetBytes(password)),
SHA256.HashData(Encoding.UTF8.GetBytes(adminPassword)));
if (!ok)
{
logger.LogWarning("Failed admin login from {Ip}", HttpContext.Connection.RemoteIpAddress);
TempData["Status"] = strings["AdminPasswordWrong"].Value;
TempData["StatusType"] = "error";
return LocalRedirect("/Inbox");
}
var admin = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.Name, "admin"), new Claim(ClaimTypes.Role, "Admin")], Program.AdminScheme));
await HttpContext.SignInAsync(Program.AdminScheme, admin);
return LocalRedirect("/Inbox");
}
[HttpPost("logout")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(Program.AdminScheme);
return LocalRedirect("/");
}
//JSON for the /Inbox page (AJAX)
[HttpGet("list")]
2026-10-28 13:23:35 +02:00
[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();
}