This commit is contained in:
john 2025-05-14 23:53:00 +02:00
parent baea64229b
commit 0dc41337da
36 changed files with 324 additions and 95 deletions

View file

@ -0,0 +1,17 @@
using Femto.Common.Domain;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Femto.Modules.Auth.Application;
internal class AuthenticationModule(IHost host) : IAuthenticationModule
{
public async Task<TResponse> PostCommand<TResponse>(ICommand<TResponse> command, CancellationToken cancellationToken = default)
{
using var scope = host.Services.CreateScope();
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
var response = await mediator.Send(command, cancellationToken);
return response;
}
}

View file

@ -0,0 +1,48 @@
using Femto.Common.Infrastructure;
using Femto.Modules.Auth.Data;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Femto.Modules.Auth.Application;
public static class AuthenticationStartup
{
public static void InitializeAuthenticationModule(this IServiceCollection rootContainer, string connectionString)
{
var hostBuilder = Host.CreateDefaultBuilder();
hostBuilder.ConfigureServices(services => ConfigureServices(services, connectionString));
var host = hostBuilder.Build();
rootContainer.AddScoped<IAuthenticationModule>(_ => new AuthenticationModule(host));
}
private static void ConfigureServices(IServiceCollection services, string connectionString)
{
services.AddDbContext<AuthContext>(
builder =>
{
builder.UseNpgsql(connectionString);
builder.UseSnakeCaseNamingConvention();
});
services.AddMediatR(c => c.RegisterServicesFromAssembly(typeof(AuthenticationStartup).Assembly));
services.AddDbContext<AuthContext>(builder =>
{
builder.UseNpgsql();
builder.UseSnakeCaseNamingConvention();
builder.EnableSensitiveDataLogging();
});
services.AddMediatR(c =>
{
c.RegisterServicesFromAssembly(typeof(AuthenticationStartup).Assembly);
});
services.AddTransient(
typeof(IPipelineBehavior<,>),
typeof(SaveChangesPipelineBehaviour<,>)
);
}
}

View file

@ -0,0 +1,6 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Commands.Login;
public record LoginCommand(string Username, string Password) : ICommand<LoginResult>;

View file

@ -0,0 +1,33 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Application.Services;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Commands.Login;
internal class LoginCommandHandler(AuthContext context, SessionGenerator sessionGenerator)
: ICommandHandler<LoginCommand, LoginResult>
{
public async Task<LoginResult> Handle(LoginCommand request, CancellationToken cancellationToken)
{
var user = await context.Users.SingleOrDefaultAsync(
u => u.Username == request.Username,
cancellationToken
);
if (user is null)
throw new DomainException("invalid credentials");
if (!user.HasPassword(request.Password))
throw new DomainException("invalid credentials");
var session = sessionGenerator.GenerateSession();
await context.AddAsync(session, cancellationToken);
return new(new Session(session.Id, session.Expires), user.Id, user.Username);
}
}

View file

@ -0,0 +1,6 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Commands.Register;
public record RegisterCommand(string Username, string Password) : ICommand<RegisterResult>;

View file

@ -0,0 +1,23 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Application.Services;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Application.Commands.Register;
internal class RegisterCommandHandler(AuthContext context, SessionGenerator sessionGenerator) : ICommandHandler<RegisterCommand, RegisterResult>
{
public async Task<RegisterResult> Handle(RegisterCommand request, CancellationToken cancellationToken)
{
var user = new UserIdentity(request.Username);
user.SetPassword(request.Password);
var session = user.StartNewSession();
await context.AddAsync(user, cancellationToken);
return new(new Session(session.Id, session.Expires), user.Id, user.Username);
}
}

View file

@ -0,0 +1,6 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Commands.ValidateSession;
public record ValidateSessionCommand(string SessionId) : ICommand<ValidateSessionResult>;

View file

@ -0,0 +1,34 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Commands.ValidateSession;
internal class ValidateSessionCommandHandler(AuthContext context)
: ICommandHandler<ValidateSessionCommand, ValidateSessionResult>
{
public async Task<ValidateSessionResult> Handle(
ValidateSessionCommand request,
CancellationToken cancellationToken
)
{
var now = DateTimeOffset.UtcNow;
var user = await context.Users.SingleOrDefaultAsync(
u => u.Sessions.Any(s => s.Id == request.SessionId && s.Expires > now),
cancellationToken
);
if (user is null)
throw new DomainException("invalid session");
var session = user.StartNewSession();
return new ValidateSessionResult(
new Session(session.Id, session.Expires),
user.Id,
user.Username
);
}
}

View file

@ -0,0 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record LoginResult(Session Session, Guid UserId, string Username);

View file

@ -0,0 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record RegisterResult(Session Session, Guid UserId, string Username);

View file

@ -0,0 +1,5 @@
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Application.Dto;
public record Session(string SessionId, DateTimeOffset Expires);

View file

@ -0,0 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record ValidateSessionResult(Session Session, Guid UserId, string Username);

View file

@ -0,0 +1,8 @@
using Femto.Common.Domain;
namespace Femto.Modules.Auth.Application;
public interface IAuthenticationModule
{
Task<TResponse> PostCommand<TResponse>(ICommand<TResponse> command, CancellationToken cancellationToken = default);
}

View file

@ -0,0 +1,11 @@
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Application.Services;
public class SessionGenerator
{
public UserSession GenerateSession()
{
throw new NotImplementedException();
}
}

View file

