forked from sanchezvem/PyroFetes
Ajout de Login et du model réuni avec tout les autres Sujet
This commit is contained in:
50
PyroFetes/Endpoints/Login/UserLoginEndpoint.cs
Normal file
50
PyroFetes/Endpoints/Login/UserLoginEndpoint.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using PyroFetes.DTO.Login.Request;
|
||||
using FastEndpoints.Security;
|
||||
using PyroFetes.DTO.Login.Response;
|
||||
using FastEndpoints;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PyroFetes;
|
||||
|
||||
namespace PyroFetes.Endpoints.Login;
|
||||
|
||||
public class UserLoginEndpoint(PyroFetesDbContext database) : Endpoint<ConnectLoginDto, GetLoginConnectDto>
|
||||
{
|
||||
public override void Configure()
|
||||
{
|
||||
Post("/api/login");
|
||||
AllowAnonymous();
|
||||
}
|
||||
|
||||
public override async Task HandleAsync(ConnectLoginDto req, CancellationToken ct)
|
||||
{
|
||||
var login = await database.Logins.SingleOrDefaultAsync(x => x.Username == req.Username, ct);
|
||||
|
||||
if (login == null)
|
||||
{
|
||||
await Send.UnauthorizedAsync(ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (BCrypt.Net.BCrypt.Verify(req.Password + login.Salt, login.Password))
|
||||
{
|
||||
var jwtToken = JwtBearer.CreateToken(
|
||||
o =>
|
||||
{
|
||||
o.SigningKey = "ThisIsASuperSecretJwtKeyThatIsAtLeast32CharsLong";
|
||||
o.ExpireAt = DateTime.UtcNow.AddMinutes(15);
|
||||
if (login.Role != null) o.User.Roles.Add(login.Role);
|
||||
o.User.Claims.Add(("Username", login.Username)!);
|
||||
o.User.Claims.Add(("FullName", login.FullName)!);
|
||||
o.User["UserId"] = "001";
|
||||
});
|
||||
|
||||
GetLoginConnectDto responseDto = new()
|
||||
{
|
||||
Token = jwtToken
|
||||
};
|
||||
|
||||
await Send.OkAsync(responseDto, ct);
|
||||
}
|
||||
else await Send.UnauthorizedAsync(ct);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user