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,8 +1,10 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using Femto.Api.Sessions;
using Femto.Common;
using Femto.Modules.Auth.Application;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Application.Interface.ValidateSession;
using Femto.Modules.Auth.Errors;
using Microsoft.AspNetCore.Authentication;
@ -25,29 +27,42 @@ internal class SessionAuthenticationHandler(
if (string.IsNullOrWhiteSpace(sessionId))
return AuthenticateResult.NoResult();
var userJson = this.Request.Cookies["user"];
if (string.IsNullOrWhiteSpace(userJson))
return AuthenticateResult.Fail("Invalid user");
var user = JsonSerializer.Deserialize<UserInfo>(userJson);
if (user is null)
return AuthenticateResult.Fail("Invalid user");
var rememberMe = this.Request.Cookies["rememberme"];
try
{
var result = await authModule.Command(new ValidateSessionCommand(sessionId));
var result = await authModule.Command(
new ValidateSessionCommand(sessionId, user, rememberMe)
);
var claims = new List<Claim>
{
new(ClaimTypes.Name, result.User.Username),
new("sub", result.User.Id.ToString()),
new("user_id", result.User.Id.ToString()),
new(ClaimTypes.Name, user.Username),
new("sub", user.Id.ToString()),
new("user_id", user.Id.ToString()),
};
claims.AddRange(
result.User.Roles.Select(role => new Claim(ClaimTypes.Role, role.ToString()))
);
claims.AddRange(user.Roles.Select(role => new Claim(ClaimTypes.Role, role.ToString())));
var identity = new ClaimsIdentity(claims, this.Scheme.Name);
var principal = new ClaimsPrincipal(identity);
this.Context.SetSession(result.Session, result.User, Logger);
this.Context.SetSession(result.SessionDto, user, Logger);
currentUserContext.CurrentUser = new CurrentUser(
result.User.Id,
result.User.Username,
result.Session.SessionId
user.Id,
user.Username,
result.SessionDto.SessionId,
rememberMe
);
return AuthenticateResult.Success(