@ -0,0 +1,23 @@
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Contracts;
internal class AuthenticationService(AuthContext context) : IAuthenticationService
{
public async Task<UserInfo> Register(string username, string password)
{
var user = new UserIdentity(username).WithPassword(password);
await context.AddAsync(user);
await context.SaveChangesAsync();
return new(user.Id, user.Username);
}
public async Task<UserInfo> Authenticate(string username, string password)
{
throw new NotImplementedException();
}
}
public class AuthenticationError(string message, Exception inner) : Exception(message, inner);

View file

@ -0,0 +1,7 @@
namespace Femto.Modules.Auth.Contracts;
public interface IAuthenticationService
{
public Task<UserInfo?> Register(string username, string password);
public Task<UserInfo?> Authenticate(string username, string password);
}

View file

@ -0,0 +1,3 @@
namespace Femto.Modules.Auth.Contracts;
public record UserInfo(Guid UserId, string Username);

View file

@ -0,0 +1,18 @@
using Femto.Common.Infrastructure.Outbox;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Data;
internal class AuthContext : DbContext, IOutboxContext
{
public virtual DbSet<UserIdentity> Users { get; }
public virtual DbSet<OutboxEntry> Outbox { get; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.HasDefaultSchema("authn");
builder.ApplyConfigurationsFromAssembly(typeof(AuthContext).Assembly);
}
}

View file

@ -0,0 +1,15 @@
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Femto.Modules.Auth.Data.Configurations;
internal class UserIdentityTypeConfiguration : IEntityTypeConfiguration<UserIdentity>
{
public void Configure(EntityTypeBuilder<UserIdentity> builder)
{
builder.ToTable("user_identity");
builder.OwnsOne(u => u.Password).WithOwner().HasForeignKey("user_id");
builder.OwnsMany(u => u.Sessions).WithOwner().HasForeignKey("user_id");
}
}

View file

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="8.3.0" />
<PackageReference Include="EFCore.NamingConventions" Version="9.0.0" />
<PackageReference Include="Geralt" Version="3.3.0" />
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Femto.Common\Femto.Common.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Models\DomainEventHandlers\" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,5 @@
using Femto.Common.Domain;
namespace Femto.Modules.Auth.Models.Events;
internal record UserWasCreatedEvent(UserIdentity User) : DomainEvent;

View file

@ -0,0 +1,60 @@
using System.Text;
using System.Text.Unicode;
using Femto.Common.Domain;
using Femto.Modules.Auth.Models.Events;
using Geralt;
namespace Femto.Modules.Auth.Models;
internal class UserIdentity : Entity
{
public Guid Id { get; private set; }
public string Username { get; private set; }
public UserPassword Password { get; private set; }
public ICollection<UserSession> Sessions { get; private set; }
private UserIdentity() { }
public UserIdentity(string username)
{
this.Id = Guid.CreateVersion7();
this.Username = username;
this.AddDomainEvent(new UserWasCreatedEvent(this));
}
public UserIdentity WithPassword(string password)
{
this.SetPassword(password);
return this;
}
public void SetPassword(string password)
{
this.Password = new UserPassword(password);
}
public bool HasPassword(string requestPassword)
{
if (this.Password is null)
{
return false;
}
return this.Password.Check(requestPassword);
}
public UserSession StartNewSession()
{
var session = UserSession.Create();
this.Sessions.Add(session);
return session;
}
}
public class SetPasswordError(string message, Exception inner) : DomainException(message, inner);

View file

@ -0,0 +1,73 @@
using System.Text;
using Geralt;
using JetBrains.Annotations;
namespace Femto.Modules.Auth.Models;
internal class UserPassword
{
private const int Iterations = 3;
private const int MemorySize = 67108864;
public Guid Id { get; private set; }
private byte[] Hash { get; set; }
private byte[] Salt { get; set; }
[UsedImplicitly]
private UserPassword() {}
public UserPassword(string password)
{
this.Id = Guid.NewGuid();
this.Salt = ComputeSalt();
this.Hash = ComputePasswordHash(password, Salt);
}
public bool Check(string password)
{
var matches = Argon2id.VerifyHash(
Hash,
Combine(password, Salt)
);
if (!matches)
return false;
if (Argon2id.NeedsRehash(Hash, Iterations, MemorySize))
{
this.Salt = ComputeSalt();
this.Hash = ComputePasswordHash(password, Salt);
}
return true;
}
private static byte[] ComputeSalt() => System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);
private static byte[] ComputePasswordHash(string password, byte[] salt)
{
var hash = new byte[128];
try
{
Argon2id.ComputeHash(hash, Combine(password, salt), Iterations, MemorySize);
}
catch (Exception e)
{
throw new SetPasswordError("Failed to hash password", e);
}
return hash;
}
private static byte[] Combine(string password, byte[] salt)
{
var passwordBytes = Encoding.UTF8.GetBytes(password);
var hashInput = new byte[passwordBytes.Length + salt.Length];
passwordBytes.CopyTo(hashInput, 0);
salt.CopyTo(hashInput, passwordBytes.Length);
return hashInput;
}
}

View file

@ -0,0 +1,19 @@
namespace Femto.Modules.Auth.Models;
public class UserSession
{
private static TimeSpan SessionTimeout = TimeSpan.FromMinutes(30);
public string Id { get; private set; }
public DateTimeOffset Expires { get; private set; }
private UserSession() {}
public static UserSession Create()
{
return new()
{
Id = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)),
Expires = DateTimeOffset.Now + SessionTimeout
};
}
}