From c96eb155aec9809f7008c01ec9d1a76bf80b2af0 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Thu, 19 Nov 2026 13:41:42 +0100 Subject: [PATCH] Add SMTP email delivery and deployment config --- README.md | 6 +- backend/Directory.Packages.props | 1 + .../Controllers/AuthController.cs | 6 +- backend/src/Helpdesk.Api/Program.cs | 9 ++- .../Helpdesk.Application/Auth/AuthService.cs | 26 +++++++-- .../src/Helpdesk.Application/Common/Errors.cs | 5 ++ .../DependencyInjection.cs | 28 ++++++++- .../Email/LoggingEmailSender.cs | 14 +---- .../Email/SmtpEmailSender.cs | 57 +++++++++++++++++++ .../Helpdesk.Infrastructure.csproj | 1 + deploy/.env.example | 23 +++++++- deploy/docker-compose.yml | 12 +++- 12 files changed, 160 insertions(+), 28 deletions(-) create mode 100644 backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs diff --git a/README.md b/README.md index 34720be..eae53f4 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,11 @@ Potřeba je jen Docker Desktop. 3. Swagger UI: · stav a verze schématu: -Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN_PASSWORD`. Odesílání e-mailů je zatím jen do logu – odkaz pro ověření e-mailu po registraci najdete v `docker compose -f deploy/docker-compose.yml logs api`. +Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_EMAIL` a `ADMIN_PASSWORD`. V režimu `Development` s prázdnými hodnotami `SMTP_MAILBOX` a `SMTP_PASSWORD` najdete ověřovací odkazy a odkazy pro obnovu hesla v logu služby `api`. + +Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS. + +Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli. ### Vývoj bez Dockeru diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index 235fb47..ee2454d 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -17,6 +17,7 @@ + diff --git a/backend/src/Helpdesk.Api/Controllers/AuthController.cs b/backend/src/Helpdesk.Api/Controllers/AuthController.cs index 760e483..dce9ef1 100644 --- a/backend/src/Helpdesk.Api/Controllers/AuthController.cs +++ b/backend/src/Helpdesk.Api/Controllers/AuthController.cs @@ -21,6 +21,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] public async Task> Register(RegisterRequest request, CancellationToken ct) { var user = await auth.RegisterAsync(request, ct); @@ -74,9 +75,10 @@ public sealed class AuthController(AuthService auth) : ControllerBase /// Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne. [HttpPost("forgot-password")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task ForgotPassword(ForgotPasswordRequest request, CancellationToken ct) + public IActionResult ForgotPassword(ForgotPasswordRequest request, [FromServices] IHostApplicationLifetime lifetime) { - await auth.ForgotPasswordAsync(request, ct); + // Doba vyhledání účtu a doručení přes SMTP se nesmí projevit v době odpovědi. + Response.OnCompleted(() => auth.ForgotPasswordAsync(request, lifetime.ApplicationStopping)); return NoContent(); } diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index c6f7309..88dd819 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -2,13 +2,20 @@ using System.Threading.RateLimiting; using Helpdesk.Api.Infrastructure; using Helpdesk.Application; using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Auth; using Helpdesk.Infrastructure; using Microsoft.IdentityModel.JsonWebTokens; var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplication(builder.Configuration); -builder.Services.AddInfrastructure(builder.Configuration); +builder.Services.AddInfrastructure(builder.Configuration, builder.Environment); +builder.Services.AddOptions() + .Validate(options => Uri.TryCreate(options.WebBaseUrl, UriKind.Absolute, out var url) && + (url.Scheme == Uri.UriSchemeHttps || (builder.Environment.IsDevelopment() && url.Scheme == Uri.UriSchemeHttp)) && + string.IsNullOrEmpty(url.UserInfo) && string.IsNullOrEmpty(url.Query) && string.IsNullOrEmpty(url.Fragment), + "Nastavte Registration:WebBaseUrl na veřejnou HTTPS adresu webové aplikace bez parametrů.") + .ValidateOnStart(); builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); diff --git a/backend/src/Helpdesk.Application/Auth/AuthService.cs b/backend/src/Helpdesk.Application/Auth/AuthService.cs index 869419b..86c31fb 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -32,12 +32,17 @@ public sealed class AuthService( ?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem."); var normalized = User.NormalizeEmail(request.Email); - if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, ct)) + var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct); + if (user is null) + { + user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); + db.Users.Add(user); + await db.SaveChangesAsync(ct); + } + else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash)) + { throw new ConflictException("Účet s tímto e-mailem už existuje."); - - var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); - db.Users.Add(user); - await db.SaveChangesAsync(ct); + } await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct); return UserDto.From(user); @@ -123,8 +128,17 @@ public sealed class AuthService( { var normalized = User.NormalizeEmail(request.Email ?? ""); var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct); - if (user is not null) + if (user is null) + return; + + try + { await SendEmailTokenAsync(user, TokenType.PasswordReset, ct); + } + catch (EmailDeliveryException) + { + // SMTP zapisuje typ chyby. Odpověď na obnovu hesla zůstává pro všechny adresy stejná. + } } public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct) diff --git a/backend/src/Helpdesk.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index 39e5b29..bf94d77 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -31,4 +31,9 @@ public sealed class BadRequestException(string message) : AppException(message) public override int StatusCode => 400; } +public sealed class EmailDeliveryException() : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") +{ + public override int StatusCode => 503; +} + public sealed record PagedResult(IReadOnlyList Items, int TotalCount, int Page, int PageSize); diff --git a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs index 40b6693..748944e 100644 --- a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs +++ b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs @@ -8,12 +8,15 @@ using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using MimeKit; namespace Helpdesk.Infrastructure; public static class DependencyInjection { - public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddInfrastructure( + this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment) { var connectionString = configuration.GetConnectionString("Helpdesk") ?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk."); @@ -33,7 +36,7 @@ public static class DependencyInjection services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + AddEmailSender(services, configuration.GetSection("Smtp"), environment); services.AddSingleton(); services.AddHostedService(); @@ -41,4 +44,25 @@ public static class DependencyInjection services.AddHostedService(); return services; } + + private static void AddEmailSender(IServiceCollection services, IConfigurationSection configuration, IHostEnvironment environment) + { + if (environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["Mailbox"]) && + string.IsNullOrWhiteSpace(configuration["Password"])) + { + services.AddSingleton(); + return; + } + + services.AddOptions() + .Bind(configuration) + .Validate(options => !string.IsNullOrWhiteSpace(options.Host) && options.Port is >= 1 and <= 65535, + "Nastavte platný SMTP server a port.") + .Validate(options => MailboxAddress.TryParse(options.Mailbox, out var mailbox) && + mailbox.Address == options.Mailbox && mailbox.Address.Contains('@'), + "Nastavte celou e-mailovou adresu SMTP schránky.") + .Validate(options => !string.IsNullOrWhiteSpace(options.Password), "Nastavte heslo SMTP schránky.") + .ValidateOnStart(); + services.AddSingleton(); + } } diff --git a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs index 6b269b5..036678b 100644 --- a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs @@ -1,27 +1,19 @@ using Helpdesk.Application.Abstractions; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Helpdesk.Infrastructure.Email; /// -/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět -/// v docker compose logs api). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi. +/// Vývojová náhrada odesílání e-mailů, pokud schránka SMTP není nakonfigurována. /// -internal sealed partial class LoggingEmailSender(ILogger logger, IHostEnvironment environment) : IEmailSender +internal sealed partial class LoggingEmailSender(ILogger logger) : IEmailSender { public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) { - if (environment.IsDevelopment()) - LogEmail(to, subject, body); - else - LogMissingTransport(); + LogEmail(to, subject, body); return Task.CompletedTask; } [LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")] private partial void LogEmail(string to, string subject, string body); - - [LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")] - private partial void LogMissingTransport(); } diff --git a/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs new file mode 100644 index 0000000..28ced30 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Email/SmtpEmailSender.cs @@ -0,0 +1,57 @@ +using System.Net.Sockets; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using MailKit; +using MailKit.Net.Smtp; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MimeKit; + +namespace Helpdesk.Infrastructure.Email; + +internal sealed class SmtpOptions +{ + public string Host { get; set; } = "smtp.seznam.cz"; + public int Port { get; set; } = 465; + public string Mailbox { get; set; } = ""; + public string Password { get; set; } = ""; +} + +internal sealed partial class SmtpEmailSender(IOptions options, ILogger logger) : IEmailSender +{ + public async Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) + { + if (!MailboxAddress.TryParse(to, out var recipient)) + { + LogDeliveryFailure("InvalidRecipient"); + throw new EmailDeliveryException(); + } + + var settings = options.Value; + using var message = new MimeMessage { Subject = subject, Body = new TextPart("plain") { Text = body } }; + message.From.Add(MailboxAddress.Parse(settings.Mailbox)); + message.To.Add(recipient); + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + using var client = new SmtpClient(); + try + { + await client.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.SslOnConnect, timeout.Token); + await client.AuthenticateAsync(settings.Mailbox, settings.Password, timeout.Token); + await client.SendAsync(message, timeout.Token); + } + catch (Exception exception) when (!cancellationToken.IsCancellationRequested && + exception is (IOException or SocketException or CommandException or ProtocolException or + AuthenticationException or SslHandshakeException or NotSupportedException or TimeoutException or + OperationCanceledException)) + { + LogDeliveryFailure(exception.GetType().Name); + throw new EmailDeliveryException(); + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")] + private partial void LogDeliveryFailure(string failureType); +} diff --git a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj index 3fd70f6..593292c 100644 --- a/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj +++ b/backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj @@ -10,6 +10,7 @@ + diff --git a/deploy/.env.example b/deploy/.env.example index 803ec70..cf5178d 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -11,8 +11,27 @@ APP_DB_PASSWORD=change-me-app JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= -# Účet administrátora – vytvoří se při prvním startu API, pokud neexistuje. -ADMIN_EMAIL=admin@univerzita.cz +# Volitelný účet administrátora vytvořený při prvním startu API. +ADMIN_EMAIL=admin@domain.local ADMIN_PASSWORD=change-me-admin +# HTTP adresa a port API na hostiteli, kam se reverse proxy připojuje. +# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli. +PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1 +API_HTTP_PORT=8080 + +# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény. +PUBLIC_BASE_URL= #https://helpdesk.domain.local +STUDENT_EMAIL_DOMAIN= #student.domain.local +TEACHER_EMAIL_DOMAIN= #domain.local + +# Email Profi. V Production vyplňte celou adresu schránky a její heslo. +SMTP_HOST=smtp.seznam.cz +SMTP_PORT=465 +SMTP_MAILBOX= +# Jednoduché uvozovky zachovají ve skutečném hesle např. znak $. +SMTP_PASSWORD='' + +# Development = bez proxy +# Production = s reverse proxy ASPNETCORE_ENVIRONMENT=Development diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 204cdea..d977619 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -1,5 +1,5 @@ # Vývojové spuštění backendu: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build -# Topologie odpovídá kap. 15 návrhu; proxy (nginx + HTTPS), web a mailpit přibudou v dalších fázích. +# Reverse proxy ukončuje HTTPS a připojuje se k API přes HTTP. name: helpdesk @@ -44,6 +44,13 @@ services: ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}" Jwt__SigningKey: ${JWT_SIGNING_KEY:?} Encryption__Key: ${ENCRYPTION_KEY:?} + Registration__WebBaseUrl: ${PUBLIC_BASE_URL:-https://helpdesk.localhost} + Registration__StudentEmailDomains__0: ${STUDENT_EMAIL_DOMAIN:-student.univerzita.cz} + Registration__TeacherEmailDomains__0: ${TEACHER_EMAIL_DOMAIN:-univerzita.cz} + Smtp__Host: ${SMTP_HOST:-smtp.seznam.cz} + Smtp__Port: ${SMTP_PORT:-465} + Smtp__Mailbox: ${SMTP_MAILBOX:-} + Smtp__Password: ${SMTP_PASSWORD:-} ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} volumes: @@ -51,9 +58,8 @@ services: depends_on: migrator: condition: service_completed_successfully - # Dočasně publikováno přímo; po přidání nginx proxy bude API dostupné jen přes ni. ports: - - "8080:8080" + - "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080" networks: [frontend, backend] networks: