Základní backend: migrace, autentizace JWT, role, Swagger
- Helpdesk.Migrator (DbUp) aplikuje db/migrations, evidence v schema_version - Domain/Application/Infrastructure/Api podle Clean Architecture - registrace, ověření e-mailu, login, refresh s rotací, logout, reset hesla - JWT podle RFC 7519 evidované jen podle jti v auth_token - správa uživatelů a rolí, číselníky, ProblemDetails, Swagger UI - Docker Compose (db, migrator, api), oddělené DB účty - notifikace mají cizí klíče na issue a proposal - unit testy domény a zabezpečení Closes #1, closes #2, closes #3, closes #4, closes #5, closes #9
This commit is contained in:
1 parent
fc76be7d69
commit
a51d386278
64 files changed
+4394
-1
No files matched your search
@@ -0,0 +1,46 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
|
||||
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
||||
/// </summary>
|
||||
internal sealed partial class AdminSeeder(
|
||||
IServiceScopeFactory scopes,
|
||||
IConfiguration configuration,
|
||||
ILogger<AdminSeeder> logger) : IHostedService
|
||||
{
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var email = configuration["ADMIN_EMAIL"];
|
||||
var password = configuration["ADMIN_PASSWORD"];
|
||||
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
|
||||
return;
|
||||
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||
|
||||
var normalized = User.NormalizeEmail(email);
|
||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
|
||||
return;
|
||||
|
||||
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
||||
admin.ConfirmEmail();
|
||||
db.Users.Add(admin);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
LogCreated(email);
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Vytvořen účet administrátora {Email}.")]
|
||||
private partial void LogCreated(string email);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeConfiguration<User>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<User> b)
|
||||
{
|
||||
b.ToTable("app_user");
|
||||
b.HasKey(u => u.Id);
|
||||
b.Property(u => u.Email).HasMaxLength(254);
|
||||
b.Property(u => u.EmailNormalized).HasMaxLength(254);
|
||||
b.HasIndex(u => u.EmailNormalized).IsUnique();
|
||||
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
|
||||
b.Property(u => u.Phone)
|
||||
.HasColumnName("phone_encrypted")
|
||||
.HasConversion(encryptor.StringToCipherConverter)
|
||||
.HasMaxLength(512);
|
||||
b.Ignore(u => u.FullName);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class AuthTokenConfiguration : IEntityTypeConfiguration<AuthToken>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AuthToken> b)
|
||||
{
|
||||
b.ToTable("auth_token");
|
||||
b.HasKey(t => t.Jti);
|
||||
b.Property(t => t.Jti).HasMaxLength(36);
|
||||
b.Property(t => t.TokenType).HasConversion<EnumCodeConverter<TokenType>>().HasMaxLength(20);
|
||||
b.Property(t => t.RevokeReason).HasConversion<EnumCodeConverter<RevokeReason>>().HasMaxLength(30);
|
||||
// Vazba jen ze závislé strany – User nemá kolekci tokenů (kap. 12.3).
|
||||
b.HasOne<User>().WithMany().HasForeignKey(t => t.UserId);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class BuildingConfiguration : IEntityTypeConfiguration<Building>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Building> b)
|
||||
{
|
||||
b.ToTable("building");
|
||||
b.HasKey(x => x.Id);
|
||||
b.HasIndex(x => x.Code).IsUnique();
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class IssueCategoryConfiguration : IEntityTypeConfiguration<IssueCategory>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IssueCategory> b) => b.ToTable("issue_category");
|
||||
}
|
||||
|
||||
internal sealed class ProposalCategoryConfiguration : IEntityTypeConfiguration<ProposalCategory>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ProposalCategory> b) => b.ToTable("proposal_category");
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Helpdesk.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>Vyplní <c>created_at</c> u nově přidaných entit s <see cref="IHasCreatedAt"/> (kap. 12.4).</summary>
|
||||
internal sealed class CreatedAtInterceptor(TimeProvider clock) : SaveChangesInterceptor
|
||||
{
|
||||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
Stamp(eventData.Context);
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Stamp(eventData.Context);
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
private void Stamp(DbContext? context)
|
||||
{
|
||||
if (context is null)
|
||||
return;
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
foreach (var entry in context.ChangeTracker.Entries<IHasCreatedAt>())
|
||||
{
|
||||
if (entry.State == EntityState.Added)
|
||||
entry.Entity.CreatedAt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Helpdesk.Domain;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>Enum ↔ textový kód v DB (<c>FacilityManager</c> ↔ <c>'FACILITY_MANAGER'</c>), hodnoty hlídá CHECK omezení.</summary>
|
||||
internal sealed class EnumCodeConverter<TEnum>() : ValueConverter<TEnum, string>(
|
||||
v => v.ToCode(),
|
||||
v => EnumCode.Parse<TEnum>(v))
|
||||
where TEnum : struct, Enum;
|
||||
@@ -0,0 +1,43 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// EF Core slouží jen k mapování – schéma vytvářejí SQL migrace v <c>db/migrations</c> (kap. 12.5).
|
||||
/// Názvy sloupců jsou snake_case (EFCore.NamingConventions), tabulky jsou pojmenované explicitně.
|
||||
/// </summary>
|
||||
public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> options, FieldEncryptor encryptor)
|
||||
: DbContext(options), IAppDbContext
|
||||
{
|
||||
public DbSet<User> Users => Set<User>();
|
||||
public DbSet<AuthToken> AuthTokens => Set<AuthToken>();
|
||||
public DbSet<Building> Buildings => Set<Building>();
|
||||
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
|
||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor));
|
||||
modelBuilder.ApplyConfiguration(new AuthTokenConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||
}
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||
{
|
||||
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||
configurationBuilder.Properties<DateTime?>().HaveConversion<UtcDateTimeConverter>();
|
||||
}
|
||||
|
||||
private sealed class UtcDateTimeConverter() : ValueConverter<DateTime, DateTime>(
|
||||
v => v.Kind == DateTimeKind.Utc ? v : v.ToUniversalTime(),
|
||||
v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
|
||||
}
|
||||
Reference in new issue
Block a user