Skip to content

Commit

Permalink
fix: #dev async fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
marcinbator committed Nov 23, 2024
1 parent 998c5ef commit 5ab8bf9
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 45 deletions.
9 changes: 5 additions & 4 deletions rag-2-backend/Infrastructure/Module/Auth/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public async Task<UserLoginResponse> LoginUser(string email, string password, do
if (user.Banned)
throw new UnauthorizedException("User banned");

var refreshToken = GenerateRefreshToken(refreshTokenExpirationTimeDays, user);
var refreshToken = await GenerateRefreshToken(refreshTokenExpirationTimeDays, user);

return new UserLoginResponse
{
Expand Down Expand Up @@ -64,16 +64,17 @@ public async Task LogoutUser(string token)

//

private RefreshToken GenerateRefreshToken(double refreshTokenExpirationTimeDays, Database.Entity.User user)
private async Task<RefreshToken> GenerateRefreshToken(double refreshTokenExpirationTimeDays,
Database.Entity.User user)
{
var refreshToken = new RefreshToken
{
User = user,
Expiration = DateTime.Now.AddDays(refreshTokenExpirationTimeDays),
Token = Guid.NewGuid().ToString()
};
databaseContext.RefreshTokens.Add(refreshToken);
databaseContext.SaveChanges();
await databaseContext.RefreshTokens.AddAsync(refreshToken);
await databaseContext.SaveChangesAsync();
return refreshToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,23 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)

while (!cancellationToken.IsCancellationRequested)
{
DeleteUnusedAccountTokens();
DeleteUnusedRefreshTokens();
DeleteUnusedPasswordResetTokens();
UpdateCachedStats();
await DeleteUnusedAccountTokens();
await DeleteUnusedRefreshTokens();
await DeleteUnusedPasswordResetTokens();
await UpdateCachedStats();

await Task.Delay(TimeSpan.FromHours(3), cancellationToken);
}
}

//

private void DeleteUnusedAccountTokens()
private async Task DeleteUnusedAccountTokens()
{
var unconfirmedUsers = new List<Database.Entity.User>();
var unusedTokens = _dbContext.AccountConfirmationTokens
var unusedTokens = await _dbContext.AccountConfirmationTokens
.Include(t => t.User)
.Where(t => t.Expiration < DateTime.Now).ToList();
.Where(t => t.Expiration < DateTime.Now).ToListAsync();

foreach (var users in unusedTokens.Select(token =>
new List<Database.Entity.User>(_dbContext.Users.Where(u =>
Expand All @@ -48,30 +48,30 @@ private void DeleteUnusedAccountTokens()

_dbContext.Users.RemoveRange(unconfirmedUsers);
_dbContext.AccountConfirmationTokens.RemoveRange(unusedTokens);
_dbContext.SaveChanges();
await _dbContext.SaveChangesAsync();

Console.WriteLine("Deleted " + unconfirmedUsers.Count + " unconfirmed accounts with tokens");
}

private void DeleteUnusedRefreshTokens()
private async Task DeleteUnusedRefreshTokens()
{
var unusedTokens = _dbContext.RefreshTokens.Where(b => b.Expiration < DateTime.Now).ToList();
_dbContext.RefreshTokens.RemoveRange(unusedTokens);
_dbContext.SaveChanges();
await _dbContext.SaveChangesAsync();

Console.WriteLine("Deleted " + unusedTokens.Count + " expired refresh tokens");
}

private void DeleteUnusedPasswordResetTokens()
private async Task DeleteUnusedPasswordResetTokens()
{
var unusedTokens = _dbContext.PasswordResetTokens.Where(b => b.Expiration < DateTime.Now).ToList();
_dbContext.PasswordResetTokens.RemoveRange(unusedTokens);
_dbContext.SaveChanges();
await _dbContext.SaveChangesAsync();

Console.WriteLine("Deleted " + unusedTokens.Count + " expired password reset tokens");
}

private async void UpdateCachedStats()
private async Task UpdateCachedStats()
{
var games = await _dbContext.Games.ToListAsync();
foreach (var game in games) await _statsUtil.UpdateCachedGameStats(game);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task AddCourse(CourseRequest request)
Name = request.Name
};

context.Courses.Add(course);
await context.Courses.AddAsync(course);
await context.SaveChangesAsync();
}

Expand Down
12 changes: 6 additions & 6 deletions rag-2-backend/Infrastructure/Module/Game/GameController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,27 @@ public async Task<IEnumerable<GameResponse>> GetGames()
/// <response code="400">Game with this name already exists</response>
[HttpPost]
[Authorize(Roles = "Admin")]
public void Add([FromBody] [Required] GameRequest request)
public async Task Add([FromBody] [Required] GameRequest request)
{
gameService.AddGame(request);
await gameService.AddGame(request);
}

/// <summary>Edit existing game (Admin)</summary>
/// <response code="404">Game not found</response>
/// <response code="400">Game with this name already exists</response>
[HttpPut("{id:int}")]
[Authorize(Roles = "Admin")]
public void Edit([FromBody] [Required] GameRequest request, int id)
public async Task Edit([FromBody] [Required] GameRequest request, int id)
{
gameService.EditGame(request, id);
await gameService.EditGame(request, id);
}

/// <summary>Remove existing game (Admin)</summary>
/// <response code="404">Game not found</response>
[HttpDelete("{id:int}")]
[Authorize(Roles = "Admin")]
public void Remove([Required] int id)
public async Task Remove([Required] int id)
{
gameService.RemoveGame(id);
await gameService.RemoveGame(id);
}
}
2 changes: 1 addition & 1 deletion rag-2-backend/Infrastructure/Module/Game/GameService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public async Task AddGame(GameRequest request)
Description = request.Description
};

context.Games.Add(game);
await context.Games.AddAsync(game);
await context.SaveChangesAsync();
}

Expand Down
32 changes: 16 additions & 16 deletions rag-2-backend/Infrastructure/Module/User/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,69 +17,69 @@ public class UserController(UserService userService) : ControllerBase
/// <summary>Register new user</summary>
/// <response code="400">User already exists or wrong data</response>
[HttpPost("register")]
public void Register([FromBody] [Required] UserRequest userRequest)
public async Task Register([FromBody] [Required] UserRequest userRequest)
{
userService.RegisterUser(userRequest);
await userService.RegisterUser(userRequest);
}

/// <summary>Resend confirmation email to specified email</summary>
/// <response code="404">User not found</response>
/// <response code="400">User is already confirmed</response>
[HttpPost("resend-confirmation-email")]
public void ResendConfirmationEmail([Required] string email)
public async Task ResendConfirmationEmail([Required] string email)
{
userService.ResendConfirmationEmail(email);
await userService.ResendConfirmationEmail(email);
}

/// <summary>Confirm account with token from mail</summary>
/// <response code="400">Invalid token</response>
[HttpPost("confirm-account")]
public void ConfirmAccount([Required] string token)
public async Task ConfirmAccount([Required] string token)
{
userService.ConfirmAccount(token);
await userService.ConfirmAccount(token);
}

/// <summary>Edit account info (Auth)</summary>
/// <response code="400">Wrong data</response>
[HttpPatch("update")]
[Authorize]
public void UpdateAccount([Required] UserEditRequest request)
public async Task UpdateAccount([Required] UserEditRequest request)
{
userService.UpdateAccount(request, AuthDao.GetPrincipalEmail(User));
await userService.UpdateAccount(request, AuthDao.GetPrincipalEmail(User));
}

/// <summary>Request password reset for given email</summary>
[HttpPost("request-password-reset")]
public void RequestPasswordReset([Required] string email)
public async Task RequestPasswordReset([Required] string email)
{
userService.RequestPasswordReset(email);
await userService.RequestPasswordReset(email);
}

/// <summary>Reset password with token and new password</summary>
/// <response code="400">Invalid token</response>
[HttpPost("reset-password")]
public void ResetPassword([Required] string tokenValue, [Required] string newPassword)
public async Task ResetPassword([Required] string tokenValue, [Required] string newPassword)
{
userService.ResetPassword(tokenValue, newPassword);
await userService.ResetPassword(tokenValue, newPassword);
}

/// <summary>Change current user's password (Auth)</summary>
/// <response code="400">Invalid old password or given the same password as old</response>
[HttpPost("change-password")]
[Authorize]
public void ChangePassword([Required] string oldPassword, [Required] string newPassword)
public async Task ChangePassword([Required] string oldPassword, [Required] string newPassword)
{
userService.ChangePassword(AuthDao.GetPrincipalEmail(User), oldPassword, newPassword);
await userService.ChangePassword(AuthDao.GetPrincipalEmail(User), oldPassword, newPassword);
}

/// <summary>Permanently delete account and all data (Auth)</summary>
[HttpDelete("delete-account")]
[Authorize]
public void DeleteAccount()
public async Task DeleteAccount()
{
var header = HttpContext.Request.Headers.Authorization.FirstOrDefault() ??
throw new UnauthorizedAccessException("Unauthorized");

userService.DeleteAccount(AuthDao.GetPrincipalEmail(User), header);
await userService.DeleteAccount(AuthDao.GetPrincipalEmail(User), header);
}
}
2 changes: 1 addition & 1 deletion rag-2-backend/Infrastructure/Module/User/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ await UpdateUserProperties(
user
);

