Files
Knots/Knots/Endpoints/User/CreateUserEndpoint.cs
T

33 lines
1000 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 SendErrorsAsync(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 SendNoContentAsync(ct);
}
}