Compare commits

...

6 Commits

12 changed files with 350 additions and 73 deletions

View File

@@ -1,12 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<IsPackable>true</IsPackable>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.2.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

View File

@@ -0,0 +1,58 @@
using APIFicheros.DTOs;
using bdAsegasa;
using bdAsegasa.db;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using tsUtilidades;
namespace APIFicheros.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController : Controller
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody] DatosAuth loginDto)
{
string token = "";
string datosLoginUser = _configuration["DatosLogin:Usuario"];
string datosLoginPassword = _configuration["DatosLogin:Password"];
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (loginDto.usuario == datosLoginUser && loginDto.password == datosLoginPassword)
{
token = Utilidades.AuthenticateUser(loginDto, _configuration);
}
else
{
return Unauthorized("Nombre de usuario o contraseña incorrectos.");
}
return Ok(new
{
Token = token
});
}
}
}

View File

@@ -1,6 +1,8 @@
using APIFicheros.DTOs;
using bdAsegasa;
using bdAsegasa.db;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
@@ -10,11 +12,11 @@ namespace APIFicheros.Controllers
{
[ApiController]
[Route("[controller]")]
public class ObtenerFicherosController : Controller
public class ManipularFicherosController : Controller
{
private readonly IConfiguration _configuration;
private bdAsegasa.tscgestionasegasa bd;
public ObtenerFicherosController(IConfiguration configuration)
public ManipularFicherosController(IConfiguration configuration)
{
_configuration = configuration;
@@ -25,14 +27,12 @@ namespace APIFicheros.Controllers
}
[HttpPost("ObtenerFicherosFaltantes")]
public ActionResult PostNombreBD([FromBody] string numeroPoliza)
[Authorize]
public ActionResult PostComprobarFicheros([FromBody] string numeroPoliza)
{
try
{
int idPoliza = bd.polizassg.First(x => x.NumeroPoliza!.Contains(numeroPoliza)).idPoliza;
@@ -54,8 +54,9 @@ namespace APIFicheros.Controllers
return Ok(listadoFicherosFaltantes);
}
catch (Exception ex) {
catch (Exception ex)
{
return BadRequest("Ha ocurrido un error. Mensaje de error: " + ex.Message);
}
@@ -63,5 +64,41 @@ namespace APIFicheros.Controllers
}
[HttpPost("SubirFicherosFaltantes")]
[Authorize]
public ActionResult PostSubirFicheros([FromBody] DatosFicheros datosFichero)
{
var transaction = bd.Database.BeginTransaction();
try
{
int idFichero = Utilidades.guardarFichero(bd, datosFichero.fichero, datosFichero.nombreFichero, datosFichero.descripcion, datosFichero.idDocumento);
documentospolizassg documentoObtenido = bd.documentospolizassg.First( x => x.idDocumento == datosFichero.idDocumento);
documentoObtenido.idFichero = idFichero;
bd.Update(documentoObtenido);
bd.SaveChanges();
transaction.Commit();
return Ok("Fichero subido correctamente");
}
catch (Exception ex)
{
transaction.Rollback();
return BadRequest("Ha ocurrido un error. Mensaje de error: " + ex.Message);
}
}
}
}

View File

@@ -1,32 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace APIFicheros.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}

View File

