From dc7daaef5cf2f2d904190aa44431aeedbc393d56 Mon Sep 17 00:00:00 2001 From: Timothy Schenk Date: Sun, 12 Nov 2023 13:18:36 +0100 Subject: [PATCH] fix: add transaction to avoid not updating the password --- .editorconfig | 2 ++ Server/PacketHandlers/LoginHandler.cs | 36 +++++++++++++++++++-------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/.editorconfig b/.editorconfig index e270271..6389e64 100644 --- a/.editorconfig +++ b/.editorconfig @@ -28,6 +28,8 @@ insert_final_newline = true indent_size = 4 dotnet_sort_system_directives_first = true +MA0004.report = DetectContext # (default) Try to detect the current context and report only if it considers ConfigureAwait is needed +MA0004.report = Always # Always report missing ConfigureAwait whatever the context # Don't use this. qualifier dotnet_style_qualification_for_field = false:suggestion dotnet_style_qualification_for_property = false:suggestion diff --git a/Server/PacketHandlers/LoginHandler.cs b/Server/PacketHandlers/LoginHandler.cs index 35dd997..e1ec019 100644 --- a/Server/PacketHandlers/LoginHandler.cs +++ b/Server/PacketHandlers/LoginHandler.cs @@ -44,16 +44,32 @@ public class LoginHandler : IPacketHandler { if (this._configuration.GetSection("Testing").GetValue("CreateAccountOnLogin")) { - argon2Id.Salt = RandomNumberGenerator.GetBytes(16); - var finalAccount = - await this._wonderkingContext.Accounts.AddAsync(new Account(packet.Username, Array.Empty(), "", - 0, argon2Id.Salt)).ConfigureAwait(true); - await this._wonderkingContext.SaveChangesAsync().ConfigureAwait(true); - argon2Id.AssociatedData = finalAccount.Entity.Id.ToByteArray(); - finalAccount.Entity.Password = await argon2Id.GetBytesAsync(16).ConfigureAwait(true); - this._wonderkingContext.Accounts.Update(finalAccount.Entity); - loginResponseReason = LoginResponseReason.Ok; - await this._wonderkingContext.SaveChangesAsync().ConfigureAwait(true); + var transaction = + await _wonderkingContext.Database.BeginTransactionAsync().ConfigureAwait(true); + await using (transaction.ConfigureAwait(true)) + { + try + { + argon2Id.Salt = RandomNumberGenerator.GetBytes(16); + var finalAccount = + await this._wonderkingContext.Accounts.AddAsync(new Account(packet.Username, + Array.Empty(), "", + 0, argon2Id.Salt)).ConfigureAwait(true); + await this._wonderkingContext.SaveChangesAsync().ConfigureAwait(true); + argon2Id.AssociatedData = finalAccount.Entity.Id.ToByteArray(); + finalAccount.Entity.Password = await argon2Id.GetBytesAsync(16).ConfigureAwait(true); + this._wonderkingContext.Accounts.Update(finalAccount.Entity); + loginResponseReason = LoginResponseReason.Ok; + await this._wonderkingContext.SaveChangesAsync().ConfigureAwait(true); + + await transaction.CommitAsync().ConfigureAwait(true); + } + catch (Exception) + { + await transaction.RollbackAsync().ConfigureAwait(true); // Rollback the transaction on error + throw; + } + } } else {