wip session auth

This commit is contained in:
john 2025-05-29 00:39:40 +02:00
parent aa4394fd21
commit 7b6c155a73
23 changed files with 321 additions and 90 deletions

View file

@ -1,3 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record LoginResult(Session Session, UserInfo User);
public record LoginResult(SessionDto SessionDto, UserInfo User);

View file

@ -1,3 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record RefreshUserSessionResult(Session Session, UserInfo User);
public record RefreshUserSessionResult(SessionDto SessionDto, UserInfo User);

View file

@ -1,3 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record RegisterResult(Session Session, UserInfo User);
public record RegisterResult(SessionDto SessionDto, UserInfo User);

View file

@ -2,9 +2,16 @@ using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Application.Dto;
public record Session(string SessionId, DateTimeOffset Expires)
public record SessionDto(
string SessionId,
DateTimeOffset Expires,
bool Weak,
string? RememberMe = null
)
{
internal Session(UserSession session) : this(session.Id, session.Expires)
{
}
}
internal SessionDto(Session session)
: this(session.Id, session.Expires, !session.IsStronglyAuthenticated) { }
internal SessionDto(Session session, string? rememberMe)
: this(session.Id, session.Expires, !session.IsStronglyAuthenticated, rememberMe) { }
}

View file

@ -1,3 +1,3 @@
namespace Femto.Modules.Auth.Application.Dto;
public record ValidateSessionResult(Session Session, UserInfo User);
public record ValidateSessionResult(SessionDto SessionDto);

View file

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

View file

@ -0,0 +1,12 @@
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 +1,7 @@
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.Login;
@ -21,8 +22,10 @@ internal class LoginCommandHandler(AuthContext context)
if (!user.HasPassword(request.Password))
throw new DomainError("invalid credentials");
var session = user.StartNewSession();
return new(new Session(session.Id, session.Expires), new UserInfo(user));
var session = Session.Strong(user.Id);
await context.AddAsync(session, cancellationToken);
return new(new SessionDto(session), new UserInfo(user));
}
}

View file

@ -4,4 +4,4 @@ using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.RefreshUserSession;
public record RefreshUserSessionCommand(Guid ForUser, CurrentUser CurrentUser) : ICommand<RefreshUserSessionResult>;
public record RefreshUserCommand(Guid ForUser, CurrentUser CurrentUser) : ICommand<RefreshUserSessionResult>;

View file

@ -2,15 +2,17 @@ using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Errors;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.RefreshUserSession;
internal class RefreshUserSessionCommandHandler(AuthContext context)
: ICommandHandler<RefreshUserSessionCommand, RefreshUserSessionResult>
: ICommandHandler<RefreshUserCommand, RefreshUserSessionResult>
{
public async Task<RefreshUserSessionResult> Handle(
RefreshUserSessionCommand request,
RefreshUserCommand request,
CancellationToken cancellationToken
)
{
@ -25,8 +27,20 @@ internal class RefreshUserSessionCommandHandler(AuthContext context)
if (user is null)
throw new DomainError("invalid request");
var session = user.PossiblyRefreshSession(request.CurrentUser.SessionId);
var session = await context.Sessions.SingleOrDefaultAsync(
s => s.Id == request.CurrentUser.SessionId && s.Expires > DateTimeOffset.UtcNow,
cancellationToken
);
return new(new Session(session), new UserInfo(user));
if (session is null)
throw new InvalidSessionError();
if (session.ShouldRefresh)
{
session = Session.Weak(user.Id);
await context.AddAsync(session, cancellationToken);
}
return new(new SessionDto(session), new UserInfo(user));
}
}

View file

