Skip to content

Commit

Permalink
Solved removing refresh token from the db ubon adding/requesting a ne…
Browse files Browse the repository at this point in the history
…w one
  • Loading branch information
moheladwy committed Jan 21, 2025
1 parent 05d6cf0 commit 744872e
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions server/src/Todo.Infrastructure/Services/AuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,19 +146,27 @@ public async Task<AuthResponse> LoginWithRefreshToken(string refreshToken)
if (string.IsNullOrEmpty(refreshToken))
throw new ArgumentNullException(nameof(refreshToken), "Refresh token cannot be null or empty");

var user = await _userManager.Users.FirstOrDefaultAsync(u => u.RefreshToken.Token == refreshToken);
var user = await _userManager.Users
.Include(u => u.RefreshToken)
.FirstOrDefaultAsync(u => u.RefreshToken.Token == refreshToken);

Check warning on line 151 in server/src/Todo.Infrastructure/Services/AuthenticationService.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 151 in server/src/Todo.Infrastructure/Services/AuthenticationService.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

if (user == null || user.RefreshToken?.ExpirationDate <= DateTime.UtcNow)
throw new UnauthorizedAccessException("Invalid refresh token");

var token = _tokenService.GenerateToken(user);
// Store the old refresh token ID
var oldRefreshTokenId = user.RefreshTokenId;
var accessToken = _tokenService.GenerateToken(user);
var newRefreshToken = _tokenService.GenerateRefreshToken();
newRefreshToken.UserId = user.Id;

var refreshTokenEntity = await _refreshTokenRepository.AddRefreshTokenAsync(newRefreshToken);
await UpdateUserRefreshToken(user, refreshTokenEntity);

// Delete old refresh token
if (oldRefreshTokenId.HasValue)
await _refreshTokenRepository.DeleteRefreshTokenAsync(oldRefreshTokenId.Value);

return GenerateAuthResponse(user, token, newRefreshToken);
return GenerateAuthResponse(user, accessToken, newRefreshToken);
}

private async Task UpdateUserRefreshToken(User user, RefreshToken refreshToken)
Expand Down

0 comments on commit 744872e

Please sign in to comment.