This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
using Api.Models;
|
||||
using Api.Services.Contracts;
|
||||
using Api.Settings;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Exposes endpoints used by the frontend to send contact messages and to
|
||||
/// subscribe to newsletters. All endpoints are protected by reCAPTCHA
|
||||
/// verification and rate limiting.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[EnableCors("FrontendOnly")]
|
||||
public sealed class ContactController : ControllerBase
|
||||
{
|
||||
private readonly CaptchaSettings _captchaSettings;
|
||||
private readonly ICaptchaVerifier _captcha;
|
||||
private readonly IEmailSender _email;
|
||||
private readonly ILogger<ContactController> _log;
|
||||
|
||||
public ContactController(IOptions<CaptchaSettings> options, ICaptchaVerifier captcha, IEmailSender email, ILogger<ContactController> log)
|
||||
{
|
||||
_captchaSettings = options.Value;
|
||||
_captcha = captcha;
|
||||
_email = email;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the public reCAPTCHA site key used by the client to render
|
||||
/// the reCAPTCHA widget and obtain client-side tokens.
|
||||
/// </summary>
|
||||
/// <returns>200 OK with the public site key as a string.</returns>
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetReCaptchaSiteKey(CancellationToken ct)
|
||||
{
|
||||
return Ok(_captchaSettings.PublicKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the provided reCAPTCHA token and sends a contact message
|
||||
/// via the configured email sender.
|
||||
/// </summary>
|
||||
/// <param name="req">Contact request containing name, email, subject,
|
||||
/// and message. The <c>CaptchaToken</c> field is required for verification.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>
|
||||
/// 200 OK when the message was queued/sent; 400 Bad Request when
|
||||
/// captcha verification fails; 500 on internal errors.
|
||||
/// </returns>
|
||||
[HttpPost]
|
||||
[EnableRateLimiting("contact")]
|
||||
public async Task<IActionResult> Send([FromBody] ContactRequest req, CancellationToken ct)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return ValidationProblem(ModelState);
|
||||
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
var res = await ValidateCaptcha(req.CaptchaToken, ct);
|
||||
if (!res.Verdict.Success) return BadRequest("Captcha verification failed.");
|
||||
|
||||
try
|
||||
{
|
||||
await _email.SendContactAsync(req, ct);
|
||||
return Ok(new { ok = true });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Contact send failed. ip={Ip} from={From}", res.UserIp, req.Email);
|
||||
return StatusCode(500, "Could not send message.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the provided reCAPTCHA token and subscribes the given
|
||||
/// email address to the newsletter or mailing list.
|
||||
/// </summary>
|
||||
/// <param name="req">Subscription request containing the email and
|
||||
/// the <c>CaptchaToken</c>.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>
|
||||
/// 200 OK when subscription succeeded; 400 when captcha verification
|
||||
/// fails; 500 on internal errors.
|
||||
/// </returns>
|
||||
[HttpPost("subscribe")]
|
||||
[EnableRateLimiting("contact")]
|
||||
public async Task<IActionResult> Subscribe([FromBody] SubscribeRequest req, CancellationToken ct)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return ValidationProblem(ModelState);
|
||||
|
||||
var res = await ValidateCaptcha(req.CaptchaToken, ct);
|
||||
if (!res.Verdict.Success) return BadRequest("Captcha verification failed.");
|
||||
|
||||
try
|
||||
{
|
||||
await _email.SendSubscribeAsync(req, ct);
|
||||
return Ok(new { ok = true });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Subscription failed. ip={Ip} eMail={eMail}", res.UserIp, req.Email);
|
||||
return StatusCode(500, "Failed.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper that runs reCAPTCHA verification for the supplied token and
|
||||
/// returns the verdict along with the resolved user IP address.
|
||||
/// </summary>
|
||||
/// <param name="token">Client-provided reCAPTCHA token.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>Tuple containing the verification verdict and user IP.</returns>
|
||||
private async Task<(CaptchaVerdict Verdict, string? UserIp)> ValidateCaptcha(string token, CancellationToken ct)
|
||||
{
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var verdict = await _captcha.VerifyAsync(token, userIp, ct);
|
||||
if (!verdict.Success)
|
||||
{
|
||||
_log.LogWarning("Captcha failed. ip={Ip} score={Score} err={Err}",
|
||||
userIp, verdict.Score, verdict.Error);
|
||||
}
|
||||
return (verdict, userIp);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
using Api.Services.Contracts;
|
||||
using Api.Settings;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Controller for handling file downloads with support for resume and chunked transfers.
|
||||
/// Routes are prefixed with "api/filedownload".
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[EnableCors("FrontendOnly")]
|
||||
public sealed class FileDownloadController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<FileDownloadController> _logger;
|
||||
private readonly FileStorageSettings _fileStorageSettings;
|
||||
private readonly IContentTypeProvider _contentTypeProvider;
|
||||
private readonly IEmailSender _emailSender;
|
||||
private const int BufferSize = 81920; // 80 KB buffer for optimal streaming performance
|
||||
|
||||
public FileDownloadController(
|
||||
ILogger<FileDownloadController> logger,
|
||||
IOptions<FileStorageSettings> fileStorageSettings,
|
||||
IContentTypeProvider contentTypeProvider,
|
||||
IEmailSender emailSender)
|
||||
{
|
||||
_logger = logger;
|
||||
_fileStorageSettings = fileStorageSettings.Value;
|
||||
_contentTypeProvider = contentTypeProvider;
|
||||
_emailSender = emailSender;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a file with support for resume (range requests) and chunked transfer.
|
||||
/// Supports HTTP 206 Partial Content for efficient downloads and resume capability.
|
||||
/// Sends email notification when download starts.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file to download (optional - uses default from settings if not provided)</param>
|
||||
/// <returns>File stream with appropriate headers for resumable downloads</returns>
|
||||
/// <response code="200">Full file content</response>
|
||||
/// <response code="206">Partial file content (range request)</response>
|
||||
/// <response code="404">File not found</response>
|
||||
/// <response code="416">Requested range not satisfiable</response>
|
||||
[HttpGet("{fileName?}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status206PartialContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status416RangeNotSatisfiable)]
|
||||
public async Task<IActionResult> DownloadFile(string? fileName = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Use default file name from settings if not provided
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
{
|
||||
fileName = _fileStorageSettings.DefaultFileName;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
{
|
||||
_logger.LogWarning("No file name provided and no default file name configured");
|
||||
return BadRequest(new { error = "File name is required" });
|
||||
}
|
||||
|
||||
_logger.LogInformation("Using default file name from settings: {FileName}", fileName);
|
||||
}
|
||||
|
||||
// Get the file storage path (relative to solution folder)
|
||||
var fileStoragePath = _fileStorageSettings.Path;
|
||||
|
||||
// If path is not absolute, make it relative to the solution root
|
||||
if (!Path.IsPathRooted(fileStoragePath))
|
||||
{
|
||||
var solutionRoot = Directory.GetCurrentDirectory();
|
||||
// Go up from api folder to solution root if needed
|
||||
if (solutionRoot.EndsWith("api", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
solutionRoot = Directory.GetParent(solutionRoot)?.FullName ?? solutionRoot;
|
||||
}
|
||||
fileStoragePath = Path.Combine(solutionRoot, fileStoragePath);
|
||||
}
|
||||
|
||||
// Sanitize fileName to prevent directory traversal attacks
|
||||
var sanitizedFileName = Path.GetFileName(fileName);
|
||||
var filePath = Path.Combine(fileStoragePath, sanitizedFileName);
|
||||
|
||||
// Verify file exists
|
||||
if (!System.IO.File.Exists(filePath))
|
||||
{
|
||||
_logger.LogWarning("File not found: {FilePath}", filePath);
|
||||
return NotFound(new { error = "File not found" });
|
||||
}
|
||||
|
||||
var fileInfo = new FileInfo(filePath);
|
||||
var fileLength = fileInfo.Length;
|
||||
|
||||
// Determine content type
|
||||
if (!_contentTypeProvider.TryGetContentType(filePath, out var contentType))
|
||||
{
|
||||
contentType = "application/octet-stream";
|
||||
}
|
||||
|
||||
// Send email notification asynchronously (fire and forget with error handling)
|
||||
// This is done before streaming to ensure notification is sent for both full and range downloads
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await _emailSender.SendFileDownloadNotificationAsync(sanitizedFileName, userIp, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to send file download notification for {FileName}", sanitizedFileName);
|
||||
}
|
||||
});
|
||||
|
||||
// Check if this is a range request
|
||||
var rangeHeader = Request.Headers[HeaderNames.Range].ToString();
|
||||
|
||||
if (!string.IsNullOrEmpty(rangeHeader))
|
||||
{
|
||||
return await HandleRangeRequest(filePath, fileLength, contentType, rangeHeader, sanitizedFileName);
|
||||
}
|
||||
|
||||
// Full file download
|
||||
_logger.LogInformation("Starting full file download: {FileName} ({FileSize} bytes)", sanitizedFileName, fileLength);
|
||||
|
||||
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, useAsync: true);
|
||||
|
||||
Response.Headers.Append(HeaderNames.AcceptRanges, "bytes");
|
||||
Response.Headers.Append(HeaderNames.ContentLength, fileLength.ToString());
|
||||
|
||||
return File(stream, contentType, sanitizedFileName, enableRangeProcessing: true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error downloading file: {FileName}", fileName);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, new { error = "An error occurred while downloading the file" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles HTTP range requests for partial content downloads and resume support.
|
||||
/// </summary>
|
||||
private async Task<IActionResult> HandleRangeRequest(
|
||||
string filePath,
|
||||
long fileLength,
|
||||
string contentType,
|
||||
string rangeHeader,
|
||||
string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Parse range header (format: "bytes=start-end")
|
||||
var range = rangeHeader.Replace("bytes=", "").Split('-');
|
||||
|
||||
long startByte = 0;
|
||||
long endByte = fileLength - 1;
|
||||
|
||||
if (!string.IsNullOrEmpty(range[0]))
|
||||
{
|
||||
startByte = long.Parse(range[0]);
|
||||
}
|
||||
|
||||
if (range.Length > 1 && !string.IsNullOrEmpty(range[1]))
|
||||
{
|
||||
endByte = long.Parse(range[1]);
|
||||
}
|
||||
|
||||
// Validate range
|
||||
if (startByte > endByte || startByte >= fileLength)
|
||||
{
|
||||
_logger.LogWarning("Invalid range request: {Range} for file size {FileLength}", rangeHeader, fileLength);
|
||||
return StatusCode(StatusCodes.Status416RangeNotSatisfiable);
|
||||
}
|
||||
|
||||
// Adjust end byte if it exceeds file length
|
||||
if (endByte >= fileLength)
|
||||
{
|
||||
endByte = fileLength - 1;
|
||||
}
|
||||
|
||||
var contentLength = endByte - startByte + 1;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Range request for {FileName}: bytes {Start}-{End}/{Total} ({ContentLength} bytes)",
|
||||
fileName, startByte, endByte, fileLength, contentLength);
|
||||
|
||||
// Open file stream and seek to start position
|
||||
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, useAsync: true);
|
||||
stream.Seek(startByte, SeekOrigin.Begin);
|
||||
|
||||
// Set response headers for partial content
|
||||
Response.StatusCode = StatusCodes.Status206PartialContent;
|
||||
Response.Headers.Append(HeaderNames.AcceptRanges, "bytes");
|
||||
Response.Headers.Append(HeaderNames.ContentRange, $"bytes {startByte}-{endByte}/{fileLength}");
|
||||
Response.Headers.Append(HeaderNames.ContentLength, contentLength.ToString());
|
||||
Response.ContentType = contentType;
|
||||
|
||||
// Stream the requested range
|
||||
await StreamRangeAsync(stream, Response.Body, contentLength);
|
||||
|
||||
await stream.DisposeAsync();
|
||||
|
||||
return new EmptyResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error processing range request for file: {FileName}", fileName);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Efficiently streams a specific byte range from source to destination.
|
||||
/// </summary>
|
||||
private static async Task StreamRangeAsync(Stream source, Stream destination, long bytesToRead)
|
||||
{
|
||||
var buffer = new byte[BufferSize];
|
||||
long totalBytesRead = 0;
|
||||
|
||||
while (totalBytesRead < bytesToRead)
|
||||
{
|
||||
var bytesToReadThisIteration = (int)Math.Min(BufferSize, bytesToRead - totalBytesRead);
|
||||
var bytesRead = await source.ReadAsync(buffer.AsMemory(0, bytesToReadThisIteration));
|
||||
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
break; // End of stream
|
||||
}
|
||||
|
||||
await destination.WriteAsync(buffer.AsMemory(0, bytesRead));
|
||||
totalBytesRead += bytesRead;
|
||||
}
|
||||
|
||||
await destination.FlushAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Api.Settings;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides simple endpoints to expose Google related public keys used by
|
||||
/// the frontend (for example Google Analytics tag id and Maps API key).
|
||||
/// These endpoints return only public values safe to be exposed to clients.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[EnableCors("FrontendOnly")]
|
||||
public sealed class GoogleController : ControllerBase
|
||||
{
|
||||
private readonly GoogleSettings _googleSettings;
|
||||
private readonly ILogger<GoogleController> _log;
|
||||
|
||||
public GoogleController(IOptions<GoogleSettings> options, ILogger<GoogleController> log)
|
||||
{
|
||||
_googleSettings = options.Value;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Google Tag Manager ID used by the frontend for analytics and tracking.
|
||||
/// </summary>
|
||||
/// <returns>200 OK with the Tag Manager ID as a string.</returns>
|
||||
[HttpGet("tagmanager")]
|
||||
public async Task<IActionResult> GetTagManagerId(CancellationToken ct)
|
||||
{
|
||||
return Ok(_googleSettings.TagManagerId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Google Maps API key used by the frontend to load the
|
||||
/// Maps JavaScript API. This key is expected to be restricted and
|
||||
/// safe to expose for client-side usage.
|
||||
/// </summary>
|
||||
/// <returns>200 OK with the maps API key as a string.</returns>
|
||||
[HttpGet("maps")]
|
||||
public async Task<IActionResult> GetMapKey(CancellationToken ct)
|
||||
{
|
||||
return Ok(_googleSettings.MapKey);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Controller that exposes simple health and readiness endpoints for the API.
|
||||
/// Routes are prefixed with "api/health".
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
// Enables only the "FrontendOnly" CORS policy so browser requests from the frontend are allowed.
|
||||
[EnableCors("FrontendOnly")]
|
||||
public sealed class HealthController : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Liveness probe.
|
||||
/// Indicates whether the process is running. Used by orchestration systems to confirm the process is alive.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// 200 OK with JSON payload: { "status": "alive" } when the process is running.
|
||||
/// </returns>
|
||||
// GET api/health/live
|
||||
[HttpGet("live")]
|
||||
public IActionResult Live() => Ok(new { status = "alive" });
|
||||
|
||||
/// <summary>
|
||||
/// Basic health check endpoint.
|
||||
/// Returns overall status and the current server time in UTC.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// 200 OK with JSON payload: { "status": "ok", "time": <UTC time> }.
|
||||
/// </returns>
|
||||
// GET api/health
|
||||
[HttpGet]
|
||||
public IActionResult Health() => Ok(new { status = "ok", time = DateTimeOffset.UtcNow });
|
||||
|
||||
/// <summary>
|
||||
/// Echo endpoint.
|
||||
/// Returns the received JSON payload unchanged. Useful for testing request/response plumbing.
|
||||
/// </summary>
|
||||
/// <param name="payload">Arbitrary JSON from the request body. The endpoint returns the same object.</param>
|
||||
/// <returns>200 OK with the same JSON payload provided in the request body.</returns>
|
||||
// POST api/health/echo
|
||||
[HttpPost("echo")]
|
||||
public IActionResult Echo(object payload) => Ok(payload);
|
||||
|
||||
/// <summary>
|
||||
/// Readiness probe.
|
||||
/// Indicates whether the service is ready to accept traffic. Typically checks downstream dependencies.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// 200 OK with JSON { "status": "ready" } when ready;
|
||||
/// 503 Service Unavailable with JSON { "status": "not_ready" } when not ready.
|
||||
/// </returns>
|
||||
// GET api/health/ready
|
||||
[HttpGet("ready")]
|
||||
public IActionResult Ready()
|
||||
{
|
||||
var ready = true;
|
||||
|
||||
return ready
|
||||
? Ok(new { status = "ready" })
|
||||
: StatusCode(503, new { status = "not_ready" });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user