context.Users.Add(user);
await context.Users.AddAsync(user);
await GenerateAccountTokenAndSendConfirmationMail(user);
await context.SaveChangesAsync();
}
Expand Down
2 changes: 1 addition & 1 deletion rag-2-backend/Test/Service/CourseServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public async Task ShouldAddCourse()
await _courseService.AddCourse(courseRequest);

_contextMock.Verify(
c => c.Courses.Add(It.Is<Course>(course => course.Name == courseRequest.Name)),
c => c.Courses.AddAsync(It.Is<Course>(course => course.Name == courseRequest.Name), CancellationToken.None),
Times.Once);
}

Expand Down
2 changes: 1 addition & 1 deletion rag-2-backend/Test/Service/GameServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public async Task ShouldAddGame()
await _gameService.AddGame(gameRequest);

_contextMock.Verify(
c => c.Games.Add(It.Is<Game>(g => g.Name == gameRequest.Name)),
c => c.Games.AddAsync(It.Is<Game>(g => g.Name == gameRequest.Name), CancellationToken.None),
Times.Once);
}

Expand Down
2 changes: 1 addition & 1 deletion rag-2-backend/Test/Service/UserServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ await _userService.RegisterUser(new UserRequest
}
);

_contextMock.Verify(c => c.Users.Add(It.IsAny<User>()), Times.Once);
_contextMock.Verify(c => c.Users.AddAsync(It.IsAny<User>(), CancellationToken.None), Times.Once);
_contextMock.Verify(
c => c.AccountConfirmationTokens.AddAsync(It.IsAny<AccountConfirmationToken>(), CancellationToken.None),
Times.Once);
Expand Down

0 comments on commit 5ab8bf9

Please sign in to comment.