This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
using CvMatcher.Models.Responses;
|
||||
using Models.Requests;
|
||||
using Refit;
|
||||
|
||||
namespace Api.Clients.Api.Contracts;
|
||||
|
||||
public interface ICvMatcherApi
|
||||
{
|
||||
[Multipart]
|
||||
[Post("/api/cv/upload")]
|
||||
Task<CvUploadResponse> Upload([AliasAs("file")] StreamPart file, CancellationToken ct);
|
||||
|
||||
[Post("/api/cv/match-job")]
|
||||
Task<JobMatchResponse> MatchJob([Body] JobMatchRequest request, CancellationToken ct);
|
||||
}
|
||||
@@ -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" });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System.Reflection;
|
||||
using Api.Services;
|
||||
using Api.Services.Contracts;
|
||||
using Models.Settings;
|
||||
using Refit;
|
||||
using Serilog;
|
||||
using StartupHelpers;
|
||||
|
||||
StartupExtensions.LoadDotEnvFile();
|
||||
|
||||
const string ServiceName = "api";
|
||||
var appVersion = StartupExtensions.GetApplicationVersion(Assembly.GetExecutingAssembly());
|
||||
|
||||
try
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.ConfigureJsonSerilog(ServiceName, appVersion);
|
||||
Log.Information("Starting {Service} version {AppVersion}", ServiceName, appVersion);
|
||||
|
||||
builder.AddAzureKeyVaultIfConfigured();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
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"));
|
||||
|
||||
builder.Services.AddHttpClient<ICaptchaVerifier, RecaptchaVerifier>();
|
||||
builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();
|
||||
builder.Services.AddSingleton<Microsoft.AspNetCore.StaticFiles.IContentTypeProvider, Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider>();
|
||||
|
||||
builder.Services.AddRefitClient<Api.Clients.Api.Contracts.ICvMatcherApi>()
|
||||
.ConfigureHttpClient((sp, client) =>
|
||||
{
|
||||
var config = sp.GetRequiredService<IConfiguration>();
|
||||
var baseUrl = config["CvMatcherApi:BaseUrl"] ?? string.Empty;
|
||||
if (!string.IsNullOrWhiteSpace(baseUrl))
|
||||
{
|
||||
client.BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/");
|
||||
}
|
||||
|
||||
var key = config["CvMatcherApi:InternalApiKey"];
|
||||
if (!string.IsNullOrWhiteSpace(key) && !client.DefaultRequestHeaders.Contains("X-Internal-Api-Key"))
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("X-Internal-Api-Key", key);
|
||||
}
|
||||
});
|
||||
|
||||
builder.Services.AddSwaggerWithXmlComments(Assembly.GetExecutingAssembly(), "API");
|
||||
builder.Services.ConfigureCaddyForwardedHeaders();
|
||||
builder.Services.AddFrontendCorsFromConfiguration(builder.Configuration);
|
||||
builder.Services.AddPublicApiRateLimiting(builder.Configuration);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.LogStartupDiagnostics(ServiceName);
|
||||
|
||||
app.UseForwardedHeaders();
|
||||
app.UseDefaultSerilogRequestLogging(includeProxyHeaders: true);
|
||||
app.UseSwaggerInDevelopment("API", "API");
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthorization();
|
||||
app.UseRouting();
|
||||
app.UseCors("FrontendOnly");
|
||||
app.UseRateLimiter();
|
||||
app.MapControllers();
|
||||
|
||||
Log.Information("{Service} startup complete. Listening for requests...", ServiceName);
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "{Service} terminated unexpectedly", ServiceName);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.Information("Shutting down {Service}", ServiceName);
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
@@ -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 @@
|
||||
using Api.Services.Contracts.Models;
|
||||
|
||||
namespace Api.Services.Contracts
|
||||
{
|
||||
public interface ICaptchaVerifier
|
||||
{
|
||||
Task<CaptchaVerdictModel> VerifyAsync(string token, string? userIp, string? expectedAction, CancellationToken ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Models.Requests;
|
||||
|
||||
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);
|
||||
Task SendMatchAsync(string? explicitTo, string subject, string body, string? attachmentPath, CancellationToken ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Api.Services.Contracts.Models
|
||||
{
|
||||
public sealed record CaptchaVerdictModel(bool Success, string? Error, double? Score);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Api.Services.Contracts.Models;
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Models.Settings;
|
||||
|
||||
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<CaptchaVerdictModel> VerifyAsync(string token, string? userIp, string? expectedAction, 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 CaptchaVerdictModel(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 CaptchaVerdictModel(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 CaptchaVerdictModel(false, "Captcha parse error", null);
|
||||
}
|
||||
|
||||
if (!data.success)
|
||||
{
|
||||
_log.LogWarning("Captcha verification failed for IP {Ip}. Score={Score}",
|
||||
userIp ?? "unknown", data.score);
|
||||
return new CaptchaVerdictModel(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 CaptchaVerdictModel(false, "Captcha score too low", score);
|
||||
}
|
||||
|
||||
// Optional strictness (usually v3): action/hostname checks
|
||||
var actionToCheck = !string.IsNullOrWhiteSpace(expectedAction) ? expectedAction : _opt.ExpectedAction;
|
||||
if (!string.IsNullOrWhiteSpace(actionToCheck) &&
|
||||
!string.Equals(actionToCheck, data.action, StringComparison.Ordinal))
|
||||
{
|
||||
_log.LogWarning("Captcha action mismatch. Expected={Expected}, Actual={Actual}, IP={Ip}",
|
||||
actionToCheck, data.action, userIp ?? "unknown");
|
||||
return new CaptchaVerdictModel(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 CaptchaVerdictModel(false, "Captcha hostname mismatch", data.score);
|
||||
}
|
||||
|
||||
_log.LogInformation("Captcha verified successfully for IP {Ip}. Score={Score}",
|
||||
userIp ?? "unknown", data.score);
|
||||
return new CaptchaVerdictModel(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,239 @@
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using MimeKit;
|
||||
using Models.Settings;
|
||||
using Models.Requests;
|
||||
using CvMatcher.Models.Responses;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public async Task SendMatchAsync(string? explicitTo, string subject, string body, string? attachmentPath, CancellationToken ct)
|
||||
{
|
||||
var recipients = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(explicitTo))
|
||||
{
|
||||
recipients.Add(explicitTo);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_contact.ToEmail) &&
|
||||
!recipients.Any(x => string.Equals(x, _contact.ToEmail, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
recipients.Add(_contact.ToEmail);
|
||||
}
|
||||
|
||||
if (recipients.Count == 0)
|
||||
{
|
||||
_log.LogDebug("Match email skipped - no recipients configured (user email and Contact:ToEmail missing)");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var recipient in recipients)
|
||||
{
|
||||
_log.LogInformation("Preparing CV match email to {RecipientEmail}", recipient);
|
||||
|
||||
var msg = new MimeMessage();
|
||||
msg.From.Add(MailboxAddress.Parse(_smtp.Username));
|
||||
msg.To.Add(MailboxAddress.Parse(recipient));
|
||||
msg.Subject = $"[{_environmentName}] {subject}".Trim();
|
||||
|
||||
var builder = new BodyBuilder
|
||||
{
|
||||
TextBody = body
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(attachmentPath) && File.Exists(attachmentPath))
|
||||
{
|
||||
builder.Attachments.Add(attachmentPath);
|
||||
}
|
||||
|
||||
msg.Body = builder.ToMessageBody();
|
||||
|
||||
await SendEmailAsync(msg, "cv match email", ct);
|
||||
_log.LogInformation("CV match email sent successfully to {RecipientEmail}", recipient);
|
||||
}
|
||||
}
|
||||
|
||||
public static string BuildMatchEmailBody(string cvDocumentId, JobMatchResponse result, string? jobLabel) => $@"CV Matcher result
|
||||
|
||||
CV Document ID: {cvDocumentId}
|
||||
Job: {jobLabel ?? "N/A"}
|
||||
Job URL: {result.JobUrl ?? "N/A"}
|
||||
Score: {result.Score}%
|
||||
|
||||
Summary:
|
||||
{result.Summary}
|
||||
|
||||
Strengths:
|
||||
- {string.Join("\n- ", result.Strengths)}
|
||||
|
||||
Gaps:
|
||||
- {string.Join("\n- ", result.Gaps)}
|
||||
|
||||
Recommendations:
|
||||
- {string.Join("\n- ", result.Recommendations)}";
|
||||
|
||||
public static string BuildMatchEmailSubject(int score, string? jobLabel)
|
||||
=> $"MyAi.ro CV Match: {score}% - {jobLabel ?? "Job"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
{
|
||||
"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]"
|
||||
},
|
||||
"CvMatcherApi": {
|
||||
"BaseUrl": "",
|
||||
"InternalApiKey": ""
|
||||
},
|
||||
"RateLimiting": {
|
||||
"Global": {
|
||||
"PermitLimit": 120,
|
||||
"Window": "00:01:00",
|
||||
"QueueLimit": 0,
|
||||
"AutoReplenishment": true
|
||||
},
|
||||
"Policies": {
|
||||
"contact": {
|
||||
"PermitLimit": 5,
|
||||
"Window": "00:01:00",
|
||||
"QueueLimit": 0,
|
||||
"AutoReplenishment": true
|
||||
},
|
||||
"cvMatcher": {
|
||||
"PermitLimit": 10,
|
||||
"Window": "00:10:00",
|
||||
"QueueLimit": 0,
|
||||
"AutoReplenishment": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user