This commit is contained in:
john 2025-06-16 21:11:40 +02:00
parent e282e2ece3
commit 84457413b2
20 changed files with 224 additions and 246 deletions

View file

@ -1,24 +1,16 @@
using Femto.Api.Auth;
using Femto.Api.Sessions; using Femto.Api.Sessions;
using Femto.Common; using Femto.Common;
using Femto.Modules.Auth.Application.Interface.CreateSignupCode;
using Femto.Modules.Auth.Application.Interface.GetSignupCodesQuery;
using Femto.Modules.Auth.Application.Interface.Register;
using Femto.Modules.Auth.Application.Services; using Femto.Modules.Auth.Application.Services;
using Femto.Modules.Auth.Contracts; using Femto.Modules.Auth.Contracts;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace Femto.Api.Controllers.Auth; namespace Femto.Api.Controllers.Auth;
[ApiController] [ApiController]
[Route("auth")] [Route("auth")]
public class AuthController( public class AuthController(
IAuthModule authModule,
IOptions<CookieSettings> cookieSettings,
ICurrentUserContext currentUserContext, ICurrentUserContext currentUserContext,
ILogger<AuthController> logger,
IAuthService authService IAuthService authService
) : ControllerBase ) : ControllerBase
{ {
@ -28,17 +20,17 @@ public class AuthController(
CancellationToken cancellationToken CancellationToken cancellationToken
) )
{ {
var user = await authService.GetUserWithCredentials( var result = await authService.GetUserWithCredentials(
request.Username, request.Username,
request.Password, request.Password,
cancellationToken cancellationToken
); );
if (user is null) if (result is null)
return this.BadRequest(); return this.BadRequest();
var session = await authService.CreateStrongSession(user.Id); var (user, session) = result;
HttpContext.SetSession(session, user); HttpContext.SetSession(session, user);
return new LoginResponse(user.Id, user.Username, user.Roles.Any(r => r == Role.SuperUser)); return new LoginResponse(user.Id, user.Username, user.Roles.Any(r => r == Role.SuperUser));
@ -47,13 +39,10 @@ public class AuthController(
[HttpPost("register")] [HttpPost("register")]
public async Task<ActionResult<RegisterResponse>> Register([FromBody] RegisterRequest request) public async Task<ActionResult<RegisterResponse>> Register([FromBody] RegisterRequest request)
{ {
var user = await authModule.Command( var (user, session) = await authService.CreateUserWithCredentials(request.Username, request.Password, request.SignupCode);
new RegisterCommand(request.Username, request.Password, request.SignupCode)
);
var session = await authService.CreateStrongSession(user.Id);
HttpContext.SetSession(session, user); HttpContext.SetSession(session, user);
return new RegisterResponse( return new RegisterResponse(
user.Id, user.Id,
user.Username, user.Username,
@ -106,10 +95,7 @@ public class AuthController(
CancellationToken cancellationToken CancellationToken cancellationToken
) )
{ {
await authModule.Command( await authService.AddSignupCode(request.Code, request.Name, cancellationToken);
new CreateSignupCodeCommand(request.Code, request.Email, request.Name),
cancellationToken
);
return Ok(new { }); return Ok(new { });
} }
@ -120,7 +106,7 @@ public class AuthController(
CancellationToken cancellationToken CancellationToken cancellationToken
) )
{ {
var codes = await authModule.Query(new GetSignupCodesQuery(), cancellationToken); var codes = await authService.GetSignupCodes(cancellationToken);
return new ListSignupCodesResult( return new ListSignupCodesResult(
codes.Select(c => new SignupCodeDto( codes.Select(c => new SignupCodeDto(

View file

@ -5,10 +5,10 @@ using Microsoft.Extensions.Logging;
namespace Femto.Common.Infrastructure; namespace Femto.Common.Infrastructure;
public class SaveChangesPipelineBehaviour<TRequest, TResponse>( public class DDDPipelineBehaviour<TRequest, TResponse>(
DbContext context, DbContext context,
IPublisher publisher, IPublisher publisher,
ILogger<SaveChangesPipelineBehaviour<TRequest, TResponse>> logger ILogger<DDDPipelineBehaviour<TRequest, TResponse>> logger
) : IPipelineBehavior<TRequest, TResponse> ) : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull where TRequest : notnull
{ {

View file

@ -12,7 +12,7 @@ public static class DomainServiceExtensions
services.AddScoped<DbContext>(s => s.GetRequiredService<TContext>()); services.AddScoped<DbContext>(s => s.GetRequiredService<TContext>());
services.AddTransient( services.AddTransient(
typeof(IPipelineBehavior<,>), typeof(IPipelineBehavior<,>),
typeof(SaveChangesPipelineBehaviour<,>) typeof(DDDPipelineBehaviour<,>)
); );
} }

View file

@ -41,7 +41,6 @@ public static class AuthStartup
} }
); );
rootContainer.ExposeScopedService<IAuthModule>();
rootContainer.ExposeScopedService<IAuthService>(); rootContainer.ExposeScopedService<IAuthService>();
rootContainer.AddHostedService(services => new AuthApplication(host)); rootContainer.AddHostedService(services => new AuthApplication(host));
@ -85,8 +84,12 @@ public static class AuthStartup
services.AddSingleton(publisher); services.AddSingleton(publisher);
services.AddSingleton<SessionStorage>(); services.AddSingleton<SessionStorage>();
services.AddScoped(
typeof(IPipelineBehavior<,>),
typeof(SaveChangesPipelineBehaviour<,>)
);
services.AddScoped<IAuthModule, AuthModule>();
services.AddScoped<IAuthService, AuthService>(); services.AddScoped<IAuthService, AuthService>();
} }

View file

@ -1,5 +0,0 @@
using Femto.Common.Domain;
namespace Femto.Modules.Auth.Application.Interface.CreateSignupCode;
public record CreateSignupCodeCommand(string Code, string RecipientEmail, string RecipientName): ICommand;

View file

@ -1,15 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Application.Interface.CreateSignupCode;
internal class CreateSignupCodeCommandHandler(AuthContext context) : ICommandHandler<CreateSignupCodeCommand>
{
public async Task Handle(CreateSignupCodeCommand command, CancellationToken cancellationToken)
{
var code = new SignupCode(command.RecipientEmail, command.RecipientName, command.Code);
await context.SignupCodes.AddAsync(code, cancellationToken);
}
}

View file

@ -1,6 +0,0 @@
using Femto.Common.Domain;
namespace Femto.Modules.Auth.Application.Interface.Deauthenticate;
public record DeauthenticateCommand(Guid UserId, string SessionId, string? RememberMeToken) : ICommand;

View file

@ -1,12 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Data;
namespace Femto.Modules.Auth.Application.Interface.Deauthenticate;
internal class DeauthenticateCommandHandler(AuthContext context) : ICommandHandler<DeauthenticateCommand>
{
public async Task Handle(DeauthenticateCommand request, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}

View file

@ -1,6 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.GetSignupCodesQuery;
public record GetSignupCodesQuery: IQuery<ICollection<SignupCodeDto>>;

View file

@ -1,55 +0,0 @@
using Dapper;
using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.GetSignupCodesQuery;
public class GetSignupCodesQueryHandler(IDbConnectionFactory connectionFactory)
: IQueryHandler<GetSignupCodesQuery, ICollection<SignupCodeDto>>
{
public async Task<ICollection<SignupCodeDto>> Handle(
GetSignupCodesQuery request,
CancellationToken cancellationToken
)
{
using var conn = connectionFactory.GetConnection();
// lang=sql
const string sql = """
SELECT
sc.code as Code,
sc.recipient_email as Email,
sc.recipient_name as Name,
sc.redeeming_user_id as RedeemedByUserId,
u.username as RedeemedByUsername,
sc.expires_at as ExpiresOn
FROM authn.signup_code sc
LEFT JOIN authn.user_identity u ON u.id = sc.redeeming_user_id
ORDER BY sc.created_at DESC
""";
var result = await conn.QueryAsync<QueryResultRow>(sql);
return result
.Select(row => new SignupCodeDto(
row.Code,
row.Email,
row.Name,
row.RedeemedByUserId,
row.RedeemedByUsername,
row.ExpiresOn
))
.ToList();
}
private class QueryResultRow
{
public string Code { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public Guid? RedeemedByUserId { get; set; }
public string? RedeemedByUsername { get; set; }
public DateTimeOffset? ExpiresOn { get; set; }
}
}

View file

@ -1,6 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.GetUserInfo;
public record GetUserInfoCommand(Guid ForUser) : ICommand<UserInfo?>;

View file

@ -1,27 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.GetUserInfo;
internal class GetUserInfoCommandHandler(AuthContext context)
: ICommandHandler<GetUserInfoCommand, UserInfo?>
{
public async Task<UserInfo?> Handle(
GetUserInfoCommand request,
CancellationToken cancellationToken
)
{
var user = await context.Users.SingleOrDefaultAsync(
u => u.Id == request.ForUser,
cancellationToken
);
if (user is null)
return null;
return new UserInfo(user);
}
}

View file

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

View file

@ -1,43 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.Register;
internal class RegisterCommandHandler(AuthContext context)
: ICommandHandler<RegisterCommand, UserInfo>
{
public async Task<UserInfo> Handle(RegisterCommand request, CancellationToken cancellationToken)
{
var now = DateTimeOffset.UtcNow;
var code = await context
.SignupCodes.Where(c => c.Code == request.SignupCode)
.Where(c => c.ExpiresAt == null || c.ExpiresAt > now)
.Where(c => c.RedeemingUserId == null)
.SingleOrDefaultAsync(cancellationToken);
if (code is null)
throw new DomainError("invalid signup code");
var usernameTaken = await context.Users.AnyAsync(
u => u.Username == request.Username,
cancellationToken
);
if (usernameTaken)
throw new DomainError("username taken");
var user = new UserIdentity(request.Username);
await context.AddAsync(user, cancellationToken);
user.SetPassword(request.Password);
code.Redeem(user.Id);
return new UserInfo(user);
}
}

View file

@ -1,20 +0,0 @@
using Femto.Common.Domain;
using MediatR;
namespace Femto.Modules.Auth.Application.Services;
internal class AuthModule(IMediator mediator) : IAuthModule
{
public async Task Command(ICommand command, CancellationToken cancellationToken = default) =>
await mediator.Send(command, cancellationToken);
public async Task<TResponse> Command<TResponse>(
ICommand<TResponse> command,
CancellationToken cancellationToken = default
) => await mediator.Send(command, cancellationToken);
public async Task<TResponse> Query<TResponse>(
IQuery<TResponse> query,
CancellationToken cancellationToken = default
) => await mediator.Send(query, cancellationToken);
}

View file

@ -1,4 +1,6 @@
using Dapper;
using Femto.Common.Domain; using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto; using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data; using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Infrastructure; using Femto.Modules.Auth.Infrastructure;
@ -7,9 +9,13 @@ using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Services; namespace Femto.Modules.Auth.Application.Services;
internal class AuthService(AuthContext context, SessionStorage storage) : IAuthService internal class AuthService(
AuthContext context,
SessionStorage storage,
IDbConnectionFactory connectionFactory
) : IAuthService
{ {
public async Task<UserInfo?> GetUserWithCredentials( public async Task<UserAndSession?> GetUserWithCredentials(
string username, string username,
string password, string password,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@ -18,14 +24,21 @@ internal class AuthService(AuthContext context, SessionStorage storage) : IAuthS
var user = await context var user = await context
.Users.Where(u => u.Username == username) .Users.Where(u => u.Username == username)
.SingleOrDefaultAsync(cancellationToken); .SingleOrDefaultAsync(cancellationToken);
if (user is null) if (user is null)
return null; return null;
if (!user.HasPassword(password)) if (!user.HasPassword(password))
return null; return null;
return new UserInfo(user.Id, user.Username, user.Roles.Select(r => r.Role).ToList()); var session = new Session(user.Id, true);
await storage.AddSession(session);
return new(
new UserInfo(user.Id, user.Username, user.Roles.Select(r => r.Role).ToList()),
session
);
} }
public Task<UserInfo?> GetUserWithId(Guid? userId, CancellationToken cancellationToken) public Task<UserInfo?> GetUserWithId(Guid? userId, CancellationToken cancellationToken)
@ -64,6 +77,97 @@ internal class AuthService(AuthContext context, SessionStorage storage) : IAuthS
await storage.DeleteSession(sessionId); await storage.DeleteSession(sessionId);
} }
public async Task<UserAndSession> CreateUserWithCredentials(
string username,
string password,
string signupCode,
CancellationToken cancellationToken = default
)
{
var now = DateTimeOffset.UtcNow;
var code = await context
.SignupCodes.Where(c => c.Code == signupCode)
.Where(c => c.ExpiresAt == null || c.ExpiresAt > now)
.Where(c => c.RedeemingUserId == null)
.SingleOrDefaultAsync(cancellationToken);
if (code is null)
throw new DomainError("invalid signup code");
var usernameTaken = await context.Users.AnyAsync(
u => u.Username == username,
cancellationToken
);
if (usernameTaken)
throw new DomainError("username taken");
var user = new UserIdentity(username);
await context.AddAsync(user, cancellationToken);
user.SetPassword(password);
code.Redeem(user.Id);
var session = new Session(user.Id, true);
await storage.AddSession(session);
await context.SaveChangesAsync(cancellationToken);
return new(new UserInfo(user), session);
}
public async Task AddSignupCode(
string code,
string recipientName,
CancellationToken cancellationToken
)
{
await context.SignupCodes.AddAsync(
new SignupCode("", recipientName, code),
cancellationToken
);
await context.SaveChangesAsync(cancellationToken);
}
public async Task<ICollection<SignupCodeDto>> GetSignupCodes(
CancellationToken cancellationToken = default
)
{
using var conn = connectionFactory.GetConnection();
// lang=sql
const string sql = """
SELECT
sc.code as Code,
sc.recipient_email as Email,
sc.recipient_name as Name,
sc.redeeming_user_id as RedeemedByUserId,
u.username as RedeemedByUsername,
sc.expires_at as ExpiresOn
FROM authn.signup_code sc
LEFT JOIN authn.user_identity u ON u.id = sc.redeeming_user_id
ORDER BY sc.created_at DESC
""";
var result = await conn.QueryAsync<GetSignupCodesQueryResultRow>(sql, cancellationToken);
return result
.Select(row => new SignupCodeDto(
row.Code,
row.Email,
row.Name,
row.RedeemedByUserId,
row.RedeemedByUsername,
row.ExpiresOn
))
.ToList();
}
public async Task<LongTermSession> CreateLongTermSession(Guid userId, bool isStrong) public async Task<LongTermSession> CreateLongTermSession(Guid userId, bool isStrong)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
@ -83,4 +187,14 @@ internal class AuthService(AuthContext context, SessionStorage storage) : IAuthS
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
private class GetSignupCodesQueryResultRow
{
public string Code { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public Guid? RedeemedByUserId { get; set; }
public string? RedeemedByUsername { get; set; }
public DateTimeOffset? ExpiresOn { get; set; }
}
} }

View file

@ -1,10 +0,0 @@
using Femto.Common.Domain;
namespace Femto.Modules.Auth.Application.Services;
public interface IAuthModule
{
Task Command(ICommand command, CancellationToken cancellationToken = default);
Task<TResponse> Command<TResponse>(ICommand<TResponse> command, CancellationToken cancellationToken = default);
Task<TResponse> Query<TResponse>(IQuery<TResponse> query, CancellationToken cancellationToken = default);
}

View file

@ -11,10 +11,30 @@ namespace Femto.Modules.Auth.Application.Services;
/// </summary> /// </summary>
public interface IAuthService public interface IAuthService
{ {
public Task<UserInfo?> GetUserWithCredentials(string username, string password, CancellationToken cancellationToken = default); public Task<UserAndSession?> GetUserWithCredentials(
public Task<UserInfo?> GetUserWithId(Guid? userId, CancellationToken cancellationToken = default); string username,
string password,
CancellationToken cancellationToken = default
);
public Task<UserInfo?> GetUserWithId(
Guid? userId,
CancellationToken cancellationToken = default
);
public Task<Session> CreateStrongSession(Guid userId); public Task<Session> CreateStrongSession(Guid userId);
public Task<Session> CreateWeakSession(Guid userId); public Task<Session> CreateWeakSession(Guid userId);
public Task<Session?> GetSession(string sessionId); public Task<Session?> GetSession(string sessionId);
public Task DeleteSession(string sessionId); public Task DeleteSession(string sessionId);
}
public Task<UserAndSession> CreateUserWithCredentials(
string username,
string password,
string signupCode,
CancellationToken cancellationToken = default
);
public Task AddSignupCode(string code, string recipientName, CancellationToken cancellationToken = default);
public Task<ICollection<SignupCodeDto>> GetSignupCodes(CancellationToken cancellationToken = default);
}
public record UserAndSession(UserInfo User, Session Session);

View file

@ -1,6 +1,10 @@
using Femto.Common.Domain;
using Femto.Common.Infrastructure.Outbox; using Femto.Common.Infrastructure.Outbox;
using Femto.Modules.Auth.Models; using Femto.Modules.Auth.Models;
using MediatR;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Logging;
namespace Femto.Modules.Auth.Data; namespace Femto.Modules.Auth.Data;
@ -17,4 +21,43 @@ internal class AuthContext(DbContextOptions<AuthContext> options) : DbContext(op
builder.HasDefaultSchema("authn"); builder.HasDefaultSchema("authn");
builder.ApplyConfigurationsFromAssembly(typeof(AuthContext).Assembly); builder.ApplyConfigurationsFromAssembly(typeof(AuthContext).Assembly);
} }
public override int SaveChanges()
{
throw new InvalidOperationException("Use SaveChangesAsync instead");
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
await EmitDomainEvents(cancellationToken);
return await base.SaveChangesAsync(cancellationToken);
}
private async Task EmitDomainEvents(CancellationToken cancellationToken)
{
var logger = this.GetService<ILogger<AuthContext>>();
var publisher = this.GetService<IPublisher>();
var domainEvents = this
.ChangeTracker.Entries<Entity>()
.SelectMany(e =>
{
var events = e.Entity.DomainEvents;
e.Entity.ClearDomainEvents();
return events;
})
.ToList();
logger.LogTrace("loaded {Count} domain events", domainEvents.Count);
foreach (var domainEvent in domainEvents)
{
logger.LogTrace(
"publishing {Type} domain event {Id}",
domainEvent.GetType().Name,
domainEvent.EventId
);
await publisher.Publish(domainEvent, cancellationToken);
}
}
} }

View file

@ -0,0 +1,23 @@
using Femto.Modules.Auth.Data;
using MediatR;
namespace Femto.Modules.Auth.Infrastructure;
internal class SaveChangesPipelineBehaviour<TRequest, TResponse>(AuthContext context)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken
)
{
var response = await next(cancellationToken);
if (context.ChangeTracker.HasChanges())
await context.SaveChangesAsync(cancellationToken);
return response;
}
}