Skip to content

Commit

Permalink
Optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
tinohager committed Jun 17, 2024
1 parent cf06059 commit 5cd81c1
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public async Task<ActionResult<AuthenticationResponseDto>> AuthenticateAsync(
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <response code="200">Authentication successful</response>
/// <response code="406">Invalid credential</response>
/// <response code="400">Invalid token</response>
/// <response code="500">Unexpected error</response>
[AllowAnonymous]
[HttpPost]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<TargetFrameworks>net8.0;net7.0;net6.0</TargetFrameworks>
<Nullable>enable</Nullable>

<Version>2.0.2</Version>
<Version>2.0.3</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/Nager.Authentication/Nager.Authentication.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<Nullable>enable</Nullable>
<TargetFrameworks>net8.0;net7.0;net6.0</TargetFrameworks>

<Version>2.0.2</Version>
<Version>2.0.3</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
19 changes: 18 additions & 1 deletion src/Nager.Authentication/Services/UserAuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,19 +251,31 @@ public async Task<ValidateTokenResult> ValidateTokenAsync(
var cacheKey = this.GetCacheKey(mfaIdentifier);
if (!this._memoryCache.TryGetValue<string>(cacheKey, out var emailAddress))
{
this._logger.LogError($"{nameof(ValidateTokenAsync)} - CacheKey {cacheKey} not found");

return new ValidateTokenResult
{
Success = false
};
}

this._memoryCache.Remove(cacheKey);
if (string.IsNullOrEmpty(emailAddress))
{
this._logger.LogError($"{nameof(ValidateTokenAsync)} - EmailAddress is empty");

return new ValidateTokenResult
{
Success = false
};
}

var timeTolerance = TimeSpan.FromSeconds(20);

var userEntity = await this._userRepository.GetAsync(o => o.EmailAddress == emailAddress);
if (userEntity == null)
{
this._logger.LogError($"{nameof(ValidateTokenAsync)} - No User available");

return new ValidateTokenResult
{
Success = false
Expand All @@ -273,6 +285,11 @@ public async Task<ValidateTokenResult> ValidateTokenAsync(
var twoFactorAuthenticator = new TwoFactorAuthenticator();
var isTokenValid = twoFactorAuthenticator.ValidateTwoFactorPIN(userEntity.MfaSecret, token, timeTolerance);

if (isTokenValid)
{
this._memoryCache.Remove(cacheKey);
}

return new ValidateTokenResult
{
Success = isTokenValid,
Expand Down

0 comments on commit 5cd81c1

Please sign in to comment.