feat: compiledqueries + tracing

This commit is contained in:
Timothy Schenk 2023-11-24 18:29:24 +01:00
parent b2547d25a3
commit 0704d9f07d
2 changed files with 40 additions and 14 deletions

View file

@ -0,0 +1,21 @@
// Copyright (c) 2023 Timothy Schenk. Subject to the GNU AGPL Version 3 License.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Server.DB;
using Server.DB.Documents;
namespace Server.PacketHandlers;
public partial class LoginHandler
{
private static readonly Func<WonderkingContext, Account, ValueTask<EntityEntry<Account>>> _addAccount =
EF.CompileQuery((WonderkingContext context, Account account) => context.Accounts.AddAsync(account, default));
private static readonly Func<WonderkingContext, Account, Task<EntityEntry<Account>>> _updateAccount =
EF.CompileAsyncQuery((WonderkingContext context, Account account) => context.Accounts.Update(account));
private static readonly Func<WonderkingContext, string, Task<Account>> _getAccount =
EF.CompileQuery((WonderkingContext context, string username) =>
context.Accounts.FirstOrDefaultAsync(a => a.Username == username, default));
}

View file

@ -1,9 +1,10 @@
// Copyright (c) 2023 Timothy Schenk. Subject to the GNU AGPL Version 3 License.
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using DotNext;
using Konscious.Security.Cryptography;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NetCoreServer;
@ -16,11 +17,12 @@ using Wonderking.Packets.Outgoing.Data;
namespace Server.PacketHandlers;
public class LoginHandler : IPacketHandler<LoginInfoPacket>
public partial class LoginHandler : IPacketHandler<LoginInfoPacket>
{
private readonly IConfiguration _configuration;
private readonly ILogger<LoginHandler> _logger;
private readonly WonderkingContext _wonderkingContext;
private static readonly ActivitySource _activitySource = new ActivitySource(nameof(Server));
public LoginHandler(ILogger<LoginHandler> logger, WonderkingContext wonderkingContext, IConfiguration configuration)
{
@ -33,14 +35,14 @@ public class LoginHandler : IPacketHandler<LoginInfoPacket>
{
LoginResponseReason loginResponseReason;
_logger.LoginData(packet.Username, packet.Password);
var account = await _wonderkingContext.Accounts.FirstOrDefaultAsync(a => a.Username == packet.Username);
var account = await _getAccount(_wonderkingContext, packet.Username);
if (account == null)
{
if (_configuration.GetSection("Testing").GetValue<bool>("CreateAccountOnLogin"))
{
loginResponseReason = await CreateAccountOnLoginAsync(packet.Username, packet.Password);
account = await _wonderkingContext.Accounts.FirstOrDefaultAsync(a => a.Username == packet.Username);
account = await _getAccount(_wonderkingContext, packet.Username);
}
else
{
@ -52,18 +54,21 @@ public class LoginHandler : IPacketHandler<LoginInfoPacket>
{
var salt = account.Salt;
var tempPasswordBytes = await GetPasswordHashAsync(packet.Password, salt, account.Id);
loginResponseReason = tempPasswordBytes.SequenceEqual(account.Password)
loginResponseReason = tempPasswordBytes.BitwiseEquals(account.Password)
? LoginResponseReason.Ok
: LoginResponseReason.WrongPassword;
}
var channelData = new ServerChannelData[1];
channelData[0] = new ServerChannelData { ChannelId = 0, LoadPercentage = 0, ServerId = 0 };
var loginResponsePacket = new LoginResponsePacket
{
ResponseReason = loginResponseReason,
ChannelData = new[] { new ServerChannelData { ChannelId = 0, LoadPercentage = 0, ServerId = 0 } },
ChannelData = channelData.ToArray(),
UnknownFlag = 1,
IsGameMaster = true
};
var authSession = session as AuthSession;
if (account != null && authSession != null)
{
@ -71,11 +76,12 @@ public class LoginHandler : IPacketHandler<LoginInfoPacket>
}
_logger.LogInformation("LoginResponsePacket: {@LoginResponsePacket}", loginResponsePacket);
authSession?.SendAsync(loginResponsePacket);
_ = authSession?.SendAsync(loginResponsePacket);
}
private static Task<byte[]> GetPasswordHashAsync(string password, byte[] salt, Guid userId)
private static async Task<byte[]> GetPasswordHashAsync(string password, byte[] salt, Guid userId)
{
using var activity = _activitySource.StartActivity("GetPasswordHashAsync");
// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Chea1t_Sheet.html#argon2id
// "Use Argon2id with a minimum configuration of 19 MiB of memory, an iteration count of 2, and 1 degree of parallelism."
var argon2Id = new Argon2id(Encoding.ASCII.GetBytes(password))
@ -86,11 +92,12 @@ public class LoginHandler : IPacketHandler<LoginInfoPacket>
Salt = salt,
AssociatedData = userId.ToByteArray()
};
return argon2Id.GetBytesAsync(16);
return await argon2Id.GetBytesAsync(16);
}
private async Task<LoginResponseReason> CreateAccountOnLoginAsync(string username, string password)
{
using var activity = _activitySource.StartActivity("CreateAccountOnLoginAsync");
LoginResponseReason loginResponseReason;
var transaction =
await _wonderkingContext.Database.BeginTransactionAsync();
@ -99,14 +106,12 @@ public class LoginHandler : IPacketHandler<LoginInfoPacket>
try
{
var salt = RandomNumberGenerator.GetBytes(16);
var finalAccount =
await _wonderkingContext.Accounts.AddAsync(new Account(username,
Array.Empty<byte>(), "",
0, salt));
var finalAccount = await _addAccount(_wonderkingContext, new Account(username,
Array.Empty<byte>(), "", 0, salt));
await _wonderkingContext.SaveChangesAsync();
finalAccount.Entity.Password =
await GetPasswordHashAsync(password, salt, finalAccount.Entity.Id);
_wonderkingContext.Accounts.Update(finalAccount.Entity);
_updateAccount(_wonderkingContext, finalAccount.Entity);
loginResponseReason = LoginResponseReason.Ok;
await _wonderkingContext.SaveChangesAsync();