Files
PyroFetes-Sujet1/PyroFetes/Endpoints/Login/UserLoginEndpoint.cs
2025-12-08 12:27:05 +01:00

48 lines
1.5 KiB
C#

using FastEndpoints;
using FastEndpoints.Security;
using Microsoft.EntityFrameworkCore;
using PyroFetes.DTO.Login.Request;
using PyroFetes.DTO.Login.Response;
namespace PyroFetes.Endpoints.Login;
public class UserLoginEndpoint(PyroFetesDbContext database) : Endpoint<ConnectLoginDto, GetLoginConnectDto>
{
public override void Configure()
{
Post("/login");
AllowAnonymous();
}
public override async Task HandleAsync(ConnectLoginDto req, CancellationToken ct)
{
Models.User? login = await database.Users.SingleOrDefaultAsync(x => x.Name == req.Name, ct);
if (login == null)
{
await Send.UnauthorizedAsync(ct);
return;
}
if (BCrypt.Net.BCrypt.Verify(req.Password + login.Salt, login.Password))
{
string jwtToken = JwtBearer.CreateToken(
o =>
{
o.SigningKey = "ThisIsASuperSecretJwtKeyThatIsAtLeast32CharsLong";
o.ExpireAt = DateTime.UtcNow.AddMinutes(15);
if (login.Fonction != null) o.User.Roles.Add(login.Fonction);
o.User.Claims.Add(("Username", login.Name)!);
o.User["UserId"] = "001";
});
GetLoginConnectDto responseDto = new()
{
Token = jwtToken
};
await Send.OkAsync(responseDto, ct);
}
else await Send.UnauthorizedAsync(ct);
}
}