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 { 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); } }