120 lines
4.4 KiB
C#
120 lines
4.4 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using uWine.Core.Domain.Entities;
|
|
using uWine.Core.Infrastructure.Services;
|
|
|
|
namespace uWine.Api.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("/[controller]")]
|
|
public class UserController : Controller
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
readonly AuthenticationService _authenticationService;
|
|
public UserController(IConfiguration configuration, AuthenticationService authenticationService)
|
|
{
|
|
_configuration = configuration;
|
|
_authenticationService = authenticationService;
|
|
}
|
|
//public IActionResult Index()
|
|
//{
|
|
// return View();
|
|
//}
|
|
|
|
[HttpGet("login")]
|
|
public IActionResult LoginWithBasic()
|
|
{
|
|
if (!Request.Headers.ContainsKey("Authorization"))
|
|
return Unauthorized("Authorization header missing");
|
|
|
|
var authHeader = Request.Headers["Authorization"].ToString();
|
|
|
|
if (!authHeader.StartsWith("Basic "))
|
|
return Unauthorized("Invalid auth scheme");
|
|
|
|
var encodedCredentials = authHeader.Substring("Basic ".Length).Trim();
|
|
var decodedBytes = Convert.FromBase64String(encodedCredentials);
|
|
var decodedCredentials = Encoding.UTF8.GetString(decodedBytes);
|
|
|
|
var parts = decodedCredentials.Split(':', 2);
|
|
if (parts.Length != 2)
|
|
return Unauthorized("Invalid credentials format");
|
|
var user = new User { Username = parts[0], Password = parts[1] };
|
|
var auth = _authenticationService.IsAuthenticated(user);
|
|
|
|
// 🔐 Autenticazione fittizia (da sostituire con verifica DB)
|
|
if (!auth)
|
|
return Unauthorized("Credenziali non valide");
|
|
|
|
user = _authenticationService.User(user);
|
|
|
|
var token = GenerateJwtToken(user);
|
|
return Ok(new { access_token = token });
|
|
}
|
|
|
|
[HttpGet("active")]
|
|
public IActionResult IsActive()
|
|
{
|
|
if (!Request.Headers.ContainsKey("Authorization"))
|
|
return Unauthorized("Authorization header missing");
|
|
|
|
var authHeader = Request.Headers["Authorization"].ToString();
|
|
|
|
if (!authHeader.StartsWith("Bearer "))
|
|
return Unauthorized("Invalid auth scheme");
|
|
|
|
var token = authHeader.Substring("Bearer ".Length).Trim();
|
|
var jwtSettings = _configuration.GetSection("JwtSettings");
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var key = Encoding.UTF8.GetBytes(jwtSettings["Secret"]);
|
|
try
|
|
{
|
|
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(key),
|
|
ValidateIssuer = true,
|
|
ValidIssuer = jwtSettings["Issuer"],
|
|
ValidateAudience = true,
|
|
ValidAudience = jwtSettings["Audience"],
|
|
ClockSkew = TimeSpan.Zero // No clock skew for simplicity
|
|
}, out SecurityToken validatedToken);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return Unauthorized("Invalid token");
|
|
}
|
|
|
|
return Ok(new { active = true });
|
|
}
|
|
|
|
private string GenerateJwtToken(User user)
|
|
{
|
|
var jwtSettings = _configuration.GetSection("JwtSettings");
|
|
var claims = new[]
|
|
{
|
|
new Claim("userId", user.Id.ToString()),
|
|
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
|
|
new Claim(ClaimTypes.Role, user.Role.Id.ToString())
|
|
};
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"]));
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: jwtSettings["Issuer"],
|
|
audience: jwtSettings["Audience"],
|
|
claims: claims,
|
|
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(jwtSettings["ExpiresInMinutes"])),
|
|
signingCredentials: creds
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|
|
}
|