@ -6,30 +6,38 @@ using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.Register;
internal class RegisterCommandHandler(AuthContext context) : ICommandHandler<RegisterCommand, RegisterResult>
internal class RegisterCommandHandler(AuthContext context)
: ICommandHandler<RegisterCommand, RegisterResult>
{
public async Task<RegisterResult> Handle(RegisterCommand request, CancellationToken cancellationToken)
public async Task<RegisterResult> Handle(
RegisterCommand request,
CancellationToken cancellationToken
)
{
var now = DateTimeOffset.UtcNow;
var code = await context.SignupCodes
.Where(c => c.Code == request.SignupCode)
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 user = new UserIdentity(request.Username);
await context.AddAsync(user, cancellationToken);
user.SetPassword(request.Password);
var session = user.StartNewSession();
var session = Session.Strong(user.Id);
await context.AddAsync(user, cancellationToken);
await context.AddAsync(session, cancellationToken);
code.Redeem(user.Id);
return new(new Session(session.Id, session.Expires), new UserInfo(user));
return new(new SessionDto(session), new UserInfo(user));
}
}
}

View file

@ -7,4 +7,4 @@ namespace Femto.Modules.Auth.Application.Interface.ValidateSession;
/// Validate an existing session, and then return either the current session, or a new one in case the expiry is further in the future
/// </summary>
/// <param name="SessionId"></param>
public record ValidateSessionCommand(string SessionId) : ICommand<ValidateSessionResult>;
public record ValidateSessionCommand(string SessionId, UserInfo User, string? RememberMe) : ICommand<ValidateSessionResult>;

View file

@ -1,7 +1,9 @@
using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Errors;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.ValidateSession;
@ -13,22 +15,97 @@ internal class ValidateSessionCommandHandler(AuthContext context)
ValidateSessionCommand request,
CancellationToken cancellationToken
)
{
try
{
return new ValidateSessionResult(await DoSessionValidation(request, cancellationToken));
}
finally
{
await context.SaveChangesAsync(cancellationToken);
}
}
private async Task<SessionDto> DoSessionValidation(
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),
var session = await context.Sessions.SingleOrDefaultAsync(
s => s.Id == request.SessionId,
cancellationToken
);
if (user is null)
var rememberMe = request.RememberMe;
if (session is null)
{
(session, rememberMe) = await this.TryAuthenticateWithRememberMeToken(
request.User,
request.RememberMe,
cancellationToken
);
}
if (session.UserId != request.User.Id)
{
context.Remove(session);
throw new InvalidSessionError();
}
if (session.Expires < now)
{
context.Remove(session);
throw new InvalidSessionError();
}
if (session.ShouldRefresh)
{
context.Remove(session);
session = Session.Weak(session.UserId);
await context.AddAsync(session, cancellationToken);
}
return new SessionDto(session, rememberMe);
}
private async Task<(Session, string)> TryAuthenticateWithRememberMeToken(
UserInfo user,
string? rememberMeToken,
CancellationToken cancellationToken
)
{
if (rememberMeToken is null)
throw new InvalidSessionError();
var session = user.PossiblyRefreshSession(request.SessionId);
var parts = rememberMeToken.Split('.');
if (parts.Length != 2)
throw new InvalidSessionError();
return new ValidateSessionResult(
new Session(session.Id, session.Expires),
new UserInfo(user)
var selector = parts[0];
var verifier = parts[1];
var longTermSession = await context.LongTermSessions.SingleOrDefaultAsync(
s => s.Selector == selector,
cancellationToken
);
if (longTermSession is null)
throw new InvalidSessionError();
context.Remove(longTermSession);
if (!longTermSession.Validate(verifier))
throw new InvalidSessionError();
var session = Session.Weak(user.Id);
await context.AddAsync(session, cancellationToken);
(longTermSession, rememberMeToken) = LongTermSession.Create(user.Id);
await context.AddAsync(longTermSession, cancellationToken);
return (session, rememberMeToken);
}
}

View file

