46 lines
1.4 KiB
C#
46 lines
1.4 KiB
C#
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<RefreshUserCommand, RefreshUserSessionResult>
|
|
{
|
|
public async Task<RefreshUserSessionResult> Handle(
|
|
RefreshUserCommand request,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
if (request.CurrentUser.Id != request.ForUser)
|
|
throw new DomainError("invalid request");
|
|
|
|
var user = await context.Users.SingleOrDefaultAsync(
|
|
u => u.Id == request.ForUser,
|
|
cancellationToken
|
|
);
|
|
|
|
if (user is null)
|
|
throw new DomainError("invalid request");
|
|
|
|
var session = await context.Sessions.SingleOrDefaultAsync(
|
|
s => s.Id == request.CurrentUser.SessionId && s.Expires > DateTimeOffset.UtcNow,
|
|
cancellationToken
|
|
);
|
|
|
|
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));
|
|
}
|
|
}
|