This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Models.Settings;
|
||||
using Swashbuckle.AspNetCore.Annotations;
|
||||
using Models.Requests;
|
||||
using Shared.Models.Responses;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Endpoints that expose captcha configuration and verification.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public sealed class CaptchaController : ControllerBase
|
||||
{
|
||||
private readonly CaptchaSettings _captchaSettings;
|
||||
private readonly ICaptchaVerifier _captcha;
|
||||
private readonly ILogger<CaptchaController> _log;
|
||||
|
||||
public CaptchaController(IOptions<CaptchaSettings> options, ICaptchaVerifier captcha, ILogger<CaptchaController> log)
|
||||
{
|
||||
_captchaSettings = options.Value;
|
||||
_captcha = captcha;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the public reCAPTCHA site key used by the client to render the widget.
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[SwaggerOperation(Summary = "Get captcha site key")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public IActionResult GetSiteKey()
|
||||
{
|
||||
return Ok(_captchaSettings.PublicKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify a captcha token and return the verification verdict.
|
||||
/// </summary>
|
||||
[HttpPost("verify")]
|
||||
[SwaggerOperation(Summary = "Verify captcha token")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
|
||||
[SwaggerResponse(StatusCodes.Status400BadRequest, "Captcha verification failed or token missing", typeof(ErrorResponse))]
|
||||
public async Task<IActionResult> Verify([FromBody] CaptchaVerifyRequest req, CancellationToken ct)
|
||||
{
|
||||
if (req is null || string.IsNullOrWhiteSpace(req.Token))
|
||||
{
|
||||
return BadRequest(new ErrorResponse { Error = "Missing token", Code = "captcha_token_missing" });
|
||||
}
|
||||
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var verdict = await _captcha.VerifyAsync(req.Token, userIp, req.ExpectedAction, ct);
|
||||
if (!verdict.Success)
|
||||
{
|
||||
_log.LogWarning("Captcha failed. ip={Ip} score={Score} err={Err}", userIp, verdict.Score, verdict.Error);
|
||||
return BadRequest(new ErrorResponse
|
||||
{
|
||||
Error = "Captcha verification failed.",
|
||||
Code = "captcha_verification_failed",
|
||||
Score = verdict.Score
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(verdict);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using Api.Services.Contracts.Models;
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Models.Settings;
|
||||
using Models.Requests;
|
||||
using Swashbuckle.AspNetCore.Annotations;
|
||||
using Shared.Models.Responses;
|
||||
|
||||
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 ICaptchaVerifier _captcha;
|
||||
private readonly IEmailSender _email;
|
||||
private readonly ILogger<ContactController> _log;
|
||||
|
||||
public ContactController(ICaptchaVerifier captcha, IEmailSender email, ILogger<ContactController> log)
|
||||
{
|
||||
_captcha = captcha;
|
||||
_email = email;
|
||||
_log = log;
|
||||
}
|
||||
/// <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")]
|
||||
[SwaggerOperation(Summary = "Send contact message", Description = "Validates captcha and sends a contact message using the configured email sender.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Contact message sent")]
|
||||
[SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid request or captcha verification failed")]
|
||||
[SwaggerResponse(StatusCodes.Status500InternalServerError, "Contact message could not be sent due to server error")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> Send([FromBody] ContactRequest req, CancellationToken ct)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return ValidationProblem(ModelState);
|
||||
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var verdict = await _captcha.VerifyAsync(req.CaptchaToken, userIp, "contact", ct);
|
||||
if (!verdict.Success)
|
||||
{
|
||||
return BadRequest(new ErrorResponse { Error = "Captcha verification failed.", Code = "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}", userIp, req.Email);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse { Error = "Could not send message.", Code = "contact_send_failed" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <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")]
|
||||
[SwaggerOperation(Summary = "Subscribe email", Description = "Validates captcha and subscribes an email address to the mailing list.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Subscription succeeded")]
|
||||
[SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid request or captcha verification failed")]
|
||||
[SwaggerResponse(StatusCodes.Status500InternalServerError, "Subscription failed due to server error")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> Subscribe([FromBody] SubscribeRequest req, CancellationToken ct)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return ValidationProblem(ModelState);
|
||||
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var verdict = await _captcha.VerifyAsync(req.CaptchaToken, userIp, "subscribe", ct);
|
||||
if (!verdict.Success)
|
||||
{
|
||||
return BadRequest(new ErrorResponse { Error = "Captcha verification failed.", Code = "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}", userIp, req.Email);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse { Error = "Failed.", Code = "subscription_failed" });
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
using Api.Clients.Api.Contracts;
|
||||
using Models.Requests;
|
||||
using Models.Settings;
|
||||
using Api.Services.Contracts;
|
||||
using Api.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Swashbuckle.AspNetCore.Annotations;
|
||||
using Shared.Models.Responses;
|
||||
|
||||
namespace Api.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Proxy endpoints for the CV matcher API. These endpoints forward requests to the internal cv-matcher-api.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/cv-matcher")]
|
||||
[EnableRateLimiting("cvMatcher")]
|
||||
public sealed class CvMatcherController : ControllerBase
|
||||
{
|
||||
private readonly ICvMatcherApi _cvApi;
|
||||
private readonly ICaptchaVerifier _captcha;
|
||||
private readonly FileStorageSettings _fileStorageSettings;
|
||||
private readonly IEmailSender _emailSender;
|
||||
private readonly ILogger<CvMatcherController> _logger;
|
||||
|
||||
public CvMatcherController(
|
||||
ICvMatcherApi cvApi,
|
||||
ICaptchaVerifier captcha,
|
||||
IOptions<FileStorageSettings> fileStorageSettings,
|
||||
IEmailSender emailSender,
|
||||
ILogger<CvMatcherController> logger)
|
||||
{
|
||||
_cvApi = cvApi;
|
||||
_captcha = captcha;
|
||||
_fileStorageSettings = fileStorageSettings.Value;
|
||||
_emailSender = emailSender;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Upload a CV PDF to the cv-matcher-api.
|
||||
/// </summary>
|
||||
/// <param name="request">The uploaded CV request.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
[HttpPost("upload")]
|
||||
[RequestSizeLimit(8 * 1024 * 1024)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), 499)]
|
||||
[SwaggerOperation(Summary = "Upload CV", Description = "Proxy upload of a CV PDF to the internal cv-matcher-api.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Upload succeeded")]
|
||||
[SwaggerResponse(StatusCodes.Status400BadRequest, "Missing or invalid input")]
|
||||
[SwaggerResponse(StatusCodes.Status502BadGateway, "Upstream cv-matcher-api error")]
|
||||
public async Task<IActionResult> UploadCv(
|
||||
[FromForm] UploadCvRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (request.File is null)
|
||||
{
|
||||
return BadRequest(new ErrorResponse { Error = "Missing CV PDF.", Code = "cv_file_missing" });
|
||||
}
|
||||
|
||||
var cv = request.File;
|
||||
var gdprConsent = request.GdprConsent;
|
||||
|
||||
try
|
||||
{
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var verdict = await _captcha.VerifyAsync(request.CaptchaToken ?? string.Empty, userIp, "cv_upload", ct);
|
||||
if (!verdict.Success)
|
||||
{
|
||||
_logger.LogWarning("Captcha verification failed for CV upload. IP={IP}", userIp);
|
||||
return BadRequest(new ErrorResponse { Error = "Captcha verification failed.", Code = "captcha_verification_failed" });
|
||||
}
|
||||
|
||||
if (!gdprConsent) throw new InvalidOperationException("GDPR consent is required.");
|
||||
|
||||
_logger.LogInformation("Proxying CV upload to cv-matcher-api. FileName={FileName}, Size={SizeBytes}, GdprConsent={GdprConsent}",
|
||||
cv.FileName, cv.Length, gdprConsent);
|
||||
|
||||
var stream = cv.OpenReadStream();
|
||||
var part = new Refit.StreamPart(stream, cv.FileName, "application/pdf");
|
||||
var res = await _cvApi.Upload(part, ct);
|
||||
|
||||
await CacheUploadedCvAsync(cv, res.DocumentId, ct);
|
||||
return Ok(res);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning("CV upload proxy request was cancelled by the client.");
|
||||
return StatusCode(499, new ErrorResponse { Error = "Request cancelled.", Code = "request_cancelled" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "CV upload proxy request failed.");
|
||||
return StatusCode(StatusCodes.Status502BadGateway, new ErrorResponse { Error = "CV matcher API request failed.", Code = "upstream_request_failed" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Proxy a job matching request to the cv-matcher-api.
|
||||
/// </summary>
|
||||
/// <param name="request">Job match request payload containing CV document id or job description/url.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
[HttpPost("match-job")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), 499)]
|
||||
[SwaggerOperation(Summary = "Match job", Description = "Proxy job matching request to the internal cv-matcher-api.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Match succeeded")]
|
||||
[SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid request")]
|
||||
[SwaggerResponse(StatusCodes.Status502BadGateway, "Upstream cv-matcher-api error")]
|
||||
public async Task<IActionResult> MatchJob([FromBody] JobMatchRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var userIp = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var verdict = await _captcha.VerifyAsync(request.CaptchaToken ?? string.Empty, userIp, "match_job", ct);
|
||||
if (!verdict.Success)
|
||||
{
|
||||
_logger.LogWarning("Captcha verification failed for job match. IP={IP}", userIp);
|
||||
return BadRequest(new ErrorResponse { Error = "Captcha verification failed.", Code = "captcha_verification_failed" });
|
||||
}
|
||||
|
||||
_logger.LogInformation("Proxying job match request to cv-matcher-api. CvDocumentId={CvDocumentId}, HasJobUrl={HasJobUrl}, HasJobDescription={HasJobDescription}",
|
||||
request.CvDocumentId,
|
||||
!string.IsNullOrWhiteSpace(request.JobUrl),
|
||||
!string.IsNullOrWhiteSpace(request.JobDescription));
|
||||
var res = await _cvApi.MatchJob(request, ct);
|
||||
var attachmentPath = TryGetCachedCvPath(request.CvDocumentId);
|
||||
var jobLabel = !string.IsNullOrWhiteSpace(request.JobUrl)
|
||||
? request.JobUrl
|
||||
: "Manual job description";
|
||||
|
||||
await _emailSender.SendMatchAsync(
|
||||
request.Email,
|
||||
SmtpEmailSender.BuildMatchEmailSubject(res.Score, jobLabel),
|
||||
SmtpEmailSender.BuildMatchEmailBody(request.CvDocumentId ?? "N/A", res, jobLabel),
|
||||
attachmentPath,
|
||||
ct);
|
||||
|
||||
return Ok(res);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning("Job match proxy request was cancelled by the client.");
|
||||
return StatusCode(499, new ErrorResponse { Error = "Request cancelled.", Code = "request_cancelled" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Job match proxy request failed.");
|
||||
return StatusCode(StatusCodes.Status502BadGateway, new ErrorResponse { Error = "CV matcher API request failed.", Code = "upstream_request_failed" });
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CacheUploadedCvAsync(IFormFile file, string documentId, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var storagePath = GetFileStoragePath();
|
||||
Directory.CreateDirectory(storagePath);
|
||||
var targetPath = BuildCvPath(documentId);
|
||||
await using var fileStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, useAsync: true);
|
||||
await file.CopyToAsync(fileStream, ct);
|
||||
_logger.LogInformation("Cached uploaded CV for email attachment. DocumentId={DocumentId}", documentId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Could not cache uploaded CV for attachment. DocumentId={DocumentId}", documentId);
|
||||
}
|
||||
}
|
||||
|
||||
private string? TryGetCachedCvPath(string? cvDocumentId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(cvDocumentId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var path = BuildCvPath(cvDocumentId);
|
||||
return System.IO.File.Exists(path) ? path : null;
|
||||
}
|
||||
|
||||
private string BuildCvPath(string documentId)
|
||||
{
|
||||
var safeId = string.Concat(documentId.Where(char.IsLetterOrDigit));
|
||||
if (string.IsNullOrWhiteSpace(safeId))
|
||||
{
|
||||
safeId = "cv";
|
||||
}
|
||||
|
||||
return Path.Combine(GetFileStoragePath(), $"{safeId}.pdf");
|
||||
}
|
||||
|
||||
private string GetFileStoragePath()
|
||||
{
|
||||
var fileStoragePath = _fileStorageSettings.Path;
|
||||
if (!Path.IsPathRooted(fileStoragePath))
|
||||
{
|
||||
var solutionRoot = Directory.GetCurrentDirectory();
|
||||
if (solutionRoot.EndsWith("api", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
solutionRoot = Directory.GetParent(solutionRoot)?.FullName ?? solutionRoot;
|
||||
}
|
||||
fileStoragePath = Path.Combine(solutionRoot, fileStoragePath);
|
||||
}
|
||||
|
||||
return fileStoragePath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
using Models.Settings;
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using Swashbuckle.AspNetCore.Annotations;
|
||||
using Shared.Models.Responses;
|
||||
|
||||
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?}")]
|
||||
[SwaggerOperation(Summary = "Download file", Description = "Downloads a file with support for full and ranged (resumable) transfers.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Full file content returned")]
|
||||
[SwaggerResponse(StatusCodes.Status206PartialContent, "Partial file content returned for a range request")]
|
||||
[SwaggerResponse(StatusCodes.Status400BadRequest, "No file name provided and no default configured")]
|
||||
[SwaggerResponse(StatusCodes.Status404NotFound, "Requested file was not found")]
|
||||
[SwaggerResponse(StatusCodes.Status416RangeNotSatisfiable, "Requested byte range is invalid")]
|
||||
[SwaggerResponse(StatusCodes.Status500InternalServerError, "Unexpected server error while downloading")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status206PartialContent)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status416RangeNotSatisfiable)]
|
||||
[ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)]
|
||||
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 ErrorResponse { Error = "File name is required", Code = "file_name_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 ErrorResponse { Error = "File not found", Code = "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 ErrorResponse { Error = "An error occurred while downloading the file", Code = "download_failed" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <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,57 @@
|
||||
using Models.Settings;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Swashbuckle.AspNetCore.Annotations;
|
||||
|
||||
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")]
|
||||
[SwaggerOperation(Summary = "Get Google Tag Manager ID", Description = "Returns the Google Tag Manager ID configured for frontend analytics.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Tag Manager ID returned")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
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")]
|
||||
[SwaggerOperation(Summary = "Get Google Maps key", Description = "Returns the Google Maps API key configured for frontend map features.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Maps API key returned")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetMapKey(CancellationToken ct)
|
||||
{
|
||||
return Ok(_googleSettings.MapKey);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Swashbuckle.AspNetCore.Annotations;
|
||||
|
||||
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")]
|
||||
[SwaggerOperation(Summary = "Liveness probe", Description = "Returns whether the API process is alive.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Service is alive")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
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]
|
||||
[SwaggerOperation(Summary = "Health check", Description = "Returns overall health status and current UTC time.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Health check succeeded")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
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")]
|
||||
[SwaggerOperation(Summary = "Echo payload", Description = "Returns the same JSON payload received in the request body.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Payload echoed successfully")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
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")]
|
||||
[SwaggerOperation(Summary = "Readiness probe", Description = "Returns whether the service is ready to accept traffic.")]
|
||||
[SwaggerResponse(StatusCodes.Status200OK, "Service is ready")]
|
||||
[SwaggerResponse(StatusCodes.Status503ServiceUnavailable, "Service is not ready")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
|
||||
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