MyBookmark/Modules.User.Application/Commands/RefreshTokensCommand.cs
THE_KONDRAT 7b16d72329 ui and login
mongo => postgres
2024-11-03 16:08:39 +03:00

48 lines
2.0 KiB
C#

using MediatR;
using Modules.User.Application.Gateways;
using Modules.User.Application.Models;
namespace Modules.User.Application.Commands;
public class RefreshTokensCommand : IRequest<(string AccessToken, string RefreshToken)?>
{
public string RefreshToken { get; set; } = default!;
public string? Ip { get; set; }
}
public class RefreshTokensCommandHandler(UserContext userContext, IAccountGateway accountGateway,
IUserGateway userGateway, TokenGenerator tokenGenerator) : IRequestHandler<RefreshTokensCommand, (string AccessToken, string RefreshToken)?>
{
public async Task<(string AccessToken, string RefreshToken)?> Handle(RefreshTokensCommand request, CancellationToken cancellationToken)
{
var session = await accountGateway.TryGetSession(request.RefreshToken);
if (session == null) return null;
var user = await userGateway.Get(session.AccountId);
if (user == null) return null;
var userAgent = userContext.GetUserAgent();
var location = await userContext.GetLocation(request.Ip);
var newRefreshToken = user.Account.UpdateRefreshToken(session.Id, tokenGenerator, userAgent, location?.Country, location?.Region);
await accountGateway.UpdateSessions(user.Account.Id, user.Account.Sessions.Select(q => new Session
{
Id = q.Id,
RefreshToken = q.RefreshToken,
ClientInfo = new ClientInfo
{
UserAgent = userAgent,
Location = new Location
{
Country = location?.Country,
Region = location?.Region,
}
},
AccountId = q.AccountId,
ExpiredDate = q.ExpiredDate,
}));
if (newRefreshToken == null) return null;
var jwtSettings = userContext.GetJwtSettings();
return (tokenGenerator.GenerateAccessToken(user, user.Account.Sessions.First(q => q.Id == session.Id)!, jwtSettings), newRefreshToken);
}
}