This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
# myai API - Environment Variables Template
|
||||
# Copy this file to .env and fill in your values
|
||||
# DO NOT commit .env to source control!
|
||||
|
||||
# ASP.NET Core Environment (Development, Staging, Production)
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
ASPNETCORE_URLS=http://+:8080
|
||||
|
||||
# Application Environment Name (shown in email subjects to identify which environment sent the email)
|
||||
APP_ENVIRONMENT_NAME=myai.ro-Development
|
||||
|
||||
# Azure Key Vault (Optional - for production)
|
||||
KeyVault__Enabled=false
|
||||
KeyVault__VaultUri=https://your-keyvault-name.vault.azure.net/
|
||||
|
||||
# Note: If Key Vault is enabled, you can store secrets there instead of below
|
||||
# The following settings can be overridden by Key Vault secrets
|
||||
|
||||
# SMTP Configuration
|
||||
Smtp__Host=mail.example.com
|
||||
Smtp__Port=587
|
||||
Smtp__Username=no-reply@example.com
|
||||
Smtp__Password=your-secure-password-here
|
||||
Smtp__UseStartTls=true
|
||||
|
||||
# Google reCAPTCHA
|
||||
Captcha__Provider=Recaptcha
|
||||
Captcha__SecretKey=your-recaptcha-secret-key
|
||||
Captcha__PublicKey=your-recaptcha-public-key
|
||||
Captcha__MinimumScore=0.5
|
||||
Captcha__ExpectedAction=
|
||||
Captcha__ExpectedHostname=
|
||||
|
||||
# Google Services (optional - public keys safe to expose)
|
||||
Google__TagManagerId=GTM-XXXXXXX
|
||||
Google__MapKey=
|
||||
|
||||
# File Storage (relative to solution folder - defaults to "Files" if not set)
|
||||
FileStorage__Path=Files
|
||||
FileStorage__DefaultFileName=
|
||||
FileStorage__ToEmail=admin@yourdomain.com
|
||||
FileStorage__FromEmail=no-reply@yourdomain.com
|
||||
FileStorage__SubjectPrefix=[File Download]
|
||||
|
||||
# Contact Settings
|
||||
Contact__ToEmail=contact@yourdomain.com
|
||||
Contact__FromEmail=no-reply@yourdomain.com
|
||||
Contact__SubjectPrefix=[Contact]
|
||||
|
||||
# Subscribe Settings
|
||||
Subscribe__ToEmail=contact@yourdomain.com
|
||||
Subscribe__SubjectPrefix=[Subscribe]
|
||||
|
||||
# CORS - Allowed Origins (comma separated or multiple variables)
|
||||
Cors__AllowedOrigins__0=https://yourdomain.com
|
||||
Cors__AllowedOrigins__1=https://www.yourdomain.com
|
||||
|
||||
# Logging Configuration
|
||||
Logging__LogLevel__Default=Information
|
||||
Logging__LogLevel__Microsoft=Warning
|
||||
Logging__LogLevel__Microsoft.AspNetCore=Warning
|
||||
Logging__LogLevel__Api=Information
|
||||
|
||||
# Serilog Email Alerts (for Error notifications)
|
||||
Serilog__WriteTo__2__Args__fromEmail=no-reply@yourdomain.com
|
||||
Serilog__WriteTo__2__Args__toEmail=webmaster@yourdomain.com
|
||||
Serilog__WriteTo__2__Args__mailServer=mail.example.com
|
||||
Serilog__WriteTo__2__Args__networkCredential__userName=no-reply@yourdomain.com
|
||||
Serilog__WriteTo__2__Args__networkCredential__password=your-password
|
||||
Serilog__WriteTo__2__Args__port=587
|
||||
Serilog__WriteTo__2__Args__enableSsl=true
|
||||
|
||||
@@ -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" });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src/api
|
||||
|
||||
# Copy the project file and restore first to leverage Docker layer caching
|
||||
COPY api.csproj ./
|
||||
RUN dotnet restore api.csproj
|
||||
|
||||
# Copy only the api project files to avoid bringing other projects into the build context
|
||||
COPY . ./
|
||||
RUN dotnet publish api.csproj -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
ENV ASPNETCORE_URLS=http://0.0.0.0:8080
|
||||
|
||||
COPY --from=build /app/publish .
|
||||
ENTRYPOINT ["dotnet", "api.dll"]
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Api.Models
|
||||
{
|
||||
public sealed class ContactRequest
|
||||
{
|
||||
[Required, StringLength(100)]
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
[Required, EmailAddress, StringLength(200)]
|
||||
public string Email { get; set; } = "";
|
||||
|
||||
[Required, StringLength(200)]
|
||||
public string Subject { get; set; } = "";
|
||||
|
||||
[Required, StringLength(5000)]
|
||||
public string Message { get; set; } = "";
|
||||
|
||||
// Token returned by the captcha widget
|
||||
[Required]
|
||||
public string CaptchaToken { get; set; } = "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Api.Models
|
||||
{
|
||||
public sealed class SubscribeRequest
|
||||
{
|
||||
|
||||
[Required, EmailAddress, StringLength(200)]
|
||||
public string Email { get; set; } = "";
|
||||
|
||||
// Token returned by the captcha widget
|
||||
[Required]
|
||||
public string CaptchaToken { get; set; } = "";
|
||||
}
|
||||
}
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
using Api.Services;
|
||||
using Api.Services.Contracts;
|
||||
using Api.Settings;
|
||||
using Azure.Identity;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Serilog;
|
||||
using System.Reflection;
|
||||
using System.Threading.RateLimiting;
|
||||
|
||||
|
||||
// Load .env file if it exists (for local development)
|
||||
DotNetEnv.Env.Load();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var appVersion =
|
||||
Assembly.GetExecutingAssembly()
|
||||
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
|
||||
.InformationalVersion
|
||||
?? Assembly.GetExecutingAssembly().GetName().Version?.ToString()
|
||||
?? "unknown";
|
||||
|
||||
|
||||
builder.Host.UseSerilog((context, services, configuration) =>
|
||||
{
|
||||
configuration
|
||||
.ReadFrom.Configuration(context.Configuration)
|
||||
.ReadFrom.Services(services)
|
||||
.Enrich.FromLogContext()
|
||||
.Enrich.WithMachineName()
|
||||
.Enrich.WithEnvironmentName()
|
||||
.Enrich.WithProperty("AppVersion", appVersion)
|
||||
.WriteTo.Console(new Serilog.Formatting.Json.JsonFormatter());
|
||||
});
|
||||
|
||||
Log.Information("Starting API version {AppVersion}", appVersion);
|
||||
|
||||
// --------------------
|
||||
// Azure Key Vault Configuration
|
||||
// --------------------
|
||||
var keyVaultUri = builder.Configuration["KeyVault:VaultUri"];
|
||||
var keyVaultEnabled = builder.Configuration.GetValue<bool>("KeyVault:Enabled");
|
||||
|
||||
if (keyVaultEnabled && !string.IsNullOrWhiteSpace(keyVaultUri))
|
||||
{
|
||||
Log.Information("Loading configuration from Azure Key Vault: {VaultUri}", keyVaultUri);
|
||||
|
||||
try
|
||||
{
|
||||
builder.Configuration.AddAzureKeyVault(
|
||||
new Uri(keyVaultUri),
|
||||
new DefaultAzureCredential());
|
||||
|
||||
Log.Information("Azure Key Vault configuration loaded successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning(ex, "Failed to load Azure Key Vault configuration. Continuing with other configuration sources.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Information("Azure Key Vault is disabled or not configured");
|
||||
}
|
||||
|
||||
// Controllers
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// Options
|
||||
builder.Services.Configure<GoogleSettings>(builder.Configuration.GetSection("Google"));
|
||||
builder.Services.Configure<ContactSettings>(builder.Configuration.GetSection("Contact"));
|
||||
builder.Services.Configure<SubscribeSettings>(builder.Configuration.GetSection("Subscribe"));
|
||||
builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("Smtp"));
|
||||
builder.Services.Configure<CaptchaSettings>(builder.Configuration.GetSection("Captcha"));
|
||||
builder.Services.Configure<FileStorageSettings>(builder.Configuration.GetSection("FileStorage"));
|
||||
|
||||
// Services
|
||||
builder.Services.AddHttpClient<ICaptchaVerifier, RecaptchaVerifier>();
|
||||
builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();
|
||||
builder.Services.AddSingleton<Microsoft.AspNetCore.StaticFiles.IContentTypeProvider, Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider>();
|
||||
|
||||
// Swagger
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
// If you're behind Caddy / reverse proxy
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders =
|
||||
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
|
||||
// use the normalized header Caddy sends upstream.
|
||||
options.ForwardedForHeaderName = "X-Real-IP";
|
||||
|
||||
options.KnownIPNetworks.Clear();
|
||||
options.KnownProxies.Clear();
|
||||
|
||||
options.ForwardLimit = 1;
|
||||
});
|
||||
|
||||
// --------------------
|
||||
// CORS (lock it down)
|
||||
// --------------------
|
||||
// Configure allowed origins via config/env var.
|
||||
// Example env var in Docker: Cors__AllowedOrigins__0=https://app.yourdomain.com
|
||||
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("FrontendOnly", policy =>
|
||||
{
|
||||
// If none configured, fail closed: allow nothing.
|
||||
if (allowedOrigins.Length > 0)
|
||||
{
|
||||
policy.WithOrigins(allowedOrigins)
|
||||
.WithMethods("POST", "OPTIONS") // contact form only
|
||||
.WithHeaders("Content-Type") // keep minimal
|
||||
.SetPreflightMaxAge(TimeSpan.FromHours(1));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------
|
||||
// Rate Limiting
|
||||
// --------------------
|
||||
// Two layers:
|
||||
// 1) A global limiter (keeps random traffic sane).
|
||||
// 2) A stricter policy for /api/contact.
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
// Global: per IP, moderate
|
||||
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
|
||||
{
|
||||
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(
|
||||
partitionKey: ip,
|
||||
factory: _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 120, // 120 req
|
||||
Window = TimeSpan.FromMinutes(1), // per minute
|
||||
QueueLimit = 0,
|
||||
AutoReplenishment = true
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
// Policy: contact endpoint, stricter (per IP)
|
||||
options.AddPolicy("contact", httpContext =>
|
||||
{
|
||||
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(
|
||||
partitionKey: ip,
|
||||
factory: _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 5, // 5 submits
|
||||
Window = TimeSpan.FromMinutes(1), // per minute per IP
|
||||
QueueLimit = 0,
|
||||
AutoReplenishment = true
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
|
||||
options.OnRejected = async (context, ct) =>
|
||||
{
|
||||
var logger = context.HttpContext.RequestServices
|
||||
.GetRequiredService<ILogger<Program>>();
|
||||
|
||||
var ip = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
var endpoint = context.HttpContext.Request.Path;
|
||||
|
||||
logger.LogWarning(
|
||||
"Rate limit exceeded for {Endpoint} from IP {IP}",
|
||||
endpoint, ip
|
||||
);
|
||||
|
||||
// Small, bot-unfriendly response
|
||||
context.HttpContext.Response.ContentType = "application/json";
|
||||
await context.HttpContext.Response.WriteAsync(
|
||||
"""{"error":"Too many requests. Try again later."}""",
|
||||
ct
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
var logger = app.Services.GetRequiredService<ILogger<Program>>();
|
||||
logger.LogInformation("API starting up...");
|
||||
logger.LogInformation("Environment: {Environment}", app.Environment.EnvironmentName);
|
||||
|
||||
// Log all environment variables and configuration settings at startup
|
||||
// Can be controlled via appsettings: "Logging:LogEnvironmentOnStartup": true
|
||||
var logEnvironmentOnStartup = app.Configuration.GetValue<bool>("Logging:LogEnvironmentOnStartup", defaultValue: true);
|
||||
if (logEnvironmentOnStartup)
|
||||
{
|
||||
LogEnvironmentSettings(logger, app.Configuration, app.Environment);
|
||||
}
|
||||
|
||||
// Forwarded headers must be early in the pipeline
|
||||
app.UseForwardedHeaders();
|
||||
|
||||
// Add Serilog request logging
|
||||
app.UseSerilogRequestLogging(options =>
|
||||
{
|
||||
options.MessageTemplate =
|
||||
"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";
|
||||
|
||||
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
|
||||
{
|
||||
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
|
||||
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
|
||||
diagnosticContext.Set("RemoteIP", httpContext.Connection.RemoteIpAddress?.ToString());
|
||||
diagnosticContext.Set("UserAgent", httpContext.Request.Headers.UserAgent.ToString());
|
||||
diagnosticContext.Set("XRealIP", httpContext.Request.Headers["X-Real-IP"].ToString());
|
||||
diagnosticContext.Set("XForwardedFor", httpContext.Request.Headers["X-Forwarded-For"].ToString());
|
||||
};
|
||||
});
|
||||
|
||||
// Swagger (typically only in Development)
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(options =>
|
||||
{
|
||||
options.DocumentTitle = "API";
|
||||
options.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
|
||||
options.RoutePrefix = "swagger"; // /swagger
|
||||
});
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseCors("FrontendOnly");
|
||||
|
||||
app.UseRateLimiter();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
logger.LogInformation("API startup complete. Listening for requests...");
|
||||
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "Application terminated unexpectedly");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.Information("Shutting down API...");
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs all environment variables and configuration settings at startup for diagnostics.
|
||||
/// </summary>
|
||||
static void LogEnvironmentSettings(Microsoft.Extensions.Logging.ILogger logger, IConfiguration configuration, IWebHostEnvironment environment)
|
||||
{
|
||||
logger.LogInformation("==================== ENVIRONMENT SETTINGS ====================");
|
||||
|
||||
// Environment Information
|
||||
logger.LogInformation("Application Name: {ApplicationName}", environment.ApplicationName);
|
||||
logger.LogInformation("Environment Name: {EnvironmentName}", environment.EnvironmentName);
|
||||
logger.LogInformation("Content Root Path: {ContentRootPath}", environment.ContentRootPath);
|
||||
logger.LogInformation("Web Root Path: {WebRootPath}", environment.WebRootPath);
|
||||
|
||||
// Environment Variables
|
||||
logger.LogInformation("-------------- Environment Variables --------------");
|
||||
var envVars = Environment.GetEnvironmentVariables();
|
||||
var sortedEnvVars = new SortedDictionary<string, string?>();
|
||||
|
||||
foreach (System.Collections.DictionaryEntry entry in envVars)
|
||||
{
|
||||
var key = entry.Key?.ToString() ?? string.Empty;
|
||||
var value = entry.Value?.ToString() ?? string.Empty;
|
||||
|
||||
// Mask sensitive values (passwords, secrets, tokens, keys) but show last 4 characters
|
||||
if (IsSensitiveKey(key))
|
||||
{
|
||||
value = MaskValueWithLastChars(value);
|
||||
}
|
||||
|
||||
sortedEnvVars[key] = value;
|
||||
}
|
||||
|
||||
foreach (var kvp in sortedEnvVars)
|
||||
{
|
||||
logger.LogInformation(" {Key} = {Value}", kvp.Key, kvp.Value);
|
||||
}
|
||||
|
||||
// Configuration Settings
|
||||
logger.LogInformation("-------------- Configuration Settings --------------");
|
||||
LogConfigurationRecursive(logger, configuration.GetChildren(), "");
|
||||
|
||||
logger.LogInformation("===========================================================");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively logs configuration settings with hierarchy.
|
||||
/// </summary>
|
||||
static void LogConfigurationRecursive(Microsoft.Extensions.Logging.ILogger logger, IEnumerable<IConfigurationSection> sections, string prefix)
|
||||
{
|
||||
foreach (var section in sections)
|
||||
{
|
||||
var key = string.IsNullOrEmpty(prefix) ? section.Key : $"{prefix}:{section.Key}";
|
||||
|
||||
if (section.Value != null)
|
||||
{
|
||||
var value = section.Value;
|
||||
|
||||
// Mask sensitive configuration values but show last 4 characters
|
||||
if (IsSensitiveKey(key))
|
||||
{
|
||||
value = MaskValueWithLastChars(value);
|
||||
}
|
||||
|
||||
logger.LogInformation(" {Key} = {Value}", key, value);
|
||||
}
|
||||
|
||||
// Recurse into child sections
|
||||
if (section.GetChildren().Any())
|
||||
{
|
||||
LogConfigurationRecursive(logger, section.GetChildren(), key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a configuration key contains sensitive information.
|
||||
/// </summary>
|
||||
static bool IsSensitiveKey(string key)
|
||||
{
|
||||
return key.Contains("Password", StringComparison.OrdinalIgnoreCase) ||
|
||||
key.Contains("Secret", StringComparison.OrdinalIgnoreCase) ||
|
||||
key.Contains("Token", StringComparison.OrdinalIgnoreCase) ||
|
||||
key.Contains("Key", StringComparison.OrdinalIgnoreCase) ||
|
||||
key.Contains("ConnectionString", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Masks a sensitive value but shows the last 4 characters for verification.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to mask.</param>
|
||||
/// <returns>Masked value showing last 4 characters (e.g., "***MASKED***...abcd")</returns>
|
||||
static string MaskValueWithLastChars(string value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return "***NOT SET***";
|
||||
}
|
||||
|
||||
// If value is too short, just mask it completely
|
||||
if (value.Length <= 4)
|
||||
{
|
||||
return "***MASKED***";
|
||||
}
|
||||
|
||||
// Show last 4 characters
|
||||
var lastChars = value.Substring(value.Length - 4);
|
||||
return $"***MASKED***...{lastChars}";
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"profiles": {
|
||||
"api": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "https://localhost:55119;http://localhost:55121"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_HTTPS_PORTS": "8081",
|
||||
"ASPNETCORE_HTTP_PORTS": "8080"
|
||||
},
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:62186/",
|
||||
"sslPort": 44392
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Api.Services.Contracts
|
||||
{
|
||||
public sealed record CaptchaVerdict(bool Success, string? Error, double? Score);
|
||||
|
||||
public interface ICaptchaVerifier
|
||||
{
|
||||
Task<CaptchaVerdict> VerifyAsync(string token, string? userIp, CancellationToken ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using Api.Models;
|
||||
|
||||
namespace Api.Services.Contracts
|
||||
{
|
||||
public interface IEmailSender
|
||||
{
|
||||
Task SendContactAsync(ContactRequest req, CancellationToken ct);
|
||||
Task SendSubscribeAsync(SubscribeRequest req, CancellationToken ct);
|
||||
Task SendFileDownloadNotificationAsync(string fileName, string? userIp, CancellationToken ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Api.Services.Contracts;
|
||||
using Api.Settings;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Api.Services
|
||||
{
|
||||
public sealed class RecaptchaVerifier : ICaptchaVerifier
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly CaptchaSettings _opt;
|
||||
private readonly ILogger<RecaptchaVerifier> _log;
|
||||
|
||||
public RecaptchaVerifier(HttpClient http, IOptions<CaptchaSettings> options, ILogger<RecaptchaVerifier> log)
|
||||
{
|
||||
_http = http;
|
||||
_opt = options.Value;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public async Task<CaptchaVerdict> VerifyAsync(string token, string? userIp, CancellationToken ct)
|
||||
{
|
||||
_log.LogDebug("Verifying captcha token for IP {Ip}", userIp ?? "unknown");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(_opt.SecretKey))
|
||||
{
|
||||
_log.LogWarning("Captcha verification attempted but SecretKey is not configured");
|
||||
return new CaptchaVerdict(false, "Captcha not configured", null);
|
||||
}
|
||||
|
||||
var form = new Dictionary<string, string>
|
||||
{
|
||||
["secret"] = _opt.SecretKey,
|
||||
["response"] = token
|
||||
};
|
||||
if (!string.IsNullOrWhiteSpace(userIp))
|
||||
form["remoteip"] = userIp;
|
||||
|
||||
using var resp = await _http.PostAsync(
|
||||
"https://www.google.com/recaptcha/api/siteverify",
|
||||
new FormUrlEncodedContent(form),
|
||||
ct
|
||||
);
|
||||
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
{
|
||||
_log.LogWarning("Captcha HTTP request failed with status {StatusCode} for IP {Ip}",
|
||||
(int)resp.StatusCode, userIp ?? "unknown");
|
||||
return new CaptchaVerdict(false, $"Captcha HTTP {(int)resp.StatusCode}", null);
|
||||
}
|
||||
|
||||
var data = await resp.Content.ReadFromJsonAsync<RecaptchaResponse>(cancellationToken: ct);
|
||||
if (data is null)
|
||||
{
|
||||
_log.LogError("Failed to parse captcha response for IP {Ip}", userIp ?? "unknown");
|
||||
return new CaptchaVerdict(false, "Captcha parse error", null);
|
||||
}
|
||||
|
||||
if (!data.success)
|
||||
{
|
||||
_log.LogWarning("Captcha verification failed for IP {Ip}. Score={Score}",
|
||||
userIp ?? "unknown", data.score);
|
||||
return new CaptchaVerdict(false, "Captcha failed", data.score);
|
||||
}
|
||||
|
||||
// v3 score check (score is typically null for v2)
|
||||
if (data.score is double score && score < _opt.MinimumScore)
|
||||
{
|
||||
_log.LogWarning("Captcha score {Score} below minimum {MinScore} for IP {Ip}",
|
||||
score, _opt.MinimumScore, userIp ?? "unknown");
|
||||
return new CaptchaVerdict(false, "Captcha score too low", score);
|
||||
}
|
||||
|
||||
// Optional strictness (usually v3): action/hostname checks
|
||||
if (!string.IsNullOrWhiteSpace(_opt.ExpectedAction) &&
|
||||
!string.Equals(_opt.ExpectedAction, data.action, StringComparison.Ordinal))
|
||||
{
|
||||
_log.LogWarning("Captcha action mismatch. Expected={Expected}, Actual={Actual}, IP={Ip}",
|
||||
_opt.ExpectedAction, data.action, userIp ?? "unknown");
|
||||
return new CaptchaVerdict(false, "Captcha action mismatch", data.score);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_opt.ExpectedHostname) &&
|
||||
!string.Equals(_opt.ExpectedHostname, data.hostname, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_log.LogWarning("Captcha hostname mismatch. Expected={Expected}, Actual={Actual}, IP={Ip}",
|
||||
_opt.ExpectedHostname, data.hostname, userIp ?? "unknown");
|
||||
return new CaptchaVerdict(false, "Captcha hostname mismatch", data.score);
|
||||
}
|
||||
|
||||
_log.LogInformation("Captcha verified successfully for IP {Ip}. Score={Score}",
|
||||
userIp ?? "unknown", data.score);
|
||||
return new CaptchaVerdict(true, null, data.score);
|
||||
}
|
||||
|
||||
private sealed class RecaptchaResponse
|
||||
{
|
||||
public bool success { get; set; }
|
||||
public double? score { get; set; } // v3
|
||||
public string? action { get; set; } // v3
|
||||
public string? hostname { get; set; }
|
||||
public DateTimeOffset? challenge_ts { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using Api.Services.Contracts;
|
||||
using Api.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using MimeKit;
|
||||
using Api.Settings;
|
||||
|
||||
namespace Api.Services
|
||||
{
|
||||
public sealed class SmtpEmailSender : IEmailSender
|
||||
{
|
||||
private readonly SmtpSettings _smtp;
|
||||
private readonly ContactSettings _contact;
|
||||
private readonly SubscribeSettings _subscribe;
|
||||
private readonly FileStorageSettings _fileStorage;
|
||||
private readonly ILogger<SmtpEmailSender> _log;
|
||||
private readonly string _environmentName;
|
||||
|
||||
public SmtpEmailSender(IOptions<SmtpSettings> smtp,
|
||||
IOptions<ContactSettings> contact,
|
||||
IOptions<SubscribeSettings> subscribe,
|
||||
IOptions<FileStorageSettings> fileStorage,
|
||||
ILogger<SmtpEmailSender> log)
|
||||
{
|
||||
_smtp = smtp.Value;
|
||||
_contact = contact.Value;
|
||||
_subscribe = subscribe.Value;
|
||||
_fileStorage = fileStorage.Value;
|
||||
_log = log;
|
||||
// Use APP_ENVIRONMENT_NAME from environment variable (set in docker-compose) with fallback to "Development"
|
||||
_environmentName = Environment.GetEnvironmentVariable("APP_ENVIRONMENT_NAME") ?? "Development";
|
||||
}
|
||||
|
||||
public async Task SendContactAsync(ContactRequest req, CancellationToken ct)
|
||||
{
|
||||
// Throw error if ToEmail is not configured, since contact requests are important to process.
|
||||
if (string.IsNullOrWhiteSpace(_contact.ToEmail))
|
||||
{
|
||||
_log.LogDebug("Contact email skipped - ToEmail not configured");
|
||||
throw new InvalidOperationException("Contact email recipient is not configured.");
|
||||
}
|
||||
|
||||
_log.LogInformation("Preparing contact email from {SenderEmail} to {RecipientEmail}",
|
||||
req.Email, _contact.ToEmail);
|
||||
|
||||
var msg = new MimeMessage();
|
||||
msg.From.Add(MailboxAddress.Parse(_smtp.Username));
|
||||
msg.To.Add(MailboxAddress.Parse(_contact.ToEmail));
|
||||
msg.ReplyTo.Add(MailboxAddress.Parse(req.Email));
|
||||
msg.Subject = $"{_contact.SubjectPrefix} [{_environmentName}] {req.Subject}".Trim();
|
||||
|
||||
var body =
|
||||
$@"New contact form submission:
|
||||
|
||||
Name: {req.Name}
|
||||
Email: {req.Email}
|
||||
Subject: {req.Subject}
|
||||
|
||||
Message:
|
||||
{req.Message}
|
||||
";
|
||||
|
||||
msg.Body = new TextPart("plain") { Text = body };
|
||||
|
||||
await SendEmailAsync(msg, "contact email", ct);
|
||||
|
||||
_log.LogInformation("Contact email sent successfully from {SenderEmail}", req.Email);
|
||||
}
|
||||
|
||||
public async Task SendSubscribeAsync(SubscribeRequest req, CancellationToken ct)
|
||||
{
|
||||
// Throw error if ToEmail is not configured, since subscription requests are important to process.
|
||||
if (string.IsNullOrWhiteSpace(_subscribe.ToEmail))
|
||||
{
|
||||
_log.LogDebug("Subscription email skipped - ToEmail not configured");
|
||||
throw new InvalidOperationException("Subscription email recipient is not configured.");
|
||||
}
|
||||
|
||||
_log.LogInformation("Processing subscription request for {Email}", req.Email);
|
||||
|
||||
var msg = new MimeMessage();
|
||||
msg.From.Add(MailboxAddress.Parse(_smtp.Username));
|
||||
msg.To.Add(MailboxAddress.Parse(_subscribe.ToEmail));
|
||||
msg.ReplyTo.Add(MailboxAddress.Parse(req.Email));
|
||||
msg.Subject = $"{_subscribe.SubjectPrefix} [{_environmentName}]".Trim();
|
||||
|
||||
var body =
|
||||
$@"New subscription request:
|
||||
|
||||
Email: {req.Email}
|
||||
";
|
||||
|
||||
msg.Body = new TextPart("plain") { Text = body };
|
||||
|
||||
await SendEmailAsync(msg, "subscription email", ct);
|
||||
|
||||
_log.LogInformation("Subscription email sent successfully for {Email}", req.Email);
|
||||
}
|
||||
|
||||
public async Task SendFileDownloadNotificationAsync(string fileName, string? userIp, CancellationToken ct)
|
||||
{
|
||||
// Skip sending if ToEmail is not configured
|
||||
if (string.IsNullOrWhiteSpace(_fileStorage.ToEmail))
|
||||
{
|
||||
_log.LogDebug("File download notification skipped - ToEmail not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
_log.LogInformation("Preparing file download notification for {FileName}", fileName);
|
||||
|
||||
var msg = new MimeMessage();
|
||||
msg.From.Add(MailboxAddress.Parse(_smtp.Username));
|
||||
msg.To.Add(MailboxAddress.Parse(_fileStorage.ToEmail));
|
||||
msg.Subject = $"{_fileStorage.SubjectPrefix} [{_environmentName}] {fileName}".Trim();
|
||||
|
||||
var body =
|
||||
$@"File download notification:
|
||||
|
||||
File: {fileName}
|
||||
Downloaded at: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC
|
||||
IP Address: {userIp ?? "Unknown"}
|
||||
";
|
||||
|
||||
msg.Body = new TextPart("plain") { Text = body };
|
||||
|
||||
await SendEmailAsync(msg, "file download notification email", ct);
|
||||
|
||||
_log.LogInformation("File download notification sent successfully for {FileName}", fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the SMTP server and authenticates if credentials are configured.
|
||||
/// </summary>
|
||||
private async Task ConnectAndAuthenticateAsync(SmtpClient client, CancellationToken ct)
|
||||
{
|
||||
// If you're in enterprise environments, you may need to tweak certificate validation.
|
||||
// Don't disable it casually.
|
||||
var tls = _smtp.UseStartTls ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
|
||||
|
||||
_log.LogDebug("Connecting to SMTP server {Host}:{Port} with security={Security}",
|
||||
_smtp.Host, _smtp.Port, tls);
|
||||
|
||||
await client.ConnectAsync(_smtp.Host, _smtp.Port, tls, ct);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_smtp.Username))
|
||||
{
|
||||
_log.LogDebug("Authenticating with SMTP server as {Username}", _smtp.Username);
|
||||
await client.AuthenticateAsync(_smtp.Username, _smtp.Password, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends an email message using SMTP.
|
||||
/// </summary>
|
||||
/// <param name="message">The email message to send.</param>
|
||||
/// <param name="messageType">Description of the message type for logging purposes.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
private async Task SendEmailAsync(MimeMessage message, string messageType, CancellationToken ct)
|
||||
{
|
||||
using var client = new SmtpClient();
|
||||
|
||||
await ConnectAndAuthenticateAsync(client, ct);
|
||||
|
||||
_log.LogDebug("Sending {MessageType} message", messageType);
|
||||
await client.SendAsync(message, ct);
|
||||
await client.DisconnectAsync(true, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public sealed class CaptchaSettings
|
||||
{
|
||||
// "Recaptcha" for now (easy to extend later)
|
||||
public string Provider { get; set; } = "Recaptcha";
|
||||
|
||||
public string SecretKey { get; set; } = "";
|
||||
public string PublicKey { get; set; } = "";
|
||||
// Only relevant for reCAPTCHA v3 (score-based)
|
||||
public double MinimumScore { get; set; } = 0.5;
|
||||
|
||||
// Optional but recommended for v3: enforce expected action and/or hostname
|
||||
public string? ExpectedAction { get; set; }
|
||||
public string? ExpectedHostname { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public sealed class ContactSettings
|
||||
{
|
||||
public string ToEmail { get; set; } = "";
|
||||
public string SubjectPrefix { get; set; } = "[Contact]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public sealed class FileStorageSettings
|
||||
{
|
||||
public string Path { get; set; } = "Files";
|
||||
public string DefaultFileName { get; set; } = "";
|
||||
public string ToEmail { get; set; } = "";
|
||||
public string SubjectPrefix { get; set; } = "[File Download]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public sealed class GoogleSettings
|
||||
{
|
||||
public string TagManagerId { get; set; } = "";
|
||||
public string MapKey { get; set; } = "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public sealed class KeyVaultSettings
|
||||
{
|
||||
public string VaultUri { get; set; } = "";
|
||||
public bool Enabled { get; set; } = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public class SmtpSettings
|
||||
{
|
||||
public string Host { get; set; } = "";
|
||||
public int Port { get; set; } = 587;
|
||||
public string Username { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
public bool UseStartTls { get; set; } = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Api.Settings
|
||||
{
|
||||
public sealed class SubscribeSettings
|
||||
{
|
||||
public string ToEmail { get; set; } = "";
|
||||
public string SubjectPrefix { get; set; } = "[Subscribe]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.0.0-build.$([System.DateTime]::UtcNow.ToString("yyyyMMddHHmmss"))</Version>
|
||||
<InformationalVersion>$(Version)</InformationalVersion>
|
||||
<!-- Good defaults for reverse-proxy scenarios -->
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<DisableStaticWebAssets>true</DisableStaticWebAssets>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.5.1" />
|
||||
<PackageReference Include="Azure.Identity" Version="1.21.0" />
|
||||
<PackageReference Include="DotNetEnv" Version="3.2.0" />
|
||||
<PackageReference Include="MailKit" Version="4.16.0" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Email" Version="4.2.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="logs\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
"Microsoft.AspNetCore": "Information",
|
||||
"Microsoft.AspNetCore.Hosting": "Information",
|
||||
"Microsoft.AspNetCore.Routing": "Warning",
|
||||
"System.Net.Http.HttpClient": "Warning",
|
||||
"Api": "Debug"
|
||||
}
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "Console",
|
||||
"Args": {
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "logs/dev-.log",
|
||||
"rollingInterval": "Day",
|
||||
"retainedFileCountLimit": 7,
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Information",
|
||||
"Microsoft.AspNetCore.Hosting": "Information",
|
||||
"Microsoft.AspNetCore.Routing": "Warning",
|
||||
"System.Net.Http.HttpClient": "Warning",
|
||||
"Api": "Debug"
|
||||
},
|
||||
"LogEnvironmentOnStartup": true
|
||||
},
|
||||
"KeyVault": {
|
||||
"VaultUri": "",
|
||||
"Enabled": false
|
||||
},
|
||||
"Google": {
|
||||
"TagManagerId": "",
|
||||
"MapKey": ""
|
||||
},
|
||||
"Contact": {
|
||||
"ToEmail": "",
|
||||
"FromEmail": "",
|
||||
"SubjectPrefix": ""
|
||||
},
|
||||
"Subscribe": {
|
||||
"ToEmail": "",
|
||||
"SubjectPrefix": ""
|
||||
},
|
||||
"Smtp": {
|
||||
"Host": "mail.example.com",
|
||||
"Port": 587,
|
||||
"Username": "",
|
||||
"Password": "",
|
||||
"UseStartTls": false
|
||||
},
|
||||
"Captcha": {
|
||||
"Provider": "Recaptcha",
|
||||
"SecretKey": "",
|
||||
"PublicKey": "",
|
||||
"MinimumScore": 0.5
|
||||
},
|
||||
"FileStorage": {
|
||||
"Path": "Files",
|
||||
"DefaultFileName": "",
|
||||
"ToEmail": "",
|
||||
"FromEmail": "",
|
||||
"SubjectPrefix": "[File Download]"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Email" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.AspNetCore.Hosting": "Information",
|
||||
"Microsoft.AspNetCore.Routing": "Warning",
|
||||
"System.Net.Http.HttpClient": "Warning",
|
||||
"Api": "Information"
|
||||
}
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "Console",
|
||||
"Args": {
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "logs/api-.log",
|
||||
"rollingInterval": "Day",
|
||||
"retainedFileCountLimit": 30,
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"Name": "Email",
|
||||
"Args": {
|
||||
"restrictedToMinimumLevel": "Error",
|
||||
"fromEmail": "",
|
||||
"toEmail": "",
|
||||
"mailServer": "",
|
||||
"networkCredential": {
|
||||
"userName": "",
|
||||
"password": ""
|
||||
},
|
||||
"port": 587,
|
||||
"enableSsl": true,
|
||||
"emailSubject": "[mihes.ro API] Error Alert",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}",
|
||||
"batchPostingLimit": 10,
|
||||
"period": "0.00:05:00"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithEnvironmentName" ]
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.AspNetCore.Hosting": "Information",
|
||||
"Microsoft.AspNetCore.Routing": "Warning",
|
||||
"System.Net.Http.HttpClient": "Warning",
|
||||
"Api": "Information"
|
||||
},
|
||||
"LogEnvironmentOnStartup": true
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
|
||||
"KeyVault": {
|
||||
"VaultUri": "",
|
||||
"Enabled": false
|
||||
},
|
||||
"Google": {
|
||||
"TagManagerId": "",
|
||||
"MapKey": ""
|
||||
},
|
||||
"Contact": {
|
||||
"ToEmail": "",
|
||||
"FromEmail": "",
|
||||
"SubjectPrefix": ""
|
||||
},
|
||||
"Subscribe": {
|
||||
"ToEmail": "",
|
||||
"SubjectPrefix": ""
|
||||
},
|
||||
"Smtp": {
|
||||
"Host": "mail.example.com",
|
||||
"Port": 587,
|
||||
"Username": "",
|
||||
"Password": "",
|
||||
"UseStartTls": false
|
||||
},
|
||||
"Captcha": {
|
||||
"Provider": "Recaptcha",
|
||||
"SecretKey": "",
|
||||
"PublicKey": "",
|
||||
"MinimumScore": 0.5
|
||||
},
|
||||
"FileStorage": {
|
||||
"Path": "Files",
|
||||
"DefaultFileName": "",
|
||||
"ToEmail": "",
|
||||
"FromEmail": "",
|
||||
"SubjectPrefix": "[File Download]"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user