Files
AlquilaFacil/Aspnet/Controllers/LoginController.cs
2024-10-19 18:00:58 -03:00

56 lines
2.2 KiB
C#

using Entidades.Dto;
using Modelo;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace AlquilaFacil.Controllers;
[ApiController]
public class LoginController: ControllerBase
{
[HttpPost("api/login")]
public IActionResult Login([FromBody] LoginDto loginDto) {
if (loginDto.Email == String.Empty || loginDto.Contraseña == String.Empty) return Unauthorized(new {message = "Los Datos no llegaron correctamente o faltan"});
var usuario = RepositorioUsuarios.Singleton.CheckUsuario(loginDto);
if (!usuario) return Unauthorized(new {message = "El usuario no existe o la contraseña es incorrecta"});
string tokenString = GenerarToken(loginDto);
RepositorioUsuarios.Singleton.GuardarToken(loginDto, tokenString);
return Ok( new {Email = loginDto.Email, Token = tokenString, Redirect = "/Menu"});
}
[HttpPost("api/login/validar")]
public IActionResult Verificar([FromBody] TokenDto tokenRequest){
if (tokenRequest.Email == String.Empty ||tokenRequest.Token == string.Empty ||tokenRequest.Redirect == string.Empty)
{
return Unauthorized(new { esValido = false});
}
bool esValido = RepositorioUsuarios.Singleton.CheckToken(tokenRequest);
return (esValido) ?
Ok( new { esValido = true}) : Unauthorized( new {esValido = false});
}
private string GenerarToken(LoginDto loginDto){
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("ffb2cdc15d472e41a5b626e294c45020");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, loginDto.Email)
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}