Add SMTP email delivery and deployment config

This commit is contained in:
GonnaHetzMe committed 2026-11-19 13:41:42 +01:00
1 parent 28fc49ea39
commit c96eb155ae
12 files changed
+158 -26

No files matched your search

+5 -1
View File
@@ -31,7 +31,11 @@ Potřeba je jen Docker Desktop.
3. Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
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
+1
View File
@@ -17,6 +17,7 @@
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageVersion Include="MailKit" Version="5.0.0" />
<PackageVersion Include="FluentValidation" Version="12.2.0" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<!-- testy -->
@@ -21,6 +21,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status503ServiceUnavailable)]
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
{
var user = await auth.RegisterAsync(request, ct);
@@ -74,9 +75,10 @@ public sealed class AuthController(AuthService auth) : ControllerBase
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
[HttpPost("forgot-password")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> 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();
}
+8 -1
View File
@@ -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<RegistrationOptions>()
.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<ICurrentUser, HttpCurrentUser>();
@@ -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))
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);
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.");
}
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
return UserDto.From(user);
@@ -123,9 +128,18 @@ 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)
{
@@ -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<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
@@ -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<IPasswordHasher, BCryptPasswordHasher>();
services.AddSingleton<ITokenService, JwtTokenService>();
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
services.AddSingleton<IEmailSender, LoggingEmailSender>();
AddEmailSender(services, configuration.GetSection("Smtp"), environment);
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
services.AddHostedService<RevokedTokenStoreLoader>();
@@ -41,4 +44,25 @@ public static class DependencyInjection
services.AddHostedService<AuthTokenCleanupService>();
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<IEmailSender, LoggingEmailSender>();
return;
}
services.AddOptions<SmtpOptions>()
.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<IEmailSender, SmtpEmailSender>();
}
}
@@ -1,27 +1,19 @@
using Helpdesk.Application.Abstractions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Email;
/// <summary>
/// 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 <c>docker compose logs api</c>). 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.
/// </summary>
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
{
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
{
if (environment.IsDevelopment())
LogEmail(to, subject, body);
else
LogMissingTransport();
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();
}
@@ -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<SmtpOptions> options, ILogger<SmtpEmailSender> 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);
}
@@ -10,6 +10,7 @@
<PackageReference Include="MySqlConnector" />
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="BCrypt.Net-Next" />
<PackageReference Include="MailKit" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
+21 -2
View File
@@ -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
+9 -3
View File
@@ -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: