PlanTempusApp/PlanTempus.Components/Users/Create/CreateUserHandler.cs

56 lines
2.1 KiB
C#
Raw Normal View History

2025-03-04 17:13:02 +01:00
using Insight.Database;
2025-03-06 00:05:58 +01:00
using Microsoft.ApplicationInsights;
2025-03-10 15:56:22 +01:00
using Npgsql;
using PlanTempus.Components.Users.Exceptions;
2025-03-04 17:13:02 +01:00
using PlanTempus.Core;
2025-03-12 00:13:53 +01:00
using PlanTempus.Core.CommandQueries;
2025-03-10 15:56:22 +01:00
using PlanTempus.Core.Database;
2025-03-04 17:13:02 +01:00
namespace PlanTempus.Components.Users.Create
{
2025-03-06 00:05:58 +01:00
public class CreateUserHandler(
IDatabaseOperations databaseOperations,
2025-03-12 00:13:53 +01:00
ISecureTokenizer secureTokenizer) : ICommandHandler<CreateUserCommand>
2025-03-04 23:54:55 +01:00
{
2025-03-12 00:13:53 +01:00
public async Task<CommandResponse> Handle(CreateUserCommand command)
2025-03-04 23:54:55 +01:00
{
command.TransactionId = Guid.NewGuid();
2025-03-04 23:54:55 +01:00
using var db = databaseOperations.CreateScope(nameof(CreateUserHandler));
try
{
var sql = @"
2025-03-07 16:17:30 +01:00
INSERT INTO system.users(email , password_hash, security_stamp, email_confirmed,
2025-03-04 23:54:55 +01:00
access_failed_count, lockout_enabled,
is_active)
2025-03-04 17:13:02 +01:00
VALUES(@Email, @PasswordHash, @SecurityStamp, @EmailConfirmed,
2025-03-04 23:54:55 +01:00
@AccessFailedCount, @LockoutEnabled, @IsActive)
RETURNING id, created_at, email, is_active";
2025-03-04 17:13:02 +01:00
2025-06-26 21:30:32 +02:00
await db.Connection.QuerySqlAsync(sql, new
2025-03-04 23:54:55 +01:00
{
2025-03-12 00:13:53 +01:00
command.Email,
2025-03-04 23:54:55 +01:00
PasswordHash = secureTokenizer.TokenizeText(command.Password),
SecurityStamp = Guid.NewGuid().ToString("N"),
EmailConfirmed = false,
AccessFailedCount = 0,
LockoutEnabled = false,
2025-03-12 00:13:53 +01:00
command.IsActive,
2025-03-04 23:54:55 +01:00
});
2025-06-26 21:30:32 +02:00
//lav en mapping mellem requestid og userid
return new CommandResponse(command.CorrelationId, command.GetType().Name, command.TransactionId);
2025-03-04 23:54:55 +01:00
}
2025-03-10 15:56:22 +01:00
catch (PostgresException ex) when (ex.SqlState == "23505")
{
db.Error(ex);
throw new EmailAlreadyRegistreredException();
}
2025-03-04 23:54:55 +01:00
catch (Exception ex)
{
db.Error(ex);
throw;
}
}
}
2025-03-04 17:13:02 +01:00
}