MyBookmark/Modules.User.Application/Commands/User/Session/DeleteCurrentSessionCommand.cs

35 lines
1.4 KiB
C#

using MediatR;
using Modules.User.Application.Gateways;
namespace Modules.User.Application.Commands.Session;
public class DeleteCurrentSessionCommand : IRequest<bool>
{
}
public class DeleteCurrentSessionCommandHandler(UserContext userContext, IUserRepository userRepository,
IUnitOfWork unitOfWork) : IRequestHandler<DeleteCurrentSessionCommand, bool>
{
public async Task<bool> Handle(DeleteCurrentSessionCommand request, CancellationToken cancellationToken)
{
var accountId = userContext.GetAccountId();
if (!accountId.HasValue) return false;
//TODO: if (!accountId.HasValue) throw new UnauthorizedAccessException("AccountId not found");
var user = await userRepository.GetByAccountIdAsync(accountId.Value, cancellationToken);
if (user == null) return false;
//TODO: if (user == null) throw new UserNotFoundException(); //"User not found"
var sessionId = userContext.GetSessionId();
if (!sessionId.HasValue) return false;
//TODO: if (!sessionId.HasValue) throw new Exception("Active session not found");
var success = user.DeleteSession(sessionId.Value);
if (!success) return false;
//TODO: if (!success) throw new Exception("Session not found");
await userRepository.SaveAsync(user, cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken);
return true;
}
}