PlanTempusApp/PlanTempus.Components/Users/Create/CreateUserHandler.cs
Janus C. H. Knudsen a991dcdb97 Updates configuration and refactors code structure
Migrates connection strings to new database host
Removes unnecessary code and improves configuration handling
Enhances test coverage and adds random word generation
Updates telemetry and command handling patterns
2026-01-08 21:51:43 +01:00

56 lines
No EOL
2.1 KiB
C#

using Insight.Database;
using Microsoft.ApplicationInsights;
using Npgsql;
using PlanTempus.Components.Users.Exceptions;
using PlanTempus.Core;
using PlanTempus.Core.CommandQueries;
using PlanTempus.Core.Database;
namespace PlanTempus.Components.Users.Create
{
public class CreateUserHandler(
IDatabaseOperations databaseOperations,
ISecureTokenizer secureTokenizer) : ICommandHandler<CreateUserCommand>
{
public async Task<CommandResponse> Handle(CreateUserCommand command)
{
command.TransactionId = Guid.NewGuid();
using var db = databaseOperations.CreateScope(nameof(CreateUserHandler));
try
{
var sql = @"
INSERT INTO system.users(email , password_hash, security_stamp, email_confirmed,
access_failed_count, lockout_enabled,
is_active)
VALUES(@Email, @PasswordHash, @SecurityStamp, @EmailConfirmed,
@AccessFailedCount, @LockoutEnabled, @IsActive)
RETURNING id, created_at, email, is_active";
await db.Connection.QuerySqlAsync(sql, new
{
command.Email,
PasswordHash = secureTokenizer.TokenizeText(command.Password),
SecurityStamp = Guid.NewGuid().ToString("N"),
EmailConfirmed = false,
AccessFailedCount = 0,
LockoutEnabled = false,
command.IsActive,
});
//lav en mapping mellem requestid og userid
return new CommandResponse(command.CorrelationId, command.GetType().Name, command.TransactionId);
}
catch (PostgresException ex) when (ex.SqlState == "23505")
{
db.Error(ex);
throw new EmailAlreadyRegistreredException();
}
catch (Exception ex)
{
db.Error(ex);
throw;
}
}
}
}