70 lines
2.4 KiB
C#
70 lines
2.4 KiB
C#
|
|
// backend/Controllers/AuthController.cs
|
||
|
|
using Microsoft.AspNetCore.Mvc;
|
||
|
|
using Microsoft.IdentityModel.Tokens;
|
||
|
|
using System.IdentityModel.Tokens.Jwt;
|
||
|
|
using System.Security.Claims;
|
||
|
|
using System.Text;
|
||
|
|
|
||
|
|
namespace Inventario.API.Controllers
|
||
|
|
{
|
||
|
|
// DTO para recibir las credenciales del usuario
|
||
|
|
public class LoginDto
|
||
|
|
{
|
||
|
|
public required string Username { get; set; }
|
||
|
|
public required string Password { get; set; }
|
||
|
|
public bool RememberMe { get; set; }
|
||
|
|
}
|
||
|
|
|
||
|
|
[ApiController]
|
||
|
|
[Route("api/[controller]")]
|
||
|
|
public class AuthController : ControllerBase
|
||
|
|
{
|
||
|
|
private readonly IConfiguration _config;
|
||
|
|
|
||
|
|
public AuthController(IConfiguration config)
|
||
|
|
{
|
||
|
|
_config = config;
|
||
|
|
}
|
||
|
|
|
||
|
|
[HttpPost("login")]
|
||
|
|
public IActionResult Login([FromBody] LoginDto login)
|
||
|
|
{
|
||
|
|
if (login.Username == _config["AuthSettings:Username"] && login.Password == _config["AuthSettings:Password"])
|
||
|
|
{
|
||
|
|
// Pasamos el valor de RememberMe a la función de generación
|
||
|
|
var token = GenerateJwtToken(login.Username, login.RememberMe);
|
||
|
|
return Ok(new { token });
|
||
|
|
}
|
||
|
|
return Unauthorized(new { message = "Credenciales inválidas." });
|
||
|
|
}
|
||
|
|
|
||
|
|
private string GenerateJwtToken(string username, bool rememberMe)
|
||
|
|
{
|
||
|
|
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));
|
||
|
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||
|
|
|
||
|
|
var claims = new[]
|
||
|
|
{
|
||
|
|
new Claim(JwtRegisteredClaimNames.Sub, username),
|
||
|
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
||
|
|
};
|
||
|
|
|
||
|
|
// --- LÓGICA DE EXPIRACIÓN DINÁMICA ---
|
||
|
|
// Si "rememberMe" es true, expira en 1 año.
|
||
|
|
// Si es false, expira en 6 horas.
|
||
|
|
var expirationTime = rememberMe
|
||
|
|
? DateTime.Now.AddYears(1)
|
||
|
|
: DateTime.Now.AddHours(6);
|
||
|
|
// ------------------------------------
|
||
|
|
|
||
|
|
var token = new JwtSecurityToken(
|
||
|
|
issuer: _config["Jwt:Issuer"],
|
||
|
|
audience: _config["Jwt:Audience"],
|
||
|
|
claims: claims,
|
||
|
|
expires: expirationTime,
|
||
|
|
signingCredentials: credentials);
|
||
|
|
|
||
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|