Files
Knots/Knots/Endpoints/User/CreateUserEndpoint.cs
T
2026-06-10 15:30:39 +02:00

33 lines
1002 B
C#

using FastEndpoints;
using Knots.DTO.User;
using Microsoft.EntityFrameworkCore;
namespace Knots.Endpoints.User;
public class CreateUserEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint<CreateUserDto, GetUserDto>
{
public override void Configure()
{
Post("/users");
AllowAnonymous();
}
public override async Task HandleAsync(CreateUserDto req, CancellationToken ct)
{
bool usernameExists = await db.Users
.AnyAsync(x => x.Username == req.Username, cancellationToken: ct);
if (usernameExists)
{
AddError(x => x.Username, "Ce nom d'utilisateur est déjà pris.");
await Send.ErrorsAsync(cancellation: ct);
return;
}
req.Password = BCrypt.Net.BCrypt.HashPassword(req.Password);
Models.User? user = mapper.Map<Models.User>(req);
db.Users.Add(user);
await db.SaveChangesAsync(ct);
await Send.NoContentAsync(ct);
}
}