@ -7,7 +7,9 @@ namespace Femto.Modules.Auth.Data;
internal class AuthContext(DbContextOptions<AuthContext> options) : DbContext(options), IOutboxContext
{
public virtual DbSet<UserIdentity> Users { get; set; }
public virtual DbSet<Session> Sessions { get; set; }
public virtual DbSet<SignupCode> SignupCodes { get; set; }
public virtual DbSet<LongTermSession> LongTermSessions { get; set; }
public virtual DbSet<OutboxEntry> Outbox { get; set; }
protected override void OnModelCreating(ModelBuilder builder)

View file

@ -0,0 +1,51 @@
using System.Text;
using static System.Security.Cryptography.RandomNumberGenerator;
namespace Femto.Modules.Auth.Models;
public class LongTermSession
{
private static TimeSpan TokenTimeout { get; } = TimeSpan.FromDays(90);
public int Id { get; private set; }
public string Selector { get; private set; }
public byte[] HashedVerifier { get; private set; }
public DateTimeOffset Expires { get; private set; }
public Guid UserId { get; private set; }
private LongTermSession() {}
public static (LongTermSession, string) Create(Guid userId)
{
var selector = GetString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 12);
var verifier = GetString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 32);
using var sha256 = System.Security.Cryptography.SHA256.Create();
var longTermSession = new LongTermSession
{
Selector = selector,
HashedVerifier = sha256.ComputeHash(Encoding.UTF8.GetBytes(verifier)),
UserId = userId,
Expires = DateTimeOffset.UtcNow + TokenTimeout
};
var rememberMeToken = $"{selector}.{verifier}";
return (longTermSession, rememberMeToken);
}
public bool Validate(string verifier)
{
if (this.Expires < DateTimeOffset.UtcNow)
return false;
using var sha256 = System.Security.Cryptography.SHA256.Create();
var hashedVerifier = sha256.ComputeHash(Encoding.UTF8.GetBytes(verifier));
return hashedVerifier.SequenceEqual(this.HashedVerifier);
}
}

View file

@ -15,7 +15,7 @@ internal class UserIdentity : Entity
public Password? Password { get; private set; }
public ICollection<UserSession> Sessions { get; private set; } = [];
public ICollection<Session> Sessions { get; private set; } = [];
public ICollection<UserRole> Roles { get; private set; } = [];
@ -31,12 +31,6 @@ internal class UserIdentity : Entity
this.AddDomainEvent(new UserWasCreatedEvent(this));
}
public UserIdentity WithPassword(string password)
{
this.SetPassword(password);
return this;
}
public void SetPassword(string password)
{
this.Password = new Password(password);
@ -51,25 +45,6 @@ internal class UserIdentity : Entity
return this.Password.Check(requestPassword);
}
public UserSession PossiblyRefreshSession(string sessionId)
{
var session = this.Sessions.Single(s => s.Id == sessionId);
if (session.ExpiresSoon)
return this.StartNewSession();
return session;
}
public UserSession StartNewSession()
{
var session = UserSession.Create();
this.Sessions.Add(session);
return session;
}
}
public class SetPasswordError(string message, Exception inner) : DomainError(message, inner);

View file

@ -1,21 +1,33 @@
using static System.Security.Cryptography.RandomNumberGenerator;
namespace Femto.Modules.Auth.Models;
internal class UserSession
internal class Session
{
private static TimeSpan SessionTimeout { get; } = TimeSpan.FromMinutes(30);
private static TimeSpan ExpiryBuffer { get; } = TimeSpan.FromMinutes(5);
public string Id { get; private set; }
public Guid UserId { get; private set; }
public DateTimeOffset Expires { get; private set; }
public bool ExpiresSoon => Expires < DateTimeOffset.UtcNow + ExpiryBuffer;
private UserSession() {}
public static UserSession Create()
// true if this session was created with remember me token
// otherwise false
// required to be true to do things like change password etc.
public bool IsStronglyAuthenticated { get; private set; }
public bool ShouldRefresh => this.Expires < DateTimeOffset.UtcNow + ExpiryBuffer;
private Session() { }
public static Session Strong(Guid userId) => new(userId, true);
public static Session Weak(Guid userId) => new(userId, false);
private Session(Guid userId, bool isStrong)
{
return new()
{
Id = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)),
Expires = DateTimeOffset.UtcNow + SessionTimeout
};
this.Id = Convert.ToBase64String(GetBytes(32));
this.UserId = userId;
this.Expires = DateTimeOffset.UtcNow + SessionTimeout;
this.IsStronglyAuthenticated = isStrong;
}
}
}