using System.Security.Claims; using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.Authentication; 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 strings, IConfiguration config, ILogger logger) : Controller { //form post from _MessageMe, redirects back to the page it came from [HttpPost("send")] [EnableRateLimiting("contact")] [ValidateAntiForgeryToken] public async Task 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); } //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 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 Logout() { await HttpContext.SignOutAsync(Program.AdminScheme); return LocalRedirect("/"); } //JSON for the /Inbox page (AJAX) [HttpGet("list")] [Authorize(Policy = "AdminOnly")] public async Task 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 MarkRead(int id) => await messagesService.MarkReadAsync(id) == 0 ? NotFound() : NoContent(); }