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

@ -1,4 +1,7 @@
using Femto.Modules.Authentication.Application;
using Femto.Api.Sessions;
using Femto.Modules.Auth.Application;
using Femto.Modules.Auth.Application.Commands.Login;
using Femto.Modules.Auth.Application.Commands.Register;
using Microsoft.AspNetCore.Mvc;
namespace Femto.Api.Controllers.Auth;
@ -10,17 +13,25 @@ public class AuthController(IAuthenticationModule authModule) : ControllerBase
[HttpPost("login")]
public async Task<ActionResult<LoginResponse>> Login([FromBody] LoginRequest request)
{
var result = await authModule.PostCommand(
new LoginCommand(request.Username, request.Password)
);
var userId = await authModule.PostCommand(new LoginCommand(request.Username, request.Password));
HttpContext.SetSession(result.Session);
throw new NotImplementedException();
return new LoginResponse(result.UserId, result.Username);
}
[HttpPost("signup")]
public async Task<ActionResult<SignupResponse>> Signup([FromBody] SignupRequest request)
{
throw new NotImplementedException();
var result = await authModule.PostCommand(
new RegisterCommand(request.Username, request.Password)
);
HttpContext.SetSession(result.Session);
return new SignupResponse(result.UserId, result.Username);
}
[HttpPost("delete-session")]

View file

@ -1,3 +1,3 @@
namespace Femto.Api.Controllers.Auth;
public record LoginResponse(Guid UserId, string Username, string SessionToken);
public record LoginResponse(Guid UserId, string Username);

View file

@ -1,3 +1,3 @@
namespace Femto.Api.Controllers.Auth;
public record SignupResponse(Guid UserId, string Username, string SessionToken);
public record SignupResponse(Guid UserId, string Username);

View file

@ -18,7 +18,7 @@
<ItemGroup>
<ProjectReference Include="..\Femto.Modules.Blog\Femto.Modules.Blog.csproj" />
<ProjectReference Include="..\Femto.Modules.Authentication\Femto.Modules.Authentication.csproj" />
<ProjectReference Include="..\Femto.Modules.Auth\Femto.Modules.Auth.csproj" />
<ProjectReference Include="..\Femto.Modules.Media\Femto.Modules.Media.csproj" />
</ItemGroup>

View file

@ -1,6 +1,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Femto.Modules.Authentication.Application;
using Femto.Modules.Auth.Application;
using Femto.Modules.Blog.Application;
using Femto.Modules.Media.Application;

View file

@ -0,0 +1,21 @@
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Api.Sessions;
internal static class HttpContextSessionExtensions
{
public static void SetSession(this HttpContext httpContext, Session session)
{
httpContext.Response.Cookies.Append(
"session",
session.SessionId,
new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict,
Expires = session.Expires,
}
);
}
}

View file

@ -4,4 +4,8 @@ namespace Femto.Common.Domain;
public interface ICommand : IRequest;
public interface ICommand<out T> : IRequest<T>;
public interface ICommand<out TResult> : IRequest<TResult>;
public interface ICommandHandler<in TCommand> : IRequestHandler<TCommand> where TCommand : ICommand;
public interface ICommandHandler<in TCommand, TResult> : IRequestHandler<TCommand, TResult> where TCommand : ICommand<TResult>;

View file

@ -2,4 +2,6 @@ using MediatR;
namespace Femto.Common.Domain;
public interface IQuery<out T> : IRequest<T>;
public interface IQuery<out TResult> : IRequest<TResult>;
public interface IQueryHandler<in TQuery, TResult> : IRequestHandler<TQuery, TResult> where TQuery : IQuery<TResult>;

View file

