73 lines
2.6 KiB
C#
73 lines
2.6 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);
|
|
|
|
var cookieOptions = new CookieOptions
|
|
{
|
|
HttpOnly = true,
|
|
Secure = true,
|
|
SameSite = SameSiteMode.None,
|
|
Path = "/Menu",
|
|
|
|
Expires = DateTimeOffset.UtcNow.AddHours(1)
|
|
};
|
|
|
|
Response.Cookies.Append("token", tokenString, cookieOptions);
|
|
return Ok( new {Email = loginDto.Email, Token = tokenString, Redirect = "/Menu"});
|
|
}
|
|
|
|
[HttpPost("api/login/validar")]
|
|
public IActionResult Verificar([FromBody] AccessDto request, [FromHeader(Name = "Auth")] string token){
|
|
|
|
if (request.Email == String.Empty || token == null ||request.Redirect == string.Empty)
|
|
{
|
|
return Unauthorized(new { esValido = false});
|
|
}
|
|
|
|
bool esValido = RepositorioUsuarios.Singleton.CheckToken(request.Email, token);
|
|
if (esValido) {
|
|
return Ok(new {esValido = esValido});
|
|
} else {
|
|
|
|
return Unauthorized(new {esValido = "el token no es valido"});
|
|
}
|
|
|
|
}
|
|
|
|
|
|
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);
|
|
}
|
|
}
|