@@ -0,0 +1,8 @@
namespace APIFicheros.DTOs
{
public class DatosAuth
{
public string usuario { get; set; }
public string password { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
namespace APIFicheros.DTOs
{
public class DatosFicheros
{
public int idDocumento { get; set; }
public string descripcion { get; set; }
public string nombreFichero { get; set; }
public byte[] fichero { get; set; }
}
}

View File

@@ -1,32 +1,130 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// 1. Configuraci<63>n de Servicios
// a. Configurar servicios de controladores
builder.Services.AddControllers()
.AddJsonOptions(options =>
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true; // Desactiva la validaci<63>n autom<6F>tica del estado del modelo
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
// b. Configuraci<63>n de JWT
var jwtSettings = builder.Configuration.GetSection("Jwt");
var keyString = jwtSettings["Key"];
if (string.IsNullOrEmpty(keyString))
{
throw new ArgumentNullException("JWT Key is not configured.");
}
var key = Encoding.UTF8.GetBytes(keyString);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
options.JsonSerializerOptions.ReferenceHandler =
System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
ValidateIssuer = true,
ValidIssuer = jwtSettings["Issuer"],
ValidateAudience = true,
ValidAudience = jwtSettings["Audience"],
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"])),
ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = ctx =>
{
var logger = ctx.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogError("NOMBRE FALLO {0}", ctx.Exception.GetType().Name);
logger.LogError("MENSAJE FALLO {0}", ctx.Exception.Message);
return Task.CompletedTask;
},
};
});
// d. Configurar Swagger con soporte para JWT
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "SwaggerCamcue API", Version = "v1" });
// Definir el esquema de seguridad JWT
var securityScheme = new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "Ingrese 'Bearer' seguido de su token en el campo de texto.\n\nEjemplo: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...'",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT"
};
c.AddSecurityDefinition("Bearer", securityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
// 2. Configuraci<EFBFBD>n del Pipeline HTTP
// b. Habilitar Swagger solo en Desarrollo
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerCamcue API V1");
c.RoutePrefix = string.Empty; // Swagger en la ra<72>z
});
}
app.UseHttpsRedirection();
app.UseCors(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
//app.UseHttpsRedirection();
// d. Autenticaci<63>n y Autorizaci<63>n
app.UseAuthentication();
app.UseAuthorization();
// e. Mapear Controladores
app.MapControllers();
// f. Ejecutar la Aplicaci<63>n
app.Run();

96
APIFicheros/Utilidades.cs Normal file
View File

@@ -0,0 +1,96 @@
using APIFicheros.DTOs;
using bdAsegasa;
using bdAsegasa.db;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using tsUtilidades;
namespace APIFicheros
{
public class Utilidades
{
public static string AuthenticateUser(DatosAuth loginDto, IConfiguration _configuration)
{
try
{
// Generar token JWT
var jwtSettings = _configuration.GetSection("Jwt");
var keyBytes = Encoding.UTF8.GetBytes(jwtSettings["Key"]);
var key = new SymmetricSecurityKey(keyBytes);
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim("usu", "1"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var expiration = DateTime.UtcNow.AddMinutes(int.Parse(jwtSettings["ExpireMinutes"]));
var token = new JwtSecurityToken(
issuer: jwtSettings["Issuer"],
audience: jwtSettings["Audience"],
claims: claims,
expires: expiration,
signingCredentials: creds
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return tokenString;
}
catch (Exception ex)
{
throw new Exception($"Error en la autenticación: {ex.Message}");
}
}
public static int guardarFichero(bdAsegasa.tscgestionasegasa bd, byte[] fichero,string nombreFichero ,string descripcion, int idDocu)
{
int idFichero = 0;
try
{
int idTipoFichero = bd.enumeraciones.First(x => x.Codigo.Contains("TIPFIC.DOCPOL")).idEnumeracion;
int idPoliza = bd.documentospolizassg.First(x => x.idDocumento == idDocu).idPoliza;
ficheros nuevoFichero = new ficheros();
nuevoFichero.Fichero = fichero;
nuevoFichero.NombreFichero = nombreFichero;
nuevoFichero.Descripcion = descripcion;
nuevoFichero.Fecha = DateTime.Now;
nuevoFichero.Observaciones = "Fichero subido desde API";
nuevoFichero.idTipo = idTipoFichero;
nuevoFichero.idAplicacion = idPoliza;
bd.ficheros.Add(nuevoFichero);
bd.SaveChanges();
idFichero = nuevoFichero.idFichero;
return idFichero;
}
catch (Exception ex) {
throw new Exception("Excepción: " + ex.Message);
}
}
}
}

View File

@@ -1,12 +0,0 @@
namespace APIFicheros;
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}

View File

@@ -1,15 +1,24 @@
{
"Jwt": {
"Key": "Asegasa_APIFicheros2025_5849651882",
"Issuer": "MiAPI_AuthServer",
"Audience": "TuAudience",
"ExpireMinutes":1
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"DatosLogin": {
"Usuario": "ASEGASA",
"Password": "Asegasa.2025"
},
"Configuracion": {
"SegundosMinimosEntreProcesos": "60",
"HoraProcesosDiarios": "06:30",
"NombreConexionBD": "Producción Remoto"
"NombreConexionBD": "Desarrollo"
},
"AllowedHosts": "*"
}

View File

@@ -9,10 +9,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bdAsegasa", "bdAsegasa\bdAs
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bdfactu", "..\Tecnosis\tsFactu\bdFactu\bdfactu.csproj", "{56D9C47A-1D6F-0C5B-2DB0-72EB359C1093}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tsVeriFactu", "..\Tecnosis\tsVeriFactu\tsVeriFactu.csproj", "{947E1B2F-7877-66E7-8DF0-282429B770F0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "APIFicheros", "APIFicheros\APIFicheros.csproj", "{729F814F-BBAF-A079-B0A1-D5890DA11543}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tsVeriFactu", "..\..\Comunes\tsVeriFactu\tsVeriFactu.csproj", "{DDFE8F31-9ED8-5C11-4E72-6CE96526C459}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -31,14 +31,14 @@ Global
{56D9C47A-1D6F-0C5B-2DB0-72EB359C1093}.Debug|Any CPU.Build.0 = Debug|Any CPU
{56D9C47A-1D6F-0C5B-2DB0-72EB359C1093}.Release|Any CPU.ActiveCfg = Release|Any CPU
{56D9C47A-1D6F-0C5B-2DB0-72EB359C1093}.Release|Any CPU.Build.0 = Release|Any CPU
{947E1B2F-7877-66E7-8DF0-282429B770F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{947E1B2F-7877-66E7-8DF0-282429B770F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{947E1B2F-7877-66E7-8DF0-282429B770F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{947E1B2F-7877-66E7-8DF0-282429B770F0}.Release|Any CPU.Build.0 = Release|Any CPU
{729F814F-BBAF-A079-B0A1-D5890DA11543}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{729F814F-BBAF-A079-B0A1-D5890DA11543}.Debug|Any CPU.Build.0 = Debug|Any CPU
{729F814F-BBAF-A079-B0A1-D5890DA11543}.Release|Any CPU.ActiveCfg = Release|Any CPU
{729F814F-BBAF-A079-B0A1-D5890DA11543}.Release|Any CPU.Build.0 = Release|Any CPU
{DDFE8F31-9ED8-5C11-4E72-6CE96526C459}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DDFE8F31-9ED8-5C11-4E72-6CE96526C459}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDFE8F31-9ED8-5C11-4E72-6CE96526C459}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDFE8F31-9ED8-5C11-4E72-6CE96526C459}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -23,7 +23,7 @@
<ItemGroup>
<ProjectReference Include="..\..\..\Comunes\tsVeriFactu\tsVeriFactu.csproj" />
<ProjectReference Include="..\..\Tecnosis\tsFactu\bdFactu\bdfactu.csproj" />
<ProjectReference Include="..\..\Tecnosis\tsVeriFactu\tsVeriFactu.csproj" />
<ProjectReference Include="..\..\..\Comunes\tsVeriFactu\tsVeriFactu.csproj" />
<ProjectReference Include="..\bdAsegasa\bdAsegasa.csproj" />
</ItemGroup>
</Project>