Skip to content
This repository has been archived by the owner on Aug 30, 2024. It is now read-only.

Commit

Permalink
FEAT: Updating endpoint and adding new unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
fmattioli committed Jul 23, 2024
1 parent 3a9389d commit 5f423a8
Show file tree
Hide file tree
Showing 9 changed files with 113 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ public async Task<IActionResult> Login([FromRoute] string tenant, [FromBody] Log
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> RefreshToken([FromRoute] string tenant, [FromBody] string refreshToken, CancellationToken cancellationToken)
public async Task<IActionResult> RefreshToken([FromRoute] string tenant, [FromBody] RefreshTokenRequest request, CancellationToken cancellationToken)
{
var result = await _mediator.Send(new RefreshTokenCommand(tenant, refreshToken), cancellationToken);
var result = await _mediator.Send(new RefreshTokenCommand(tenant, request.RefreshToken), cancellationToken);

if (result.IsSuccess)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ public class RefreshTokenCommandHandler(IUserRepository userRepository) : IReque
public async Task<ResponseResult<TokenDetailsResponse>> Handle(RefreshTokenCommand request, CancellationToken cancellationToken)
{
var tokeDetails = await _userRepository.RefreshTokenAsync(request.Tenant, request.RefreshToken);
return tokeDetails.ToTokenResponse();
if (tokeDetails.IsSuccess)
{
return tokeDetails.ToTokenResponse();
}

return ResponseResult<TokenDetailsResponse>.Failure(tokeDetails.Error);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace TokenManager.Application.Services.Mappers
public static class UserMapper
{
public static User ToDomain(this AddUserRequest userRequest)
{
{
return new User(userRequest.Username!, userRequest.Password, userRequest.Email!, userRequest.FirstName!, userRequest.LastName!, userRequest.Attributes);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Newtonsoft.Json;

namespace TokenManager.Application.Services.Requests.User
namespace TokenManager.Application.Services.Requests.User
{
public record LoginUserRequest(string Username, string Password);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
namespace TokenManager.Application.Services.Requests.User
{
public record RefreshTokenRequest(string RefreshToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,6 @@ public T Result
{
get
{
if (!IsSuccess)
{
throw new InvalidOperationException("No value available for failure result.");
}

return _result;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public static class UserErrors
"User.InvalidUserNameOrPassword",
$"An error occurred while trying to get JWT token. Please check username and password. {TechnicalMessage}"
);

public static Error InvalidRefreshToken => new(
"User.InvalidRefreshTokenProvided",
$"An error occurred while trying to refresh token. {TechnicalMessage}"
);

public static Error WrongPasswordDefinition => new(
"User.WrongPasswordDefinition",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public async Task<Result<TokenDetails>> RefreshTokenAsync(string tenant, string

var responseMessage = await response.Content.ReadAsStringAsync();
UserErrors.SetTechnicalMessage(responseMessage);
return Result<TokenDetails>.Failure(UserErrors.InvalidUserNameOrPasswordError);
return Result<TokenDetails>.Failure(UserErrors.InvalidRefreshToken);
}

public async Task<(bool result, string content)> CreateNewUserAsync(string tenant, User user)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using AutoFixture;
using FluentAssertions;
using Moq;
using TokenManager.Application.Services.Commands.Users;
using TokenManager.Domain.Entities;
using TokenManager.Domain.Interfaces;

namespace TokenManager.UnitTests.Handlers
{
public class RefreshTokenCommandHandlerTests
{
private readonly Fixture _autoFixture = new();
private readonly Mock<IUserRepository> _userRepositoryMock = new();
private readonly RefreshTokenCommandHandler _refreshTokenCommandHandler;

public RefreshTokenCommandHandlerTests()
{
_refreshTokenCommandHandler = new(_userRepositoryMock.Object);
}

[Fact]
public async Task HandleWhenInformAValidToken_ShouldBeRefreshedTheToken()
{
// Arrange
var refreshTokenCommand = _autoFixture.Create<RefreshTokenCommand>();

var tokenDetails = _autoFixture.Create<TokenDetails>();
var successResult = Result<TokenDetails>.Success(tokenDetails);

_userRepositoryMock
.Setup(x => x.RefreshTokenAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(successResult);

//Act
var resultHandle = await _refreshTokenCommandHandler.Handle(refreshTokenCommand, CancellationToken.None);

//Assert
resultHandle.IsSuccess
.Should()
.Be(true);

resultHandle.Result.AccessToken
.Should()
.Be(tokenDetails.Access_Token);

resultHandle.Result.ExpiresIn
.Should()
.Be(tokenDetails.Expires_In);

resultHandle.Result.RefreshExpiresIn
.Should()
.Be(tokenDetails.Refresh_Expires_In);

resultHandle.Result.RefreshToken
.Should()
.Be(tokenDetails.Refresh_Token);

resultHandle.Result.TokenType
.Should()
.Be(tokenDetails.Token_Type);
}

[Fact]
public async Task HandleWhenInformAInvalidUser_ShouldNotBeLoggedAndShouldReturnsAnError()
{
// Arrange
var refreshTokenCommand = _autoFixture.Create<RefreshTokenCommand>();

var error = _autoFixture.Create<Error>();
var failureResult = Result<TokenDetails>.Failure(error);

_userRepositoryMock
.Setup(x => x.RefreshTokenAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(failureResult);

//Act
var resultHandle = await _refreshTokenCommandHandler.Handle(refreshTokenCommand, CancellationToken.None);

//Assert
resultHandle.IsSuccess
.Should()
.Be(false);

resultHandle.Error.Description
.Should()
.Contain(error.Description);

resultHandle.Error.Code
.Should()
.Contain(error.Code);
}
}
}

0 comments on commit 5f423a8

Please sign in to comment.