Files
AlquilaFacil/Aspnet/Controllers/LoginController.cs

92 lines
3.4 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, Request.HttpContext.Connection.RemoteIpAddress);
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"});
}
}
[HttpDelete("/api/logout")]
public IActionResult CerrarSesion([FromHeader(Name = "Auth")]string Auth){
var cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
if (cli == null ) return BadRequest(new { message = "No hay un cliente con ese token" });
var log = new LoginDto {
Email = cli.Email,
Contraseña = "",
};
string tokenString = GenerarToken(log);
try{
RepositorioUsuarios.Singleton.GuardarToken(log, tokenString, Request.HttpContext.Connection.RemoteIpAddress, "Cerrar Sesión");
} catch {
return BadRequest( new { message = "Fallo al cambiar el token" } );
}
return Ok(new { message = "Se Cerro la sesion" });
}
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);
}
}