@ -1,10 +1,9 @@
using Femto.Common.Domain;
using Femto.Modules.Authentication.Data;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Femto.Modules.Authentication.Application;
namespace Femto.Modules.Auth.Application;
internal class AuthenticationModule(IHost host) : IAuthenticationModule
{

View file

@ -1,12 +1,11 @@
using Femto.Common.Infrastructure;
using Femto.Common.Infrastructure.Outbox;
using Femto.Modules.Authentication.Data;
using Femto.Modules.Auth.Data;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Femto.Modules.Authentication.Application;
namespace Femto.Modules.Auth.Application;
public static class AuthenticationStartup
{
@ -20,7 +19,7 @@ public static class AuthenticationStartup
private static void ConfigureServices(IServiceCollection services, string connectionString)
{
services.AddDbContext<AuthenticationContext>(
services.AddDbContext<AuthContext>(
builder =>
{
builder.UseNpgsql(connectionString);
@ -29,7 +28,7 @@ public static class AuthenticationStartup
services.AddMediatR(c => c.RegisterServicesFromAssembly(typeof(AuthenticationStartup).Assembly));
services.AddDbContext<AuthenticationContext>(builder =>
services.AddDbContext<AuthContext>(builder =>
{
builder.UseNpgsql();
builder.UseSnakeCaseNamingConvention();

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

@ -1,6 +1,6 @@
using Femto.Common.Domain;
namespace Femto.Modules.Authentication.Application;
namespace Femto.Modules.Auth.Application;
public interface IAuthenticationModule
{

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

@ -1,9 +1,9 @@
using Femto.Modules.Authentication.Data;
using Femto.Modules.Authentication.Models;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Authentication.Contracts;
namespace Femto.Modules.Auth.Contracts;
internal class AuthenticationService(AuthenticationContext context) : IAuthenticationService
internal class AuthenticationService(AuthContext context) : IAuthenticationService
{
public async Task<UserInfo> Register(string username, string password)
{

View file

@ -1,4 +1,4 @@
namespace Femto.Modules.Authentication.Contracts;
namespace Femto.Modules.Auth.Contracts;
public interface IAuthenticationService
{

View file

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

View file

@ -1,16 +1,18 @@
using Femto.Common.Infrastructure.Outbox;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Authentication.Data;
namespace Femto.Modules.Auth.Data;
internal class AuthenticationContext : DbContext, IOutboxContext
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(AuthenticationContext).Assembly);
builder.ApplyConfigurationsFromAssembly(typeof(AuthContext).Assembly);
}
}

View file

@ -1,8 +1,8 @@
using Femto.Modules.Authentication.Models;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Femto.Modules.Authentication.Data.Configurations;
namespace Femto.Modules.Auth.Data.Configurations;
internal class UserIdentityTypeConfiguration : IEntityTypeConfiguration<UserIdentity>
{
@ -10,5 +10,6 @@ internal class UserIdentityTypeConfiguration : IEntityTypeConfiguration<UserIden
{
builder.ToTable("user_identity");
builder.OwnsOne(u => u.Password).WithOwner().HasForeignKey("user_id");
builder.OwnsMany(u => u.Sessions).WithOwner().HasForeignKey("user_id");
}
}

View file

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

View file

@ -1,10 +1,10 @@
using System.Text;
using System.Text.Unicode;
using Femto.Common.Domain;
using Femto.Modules.Authentication.Contracts;
using Femto.Modules.Authentication.Models.Events;
using Femto.Modules.Auth.Models.Events;
using Geralt;
namespace Femto.Modules.Authentication.Models;
namespace Femto.Modules.Auth.Models;
internal class UserIdentity : Entity
{
@ -14,10 +14,9 @@ internal class UserIdentity : Entity
public UserPassword Password { get; private set; }
private UserIdentity()
{
public ICollection<UserSession> Sessions { get; private set; }
}
private UserIdentity() { }
public UserIdentity(string username)
{
@ -35,17 +34,26 @@ internal class UserIdentity : Entity
public void SetPassword(string password)
{
var hash = new byte[128];
try
{
Argon2id.ComputeHash(hash, Encoding.UTF8.GetBytes(password), 3, 67108864);
}
catch (Exception e)
{
throw new SetPasswordError("Failed to hash password", e);
this.Password = new UserPassword(password);
}
this.Password = new UserPassword(this.Id, hash, new byte[128]);
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;
}
}

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
};
}
}

View file

@ -1,5 +0,0 @@
using Femto.Common.Domain;
namespace Femto.Modules.Authentication.Application.Commands;
public record LoginCommand(string Username, string Password) : ICommand<Guid>;

View file

@ -1,19 +0,0 @@
using Femto.Modules.Authentication.Data;
using Femto.Modules.Authentication.Models;
using MediatR;
namespace Femto.Modules.Authentication.Application.Commands;
internal class LoginCommandHandler(AuthenticationContext context) : IRequestHandler<LoginCommand, Guid>
{
public async Task<Guid> Handle(LoginCommand request, CancellationToken cancellationToken)
{
var user = new UserIdentity(request.Username);
user.SetPassword(request.Password);
await context.AddAsync(user, cancellationToken);
return user.Id;
}
}

View file

@ -1,19 +0,0 @@
namespace Femto.Modules.Authentication.Models;
internal class UserPassword
{
public Guid Id { get; private set; }
public byte[] Hash { get; private set; }
public byte[] Salt { get; private set; }
private UserPassword() {}
public UserPassword(Guid id, byte[] hash, byte[] salt)
{
Id = id;
Hash = hash;
Salt = salt;
}
}

View file

@ -12,7 +12,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Femto.Common", "Femto.Commo
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Femto.Modules.Media", "Femto.Modules.Media\Femto.Modules.Media.csproj", "{AC9FBF11-FF29-4A80-B9EA-AFDF1E3DCA80}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Femto.Modules.Authentication", "Femto.Modules.Authentication\Femto.Modules.Authentication.csproj", "{7E138EF6-E075-4896-93C0-923024F0CA78}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Femto.Modules.Auth", "Femto.Modules.Auth\Femto.Modules.Auth.csproj", "{7E138EF6-E075-4896-93C0-923024F0CA78}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution