diff --git a/BackApiGateway.sln b/BackApiGateway.sln index d4a2c27..c426519 100644 --- a/BackApiGateway.sln +++ b/BackApiGateway.sln @@ -9,13 +9,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "ApiGateway\Ap EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Auth", "Auth\Auth.csproj", "{76522272-9D28-4168-8296-AFC933D22650}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "IntegradorBE\IntegradorBE.csproj", "{9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{F491CF9B-9CF8-4F3B-BBD7-A282F7DC1D6D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Microservices", "Microservices", "{A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSAdminUsuarios", "MsUsuarios\MSAdminUsuarios.csproj", "{E96CED9C-6CD0-452D-81B4-878C78303C47}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSAdminUsuarios", "Microservicios\MsUsuarios\MSAdminUsuarios.csproj", "{D0B80363-4C96-413F-8C82-48FCF2CD7F57}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "Microservicios\IntegradorBE\IntegradorBE.csproj", "{E3B575F9-4A18-43E6-A542-7CC29B086752}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -31,14 +31,14 @@ Global {76522272-9D28-4168-8296-AFC933D22650}.Debug|Any CPU.Build.0 = Debug|Any CPU {76522272-9D28-4168-8296-AFC933D22650}.Release|Any CPU.ActiveCfg = Release|Any CPU {76522272-9D28-4168-8296-AFC933D22650}.Release|Any CPU.Build.0 = Release|Any CPU - {9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9562FA86-4AEF-43E2-A6F6-D60AF09BCA12}.Release|Any CPU.Build.0 = Release|Any CPU - {E96CED9C-6CD0-452D-81B4-878C78303C47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E96CED9C-6CD0-452D-81B4-878C78303C47}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E96CED9C-6CD0-452D-81B4-878C78303C47}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E96CED9C-6CD0-452D-81B4-878C78303C47}.Release|Any CPU.Build.0 = Release|Any CPU + {D0B80363-4C96-413F-8C82-48FCF2CD7F57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0B80363-4C96-413F-8C82-48FCF2CD7F57}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0B80363-4C96-413F-8C82-48FCF2CD7F57}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0B80363-4C96-413F-8C82-48FCF2CD7F57}.Release|Any CPU.Build.0 = Release|Any CPU + {E3B575F9-4A18-43E6-A542-7CC29B086752}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E3B575F9-4A18-43E6-A542-7CC29B086752}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E3B575F9-4A18-43E6-A542-7CC29B086752}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E3B575F9-4A18-43E6-A542-7CC29B086752}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -46,8 +46,8 @@ Global GlobalSection(NestedProjects) = preSolution {AC631810-7FAF-4C9A-A35D-3EC538A49810} = {9F5D8D1C-CF99-4BDD-8497-0123656B8A48} {76522272-9D28-4168-8296-AFC933D22650} = {F491CF9B-9CF8-4F3B-BBD7-A282F7DC1D6D} - {9562FA86-4AEF-43E2-A6F6-D60AF09BCA12} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} - {E96CED9C-6CD0-452D-81B4-878C78303C47} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} + {D0B80363-4C96-413F-8C82-48FCF2CD7F57} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} + {E3B575F9-4A18-43E6-A542-7CC29B086752} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {EC576D5A-ADE3-40CC-BF55-7E52E6F18AC4} diff --git a/IntegradorBE/.config/dotnet-tools.json b/Microservicios/IntegradorBE/.config/dotnet-tools.json similarity index 100% rename from IntegradorBE/.config/dotnet-tools.json rename to Microservicios/IntegradorBE/.config/dotnet-tools.json diff --git a/IntegradorBE/Controllers/AuthController.cs b/Microservicios/IntegradorBE/Controllers/AuthController.cs similarity index 100% rename from IntegradorBE/Controllers/AuthController.cs rename to Microservicios/IntegradorBE/Controllers/AuthController.cs diff --git a/IntegradorBE/Controllers/UPCController.cs b/Microservicios/IntegradorBE/Controllers/UPCController.cs similarity index 100% rename from IntegradorBE/Controllers/UPCController.cs rename to Microservicios/IntegradorBE/Controllers/UPCController.cs diff --git a/IntegradorBE/IntegradorBE.csproj b/Microservicios/IntegradorBE/IntegradorBE.csproj similarity index 100% rename from IntegradorBE/IntegradorBE.csproj rename to Microservicios/IntegradorBE/IntegradorBE.csproj diff --git a/IntegradorBE/IntegradorBE.sln b/Microservicios/IntegradorBE/IntegradorBE.sln similarity index 100% rename from IntegradorBE/IntegradorBE.sln rename to Microservicios/IntegradorBE/IntegradorBE.sln diff --git a/IntegradorBE/Program.cs b/Microservicios/IntegradorBE/Program.cs similarity index 100% rename from IntegradorBE/Program.cs rename to Microservicios/IntegradorBE/Program.cs diff --git a/IntegradorBE/Properties/launchSettings.json b/Microservicios/IntegradorBE/Properties/launchSettings.json similarity index 100% rename from IntegradorBE/Properties/launchSettings.json rename to Microservicios/IntegradorBE/Properties/launchSettings.json diff --git a/IntegradorBE/appsettings.Development.json b/Microservicios/IntegradorBE/appsettings.Development.json similarity index 100% rename from IntegradorBE/appsettings.Development.json rename to Microservicios/IntegradorBE/appsettings.Development.json diff --git a/IntegradorBE/appsettings.json b/Microservicios/IntegradorBE/appsettings.json similarity index 100% rename from IntegradorBE/appsettings.json rename to Microservicios/IntegradorBE/appsettings.json diff --git a/Microservicios/MsUsuarios/.config/dotnet-tools.json b/Microservicios/MsUsuarios/.config/dotnet-tools.json new file mode 100644 index 0000000..b8c6c1f --- /dev/null +++ b/Microservicios/MsUsuarios/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "6.0.9", + "commands": [ + "dotnet-ef" + ] + } + } +} \ No newline at end of file diff --git a/Microservicios/MsUsuarios/.gitattributes b/Microservicios/MsUsuarios/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/Microservicios/MsUsuarios/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/Microservicios/MsUsuarios/.gitignore b/Microservicios/MsUsuarios/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/Microservicios/MsUsuarios/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/Microservicios/MsUsuarios/Context/MICROSERVICIO.cs b/Microservicios/MsUsuarios/Context/MICROSERVICIO.cs new file mode 100644 index 0000000..c23e785 --- /dev/null +++ b/Microservicios/MsUsuarios/Context/MICROSERVICIO.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +namespace MSAdminUsuarios.Context +{ + public partial class MICROSERVICIO + { + public int NU_PK_MS { get; set; } + public string? TX_SECCION_MS { get; set; } + public int? NU_PADRE_MS { get; set; } + public string? TX_ICON_MS { get; set; } + public string? TX_RUTA_MS { get; set; } + public string? TX_TABLAS_MS { get; set; } + + } +} diff --git a/Microservicios/MsUsuarios/Context/ModelContext.cs b/Microservicios/MsUsuarios/Context/ModelContext.cs new file mode 100644 index 0000000..5745378 --- /dev/null +++ b/Microservicios/MsUsuarios/Context/ModelContext.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace MSAdminUsuarios.Context +{ + public partial class ModelContext : DbContext + { + public ModelContext() + { + } + + public ModelContext(DbContextOptions options) + : base(options) + { + } + + public virtual DbSet MICROSERVICIOs { get; set; } = null!; + public virtual DbSet PERMISOSMs { get; set; } = null!; + public virtual DbSet PERFILESMs { get; set; } = null!; + public virtual DbSet PERFILESPORUSUARIOs { get; set; } = null!; + public virtual DbSet USUARIOSMs { get; set; } = null!; + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + { + } + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.HasDefaultSchema("HIMSCAP"); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.NU_PK_MS) + .HasName("MICROSERVICIOS_PK"); + + entity.ToTable("MICROSERVICIOS"); + + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.NU_PK_PMS) + .HasName("PERMISOSMS_PK"); + + entity.ToTable("PERMISOSMS"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.NU_PK_PFL) + .HasName("PERFILESMS_PK"); + + entity.ToTable("PERFILESMS"); + + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.NU_PK_PFLXUSU) + .HasName("PERFILESPORUSUARIO_PK"); + + entity.ToTable("PERFILESPORUSUARIO"); + + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.NU_PK_USUMS) + .HasName("USUARIOSMS_PK"); + + entity.ToTable("USUARIOSMS"); + }); + + OnModelCreatingPartial(modelBuilder); + } + + partial void OnModelCreatingPartial(ModelBuilder modelBuilder); + } +} diff --git a/Microservicios/MsUsuarios/Context/PERFIL.cs b/Microservicios/MsUsuarios/Context/PERFIL.cs new file mode 100644 index 0000000..a4a47e0 --- /dev/null +++ b/Microservicios/MsUsuarios/Context/PERFIL.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace MSAdminUsuarios.Context +{ + public partial class PERFIL + { + + public int NU_PK_PFL { get; set; } + public string? TX_PERFIL_PFL { get; set; } + public int? BL_ESTADO_PFL { get; set; } = 1; + + } +} diff --git a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs new file mode 100644 index 0000000..a662e5e --- /dev/null +++ b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace MSAdminUsuarios.Context +{ + public partial class PERFILPORUSUARIO + { + public int NU_PK_PFLXUSU { get; set; } + public string? TX_FKDOC_USUMS { get; set; } + public int? NU_FK_PFL { get; set; } + public int? BL_ESTADO_PFLXUSU { get; set; } = 1; + + } +} diff --git a/Microservicios/MsUsuarios/Context/PERMISO.cs b/Microservicios/MsUsuarios/Context/PERMISO.cs new file mode 100644 index 0000000..a9f9ca5 --- /dev/null +++ b/Microservicios/MsUsuarios/Context/PERMISO.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; + +namespace MSAdminUsuarios.Context +{ + public partial class PERMISO + { + public int NU_PK_PMS { get; set; } + public int? NU_FK_PFL { get; set; } + public int? NU_FK_MS { get; set; } + public int? BL_ESTADO_PMS { get; set; } = 1; + } +} diff --git a/Microservicios/MsUsuarios/Context/USUARIO.cs b/Microservicios/MsUsuarios/Context/USUARIO.cs new file mode 100644 index 0000000..90c97e3 --- /dev/null +++ b/Microservicios/MsUsuarios/Context/USUARIO.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace MSAdminUsuarios.Context +{ + public partial class USUARIO + { + public string TX_PKDOC_USUMS { get; set; } = null!; + public string? TX_LOGINNAME_USUMS { get; set; } + public string? TX_PRIMERNOM_USUMS { get; set; } + public string? TX_SEGUNDONOM_USUMS { get; set; } + public string? TX_PRIMERAPELL_USUMS { get; set; } + public string? TX_SEGUNDOAPELL_USUMS { get; set; } + public string? TX_DIRECCION_USUMS { get; set; } + public string? TX_TELEFONO_USUMS { get; set; } + public string? TX_CELULAR_USUMS { get; set; } + public string? TX_CORREO_USUMS { get; set; } + public int? NU_ESTADO_USUMS { get; set; } = 1; + public string? TX_PASSWORD_USUMS { get; set; } + public int? NU_TIPODOC_USUMS { get; set; } + public int? NU_PK_USUMS { get; set; } + + } +} diff --git a/Microservicios/MsUsuarios/Controllers/AuthController.cs b/Microservicios/MsUsuarios/Controllers/AuthController.cs new file mode 100644 index 0000000..b4d29e8 --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/AuthController.cs @@ -0,0 +1,248 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; +using MSAdminUsuarios.Context; +using Security; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + +namespace MSAdminUsuarios.Controllers +{ + [ApiController] + [Route("[controller]")] + public class AuthController : ControllerBase + { + private readonly ModelContext _context; + private readonly Encripter _encript = new(); + public AuthController(ModelContext context) + { + _context = context; + } + + [HttpPost("Login")] + public IActionResult Login([FromBody] LoginModel login) + { + try + { + if (!_encript.IsValid) return BadRequest("Lectura inválida"); + + if (login.TX_LOGINNAME_USUMS == null) return BadRequest("Es necesario ingresar un correo"); + if (login.TX_PASSWORD_USUMS == null) return BadRequest("Es necesario ingresar una contraseña"); + + USUARIO? user = _context.USUARIOSMs.FirstOrDefault(u => u.TX_LOGINNAME_USUMS == login.TX_LOGINNAME_USUMS && u.TX_PASSWORD_USUMS == _encript.EncryptPwd(login.TX_PASSWORD_USUMS)); + + if (user == null) return BadRequest("Usuario o contraseña incorrectos"); + + string token = Token(user); + + return Ok(new { + token = token, + user = user.TX_PKDOC_USUMS + }); + + } catch (Exception e) + { + return BadRequest(e.Message); + } + + } + + [HttpPost("Proveedor")] + public IActionResult LoginProveedores([FromBody] LoginModel login) + { + try + { + if (!_encript.IsValid) return BadRequest(new ResLoginExt("Lectura inválida")); + + if (login.TX_LOGINNAME_USUMS == null) return BadRequest(new ResLoginExt("Es necesario ingresar un usuario")); + if (login.TX_PASSWORD_USUMS == null) return BadRequest(new ResLoginExt("Es necesario ingresar una contraseña")); + + USUARIO? userExist = _context.USUARIOSMs.FirstOrDefault(u => u.TX_LOGINNAME_USUMS == login.TX_LOGINNAME_USUMS); + if (userExist == null) return BadRequest(new ResLoginExt("Usuario o contraseña incorrectos")); + + USUARIO? user = _context.USUARIOSMs.FirstOrDefault(u => u.TX_LOGINNAME_USUMS == login.TX_LOGINNAME_USUMS && u.TX_PASSWORD_USUMS == _encript.EncryptPwd(login.TX_PASSWORD_USUMS)); + + if (user == null) return BadRequest(new ResLoginExt("Usuario o contraseña incorrectos", true, userExist.NU_ESTADO_USUMS)); + + if (user.NU_ESTADO_USUMS != 1) return BadRequest(new ResLoginExt("Usuario inactivo o eliminado.", true, user.NU_ESTADO_USUMS)); + + string token = Token(user); + + return Ok(new ResLoginExt("Bienvenido al sistema.", true, user.NU_ESTADO_USUMS, token)); + + } + catch (Exception e) + { + return BadRequest(e.Message); + } + + } + + [HttpPatch("RenovarToken")] + public IActionResult RefreshToken([FromBody] string token) + { + try + { + JwtSecurityTokenHandler handler = new(); + JwtSecurityToken tkn = handler.ReadJwtToken(Encripter.Descypher(token)); + int pk = Int32.Parse(tkn.Claims.FirstOrDefault(c => c.Type == "pk").Value); + + USUARIO? user = _context.USUARIOSMs.FirstOrDefault(u => u.NU_PK_USUMS == pk); + + if (user == null) return BadRequest("No se encuentra usuario"); + + string newToken = Token(user); + return Ok(newToken); + + } catch(Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpGet("Encriptar")] + public IActionResult Encriptar(string text, int tipo) + { + if (!_encript.IsValid) return BadRequest("Lectura inválida"); + + if (tipo == 0) return Ok(_encript.EncryptPwd(text)); + + return Ok(_encript.EncryptHashTkn(text)); + } + + [HttpGet("Desencriptar")] + public IActionResult Desencriptar(string text, int tipo) + { + if (!_encript.IsValid) return BadRequest("Lectura inválida"); + + if (tipo == 0) return Ok(_encript.DecryptPwd(text)); + + return Ok(_encript.DecryptHashTkn(text)); + } + + [AcceptVerbs("GET")] + string Token(USUARIO user) + { + List perfilesPorUsuario = (from perf in _context.PERFILESPORUSUARIOs + where perf.TX_FKDOC_USUMS == user.TX_PKDOC_USUMS && perf.NU_FK_PFL != null && perf.BL_ESTADO_PFLXUSU == 1 + select perf).ToList(); + + List perfiles = perfilesPorUsuario.Select(p => p.NU_FK_PFL).ToList(); + + List permisos = (from perfXUs in perfilesPorUsuario + join perm in _context.PERMISOSMs on perfXUs.NU_FK_PFL equals perm.NU_FK_PFL + where perm.BL_ESTADO_PMS == 1 + select perm).ToList(); + + Dictionary perfilesPorPermiso = new(); + foreach (PERMISO p in permisos) + { + string key = p.NU_FK_MS.ToString(); + string val = p.NU_FK_PFL.ToString(); + + if (perfilesPorPermiso.ContainsKey(key)) + { + string antVal = perfilesPorPermiso[key]; + perfilesPorPermiso.Remove(key); + perfilesPorPermiso.Add(key, antVal + "," + val); + } + else + { + perfilesPorPermiso.Add(key, val); + } + } + + perfiles.Add(-1); + + //Security key debe ser un environment variable seguro + var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Encripter.HashKey)); + var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); + string nombres = ""; + string apellidos = ""; + + if (user.TX_PRIMERNOM_USUMS != null) nombres += user.TX_PRIMERNOM_USUMS; + if (user.TX_SEGUNDONOM_USUMS != null) nombres += " " + user.TX_SEGUNDONOM_USUMS; + if (user.TX_PRIMERAPELL_USUMS != null) apellidos += user.TX_PRIMERAPELL_USUMS; + if (user.TX_SEGUNDOAPELL_USUMS != null) apellidos += " " + user.TX_SEGUNDOAPELL_USUMS; + + nombres = nombres.Trim(); + apellidos = apellidos.Trim(); + + if (nombres == "") nombres = "N"; + if (apellidos == "") apellidos = "A"; + + int tipo_doc = user.NU_TIPODOC_USUMS == null ? -1 : (int)user.NU_TIPODOC_USUMS; + + ClaimsIdentity claims = new ClaimsIdentity(new List + { + new Claim("user", user.TX_PKDOC_USUMS), + new Claim("nombres", nombres), + new Claim("apellidos", apellidos), + new Claim("tipo_doc", tipo_doc.ToString()), + new Claim("pk", user.NU_PK_USUMS.ToString()) + }); + + + foreach (int p in perfiles) + { + claims.AddClaim(new Claim("perfiles", p.ToString(), ClaimValueTypes.String)); + } + + + //foreach (PERMISO p in permisos) + //{ + // claims.AddClaim(new Claim("permisos", Encripter.Encrypt(p.NU_FK_MS.ToString()))); + //} + + foreach (KeyValuePair p in perfilesPorPermiso) + { + string key = p.Key; + string val = p.Value; + + claims.AddClaim(new Claim("permisos", _encript.EncryptHashTkn(key) + "::" + val)); + } + + var securityTokenDescriptor = new SecurityTokenDescriptor + { + Subject = claims, + Expires = DateTime.Now.AddDays(20), + SigningCredentials = signingCredentials + }; + + var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); + var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor); + var token = jwtSecurityTokenHandler.WriteToken(securityToken); + + return Encripter.Cypher(token); + } + + } + + public class LoginModel + { + public string? TX_LOGINNAME_USUMS { get; set; } + public string? TX_PASSWORD_USUMS { get; set; } + } + + public class ResLoginExt + { + + public ResLoginExt(string _message, bool _exist = false, int? _estado = null, string? _token = "") + { + Message = _message; + Token = _token; + Existe = _exist; + Estado = _estado; + } + + public bool Existe { get; set; } + public int? Estado { get; set; } + public string? Token { get; set; } + public string Message { get; set; } = null!; + } + + static class Options + { + + } +} \ No newline at end of file diff --git a/Microservicios/MsUsuarios/Controllers/MicroserviciosController.cs b/Microservicios/MsUsuarios/Controllers/MicroserviciosController.cs new file mode 100644 index 0000000..cda5489 --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/MicroserviciosController.cs @@ -0,0 +1,54 @@ +using MSAdminUsuarios.Context; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace MSAdminUsuarios.Controllers +{ + [ApiController] + [Route("[controller]")] + public class MicroserviciosController : ControllerBase + { + private readonly ModelContext _context; + + public MicroserviciosController(ModelContext context) + { + _context = context; + } + + [HttpGet] + public async Task GetMicroservicios() + { + try + { + /*var consulta = from dm in _context.MICROSERVICIOs + select dm;*/ + List microservicios = await _context.MICROSERVICIOs.OrderBy(m => m.TX_SECCION_MS).ToListAsync(); + return Ok(microservicios); + } + catch (Exception ex) + { + return BadRequest(ex); + } + } + + [HttpPost] + public async Task GuardarPerfiles(MICROSERVICIO guardado) + { + try + { + + if (guardado == null) return ValidationProblem(); + + _context.MICROSERVICIOs.Add(guardado); + await _context.SaveChangesAsync(); + return Ok(); + + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + } +} + diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs new file mode 100644 index 0000000..c4e7901 --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs @@ -0,0 +1,76 @@ +using MSAdminUsuarios.Context; +using Microsoft.AspNetCore.Mvc; + +namespace MSAdminUsuarios.Controllers +{ + [ApiController] + [Route("[controller]")] + public class PerfilesController : ControllerBase + { + private readonly ModelContext _context; + + public PerfilesController(ModelContext context) + { + _context = context; + } + + [HttpGet] + public async Task GetPerfiles() + { + try + { + var consulta = from dm in _context.PERFILESMs + where dm.BL_ESTADO_PFL>=0 + select dm; + + return Ok(consulta); + } + catch (Exception ex) + { + return BadRequest(ex); + } + } + + [HttpPost] + public async Task GuardarPerfiles(PERFIL guardado) + { + try + { + + if (guardado == null) return ValidationProblem(); + + _context.PERFILESMs.Add(guardado); + await _context.SaveChangesAsync(); + return Ok(); + + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpPatch] + public async Task EditarPerfiles(PERFIL editado) + { + try + { + if (editado == null) return ValidationProblem(); + + var existe = _context.PERFILESMs.Find(editado.NU_PK_PFL); + + existe.TX_PERFIL_PFL = editado.TX_PERFIL_PFL; + existe.BL_ESTADO_PFL = editado.BL_ESTADO_PFL; + + _context.PERFILESMs.Update(existe); + await _context.SaveChangesAsync(); + return Ok(); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + } +} + diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs new file mode 100644 index 0000000..b88d670 --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs @@ -0,0 +1,124 @@ +using MSAdminUsuarios.Context; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Transactions; + +namespace MSAdminUsuarios.Controllers +{ + [ApiController] + [Route("[controller]")] + public class PerfilesPorUsuarioController : ControllerBase + { + private readonly ModelContext _context; + + public PerfilesPorUsuarioController(ModelContext context) + { + _context = context; + } + + [HttpGet] + public async Task GetPerfilesPorUsuario() + { + try + { + var consulta = from dm in _context.PERFILESPORUSUARIOs + where dm.BL_ESTADO_PFLXUSU > 0 + select dm; + + return Ok(consulta); + } + catch (Exception ex) + { + return BadRequest(ex); + } + } + + [HttpPost] + public async Task GuardarPerfilesPorUsuario(PERFILPORUSUARIO[] guardar) + { + using (var dbContextTransaction = _context.Database.BeginTransaction()) + { + List error = new List(); //Inicializamos variable para guardar errores + var count = 0; + try + { + // Se cambia a estado 0 todos los perfiles por usuario existentes + var existe_plfxusu = _context.PERFILESPORUSUARIOs.Where(x => x.BL_ESTADO_PFLXUSU == 1 && x.TX_FKDOC_USUMS == guardar[0].TX_FKDOC_USUMS).ToList(); + + foreach (var cu in existe_plfxusu) + { + cu.BL_ESTADO_PFLXUSU = 0; + _context.PERFILESPORUSUARIOs.Update(cu); + await _context.SaveChangesAsync(); + } + + + + foreach (var pxu in guardar) + { + count++; + //Se comprueba existencia de cada pxu en base de datos + var existe_pxu = (from dm in _context.PERFILESPORUSUARIOs + where dm.NU_FK_PFL == pxu.NU_FK_PFL + && dm.TX_FKDOC_USUMS == pxu.TX_FKDOC_USUMS + select dm).ToList(); + + if(existe_pxu.Count() > 0) + { + //Si existe activamos estado 1 del perfil + existe_pxu[0].BL_ESTADO_PFLXUSU = 1; + _context.Update(existe_pxu[0]); + await _context.SaveChangesAsync(); + continue; + } + else + { + if (pxu == null) + { + error.Add($"Perfil por usuario #{count} sin valores"); + continue; + } + + pxu.BL_ESTADO_PFLXUSU = 1; + _context.PERFILESPORUSUARIOs.Add(pxu); + await _context.SaveChangesAsync(); + } + } + + dbContextTransaction.Commit(); + + List all = new List(); + + all.Add($"Total registros: {guardar.Count().ToString()}"); + all.Add($"Exitosos: {(guardar.Count() - error.Count()).ToString()}"); + all.Add($"Erroneos: {error.Count().ToString()}"); + + var flag_r = 0; + foreach (var r in error) + { + flag_r++; + all.Add($"Error #{flag_r}: {r}"); + } + + if (error.Count() > 0) + { + return Conflict(all.ToList()); + } + return Ok(); + } + catch (Exception ex) + { + //hacemos rollback si hay excepción + dbContextTransaction.Rollback(); + return BadRequest(ex.Message); + } + + } + } + + } +} + diff --git a/Microservicios/MsUsuarios/Controllers/PermisosController.cs b/Microservicios/MsUsuarios/Controllers/PermisosController.cs new file mode 100644 index 0000000..48b03f5 --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/PermisosController.cs @@ -0,0 +1,154 @@ +using MSAdminUsuarios.Context; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Transactions; + +namespace MSAdminUsuarios.Controllers +{ + [ApiController] + [Route("[controller]")] + public class PermisosController : ControllerBase + { + private readonly ModelContext _context; + + public PermisosController(ModelContext context) + { + _context = context; + } + + [HttpGet] + public async Task GetPermisos() + { + try + { + var consulta = from dm in _context.PERMISOSMs + select dm; + + return Ok(consulta); + } + catch (Exception ex) + { + return BadRequest(ex); + } + } + + [HttpPost] + public async Task GuardarPermisos(PERMISO[] guardar) + { + using (var dbContextTransaction = _context.Database.BeginTransaction()) + { + List error = new List(); //Inicializamos variable para guardar errores + var count = 0; + try + { + // Se cambia a estado 0 todos los perfiles por usuario existentes + var existe_pms_c = _context.PERMISOSMs.Where(x => x.BL_ESTADO_PMS == 1 && x.NU_FK_PFL == guardar[0].NU_FK_PFL).ToList(); + + + foreach (var cu in existe_pms_c) + { + cu.BL_ESTADO_PMS = 0; + _context.PERMISOSMs.Update(cu); + await _context.SaveChangesAsync(); + } + + foreach (var pms in guardar) + { + count++; + //Se comprueba existencia de cada permiso en base de datos + var existe_pms = (from dm in _context.PERMISOSMs + where dm.NU_FK_PFL == pms.NU_FK_PFL + && dm.NU_FK_MS == pms.NU_FK_MS + select dm).ToList(); + + if (existe_pms.Count() > 0) + { + //Si existe activamos estado 1 del perfil + existe_pms[0].BL_ESTADO_PMS = 1; + _context.Update(existe_pms[0]); + await _context.SaveChangesAsync(); + continue; + } + else + { + + if (pms == null) + { + error.Add($"Perfil por usuario #{count} sin valores"); + continue; + } + + //Se valida si el permiso a guardar tiene asignado microservicio padre o hijo + var validar_ms_hijo = (from dm in _context.MICROSERVICIOs + where dm.NU_PK_MS == pms.NU_FK_MS + && dm.NU_PADRE_MS != null + select dm).ToList(); + + if (validar_ms_hijo.Count() > 0) + { + var existe_permiso_padre = (from dm in _context.PERMISOSMs + where dm.NU_FK_MS == validar_ms_hijo[0].NU_PADRE_MS + && dm.NU_FK_PFL == pms.NU_FK_PFL + select dm).ToList(); + + if (existe_permiso_padre.Count() > 0) + { + existe_permiso_padre[0].BL_ESTADO_PMS = 1; + _context.Update(existe_permiso_padre[0]); + } + else + { + PERMISO padre = new PERMISO + { + NU_PK_PMS = count * (-1), + NU_FK_PFL = pms.NU_FK_PFL, + NU_FK_MS = validar_ms_hijo[0].NU_PADRE_MS, + BL_ESTADO_PMS = 1, + }; + + _context.Add(padre); + } + } + + pms.BL_ESTADO_PMS = 1; + _context.PERMISOSMs.Add(pms); + await _context.SaveChangesAsync(); + } + } + + dbContextTransaction.Commit(); + + List all = new List(); + + all.Add($"Total registros: {guardar.Count().ToString()}"); + all.Add($"Exitosos: {(guardar.Count() - error.Count()).ToString()}"); + all.Add($"Erroneos: {error.Count().ToString()}"); + + var flag_r = 0; + foreach (var r in error) + { + flag_r++; + all.Add($"Error #{flag_r}: {r}"); + } + + if (error.Count() > 0) + { + return Conflict(all.ToList()); + } + return Ok(); + } + catch (Exception ex) + { + //hacemos rollback si hay excepción + dbContextTransaction.Rollback(); + return BadRequest(ex.Message); + } + + } + } + } +} + diff --git a/Microservicios/MsUsuarios/Controllers/UsuariosController.cs b/Microservicios/MsUsuarios/Controllers/UsuariosController.cs new file mode 100644 index 0000000..af4727a --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/UsuariosController.cs @@ -0,0 +1,324 @@ +using MSAdminUsuarios.Context; +using Microsoft.AspNetCore.Mvc; +using MSAdminUsuarios.Dto; +using Security; +using MSAdminUsuarios.Models; + +namespace MSAdminUsuarios.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UsuariosController : ControllerBase + { + private readonly ModelContext _context; + private readonly Encripter _encript = new(); + + public UsuariosController(ModelContext context) + { + _context = context; + } + + [HttpPost("UserBene")] + public async Task PostUserBeneficiario(string TX_IDENTIFICACION_AFIL) + { + ErrorModel _errorModel = new ErrorModel(); + try + { + if(TX_IDENTIFICACION_AFIL == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Ingrese un dato"); + return Ok(_errorModel); + } + + USUARIO user = new USUARIO(); + + user.TX_PKDOC_USUMS = TX_IDENTIFICACION_AFIL; + user.TX_LOGINNAME_USUMS = TX_IDENTIFICACION_AFIL; + user.TX_PASSWORD_USUMS = _encript.EncryptPwd(TX_IDENTIFICACION_AFIL); + + _context.USUARIOSMs.Add(user); + await _context.SaveChangesAsync(); + + _errorModel.error = false; + _errorModel.cuerpo.Add("Usuario creado"); + return Ok(_errorModel); + + } + catch(Exception) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Problemas con la base de datos"); + return BadRequest(_errorModel); + + } + } + + [HttpGet("Iniciales")] + public async Task GetIniciales(string TX_PKDOC_USUMS) + { + try + { + var consulta = _context.USUARIOSMs.FirstOrDefault(x => x.TX_PKDOC_USUMS == TX_PKDOC_USUMS); + + var ininame = consulta.TX_PRIMERNOM_USUMS.ToCharArray(); + var iniape = consulta.TX_PRIMERAPELL_USUMS.ToCharArray(); + + NameObject nombreObjeto = new NameObject() + { + iniciales = ininame[0].ToString() + iniape[0].ToString(), + nombre = consulta.TX_PRIMERNOM_USUMS.ToString() + " " + consulta.TX_PRIMERAPELL_USUMS.ToString(), + pk = consulta.NU_PK_USUMS, + }; + + return Ok(nombreObjeto); + } + catch (Exception ex) + { + return BadRequest(ex); + } + } + + [HttpGet] + public async Task GetUsuarios() + { + try + { + List consulta = new List(); + + consulta = (from dm in _context.USUARIOSMs + where dm.NU_ESTADO_USUMS >= 0 + select dm).ToList(); + + return Ok(consulta); + } + catch (Exception ex) + { + return BadRequest(ex); + } + } + + //[HttpGet("TESTERROR")] + //public async Task GetError() + //{ + // try + // { + // List consulta = new List(); + + // consulta.Add("Total errores: 10"); + // consulta.Add("guardados: 5"); + // consulta.Add("erroneos: 5"); + // consulta.Add("error #1: hskbjnklsnñksnñksnmñskñkmss"); + // consulta.Add("error #2: hskbjnklsnñksnñksnmñskñkmss"); + // consulta.Add("error #3: hskbjnklsnñksnñksnmñskñkmss"); + + // return Ok(consulta); + // } + // catch (Exception ex) + // { + // return BadRequest(ex); + // } + //} + + [HttpPost] + public async Task GuardarUsuarios(USUARIO usuario) + { + try + { + if (usuario == null) return Conflict(); + + if (usuario.TX_CORREO_USUMS == null) return Conflict("Indique algún correo."); + + var login_name = usuario.TX_CORREO_USUMS.Split('@'); + + var existe_login = _context.USUARIOSMs.Where(x => x.TX_LOGINNAME_USUMS == login_name[0]).Count(); + + if (existe_login > 0) return Conflict("El login ya está en uso"); + + usuario.TX_LOGINNAME_USUMS = login_name[0]; + + if (usuario.TX_PKDOC_USUMS == null) + { + var ult = _context.USUARIOSMs.Max(x => x.NU_PK_USUMS) + 1; + usuario.TX_PKDOC_USUMS = ult.ToString(); + } + + if (usuario.TX_PASSWORD_USUMS != null) + { + usuario.TX_PASSWORD_USUMS = _encript.EncryptPwd(usuario.TX_PASSWORD_USUMS); + } + + + + _context.USUARIOSMs.Add(usuario); + await _context.SaveChangesAsync(); + return Ok(); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpPatch] + public async Task EditarUsuarios(USUARIO editado) + { + ErrorModel _errorModel = new ErrorModel(); + + using (var dbContextTransaction = _context.Database.BeginTransaction()) + { + try + { + if (editado == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Ingrese datos"); + return Conflict(_errorModel); + } + + var existe = _context.USUARIOSMs.FirstOrDefault(x => x.NU_PK_USUMS == editado.NU_PK_USUMS); + + if (existe == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("El usuario que desea editar no existe"); + return Conflict(_errorModel); + } + + existe.TX_PRIMERNOM_USUMS = editado.TX_PRIMERNOM_USUMS; + existe.TX_SEGUNDONOM_USUMS = editado.TX_SEGUNDONOM_USUMS; + existe.TX_PRIMERAPELL_USUMS = editado.TX_PRIMERAPELL_USUMS; + existe.TX_SEGUNDONOM_USUMS = editado.TX_SEGUNDONOM_USUMS; + existe.TX_CELULAR_USUMS = editado.TX_CELULAR_USUMS; + existe.TX_TELEFONO_USUMS = editado.TX_TELEFONO_USUMS; + existe.TX_CORREO_USUMS = editado.TX_CORREO_USUMS; + existe.TX_DIRECCION_USUMS = editado.TX_DIRECCION_USUMS; + + ErrorModel errorPFLxUSUMS = await ActualizarRelaciones(existe.TX_PKDOC_USUMS, editado.TX_PKDOC_USUMS); + + if (errorPFLxUSUMS.error == true) + { + _errorModel.listaErrores.Add(errorPFLxUSUMS.cuerpo[0]); + return Conflict(_errorModel); + } + + _errorModel.listaErrores.Add(errorPFLxUSUMS.cuerpo[0]); + + existe.NU_TIPODOC_USUMS = editado.NU_TIPODOC_USUMS; + existe.TX_PKDOC_USUMS = editado.TX_PKDOC_USUMS; + + _context.USUARIOSMs.Update(existe); + _context.SaveChanges(); + + _errorModel.error = false; + _errorModel.cuerpo.Add("Usuario actualizado."); + dbContextTransaction.Commit(); + return Ok(_errorModel); + } + catch + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Problema con la base de datos."); + dbContextTransaction.Rollback(); + return BadRequest(_errorModel); + } + } + } + + [HttpPatch("NumeroDocumento")] + public async Task EditarNoDocumentoUsuarios(USUARIO editado) + { + ErrorModel _errorModel = new ErrorModel(); + + using (var dbContextTransaction = _context.Database.BeginTransaction()) + { + try + { + if (editado == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Ingrese datos"); + return Conflict(_errorModel); + } + + var existe = _context.USUARIOSMs.FirstOrDefault(x => x.NU_PK_USUMS == editado.NU_PK_USUMS); + + if (existe == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("El usuario que desea editar no existe"); + return Conflict(_errorModel); + } + + if (existe.TX_PKDOC_USUMS != editado.TX_PKDOC_USUMS || existe.NU_TIPODOC_USUMS != editado.NU_TIPODOC_USUMS) + { + ErrorModel errorPFLxUSUMS = await ActualizarRelaciones(existe.TX_PKDOC_USUMS, editado.TX_PKDOC_USUMS); + + if(errorPFLxUSUMS.error == true) { + _errorModel.listaErrores.Add(errorPFLxUSUMS.cuerpo[0]); + return Conflict(_errorModel); + } + + _errorModel.listaErrores.Add(errorPFLxUSUMS.cuerpo[0]); + + existe.NU_TIPODOC_USUMS = editado.NU_TIPODOC_USUMS; + existe.TX_PKDOC_USUMS = editado.TX_PKDOC_USUMS; + } + + _context.USUARIOSMs.Update(existe); + await _context.SaveChangesAsync(); + + _errorModel.error = false; + _errorModel.cuerpo.Add("Documento y tipo actualizados."); + dbContextTransaction.Commit(); + return Ok(_errorModel); + } + catch + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Problema con la base de datos."); + dbContextTransaction.Rollback(); + return BadRequest(_errorModel); + } + } + } + + [HttpPatch("Perfil_usu")] + public async Task ActualizarRelaciones(string TX_PKDOC_USUMS_anterior, string TX_PKDOC_USUMS_nuevo) + { + var _errorModel = new ErrorModel(); + try + { + var existe_any = _context.PERFILESPORUSUARIOs.FirstOrDefault(x => x.TX_FKDOC_USUMS == TX_PKDOC_USUMS_anterior); + + if (existe_any == null) + { + _errorModel.error = false; + _errorModel.cuerpo.Add($"No existen Perfiles para {TX_PKDOC_USUMS_anterior}"); + return _errorModel; + } + + List existe = _context.PERFILESPORUSUARIOs.Where(x => x.TX_FKDOC_USUMS == TX_PKDOC_USUMS_anterior).ToList(); + + foreach (var r in existe) + { + r.TX_FKDOC_USUMS = TX_PKDOC_USUMS_nuevo; + _context.PERFILESPORUSUARIOs.Update(r); + } + + await _context.SaveChangesAsync(); + _errorModel.error = false; + _errorModel.cuerpo.Add("Perfiles Actualizados."); + return _errorModel; + + } + catch + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Problema con la base de datos PERFILES POR USUARIO."); + return _errorModel; + } + } + } +} + diff --git a/Microservicios/MsUsuarios/Dto/NameObject.cs b/Microservicios/MsUsuarios/Dto/NameObject.cs new file mode 100644 index 0000000..7254520 --- /dev/null +++ b/Microservicios/MsUsuarios/Dto/NameObject.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace MSAdminUsuarios.Dto +{ + public class NameObject + { + public string? nombre { get; set; } + public string? iniciales { get; set; } + public int? pk { get; set; } + } +} diff --git a/Microservicios/MsUsuarios/MSAdminUsuarios.csproj b/Microservicios/MsUsuarios/MSAdminUsuarios.csproj new file mode 100644 index 0000000..8566351 --- /dev/null +++ b/Microservicios/MsUsuarios/MSAdminUsuarios.csproj @@ -0,0 +1,25 @@ + + + + net6.0 + enable + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/Microservicios/MsUsuarios/MSAdminUsuarios.sln b/Microservicios/MsUsuarios/MSAdminUsuarios.sln new file mode 100644 index 0000000..0faa6bc --- /dev/null +++ b/Microservicios/MsUsuarios/MSAdminUsuarios.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32519.379 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSAdminUsuarios", "MSAdminUsuarios.csproj", "{744A8996-991B-4863-A299-EB4FB7722BD0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Auth", "..\Auth\Auth.csproj", "{EE1743C5-2F34-4892-AD3B-31E85311B2EC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {744A8996-991B-4863-A299-EB4FB7722BD0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {744A8996-991B-4863-A299-EB4FB7722BD0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {744A8996-991B-4863-A299-EB4FB7722BD0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {744A8996-991B-4863-A299-EB4FB7722BD0}.Release|Any CPU.Build.0 = Release|Any CPU + {EE1743C5-2F34-4892-AD3B-31E85311B2EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EE1743C5-2F34-4892-AD3B-31E85311B2EC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EE1743C5-2F34-4892-AD3B-31E85311B2EC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EE1743C5-2F34-4892-AD3B-31E85311B2EC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {175A355C-9E8C-4C30-A2A5-7B604B4EB9E9} + EndGlobalSection +EndGlobal diff --git a/Microservicios/MsUsuarios/Models/ErrorModel.cs b/Microservicios/MsUsuarios/Models/ErrorModel.cs new file mode 100644 index 0000000..3037dc4 --- /dev/null +++ b/Microservicios/MsUsuarios/Models/ErrorModel.cs @@ -0,0 +1,17 @@ +namespace MSAdminUsuarios.Models +{ + public class ErrorModel + { + public bool error { get; set; } = false; + public List cuerpo { get; set; } = new List(); + public List? listaErrores { get; set; } = new List(); + + public ErrorModel() + { + error = false; + cuerpo = new List(); + listaErrores = new List(); + } + + } +} diff --git a/Microservicios/MsUsuarios/Program.cs b/Microservicios/MsUsuarios/Program.cs new file mode 100644 index 0000000..7dc2462 --- /dev/null +++ b/Microservicios/MsUsuarios/Program.cs @@ -0,0 +1,61 @@ +using MSAdminUsuarios.Context; +using Microsoft.EntityFrameworkCore; +using Security; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +// Cadena de Conexion a Bases de Datos +var connectionString = builder.Configuration.GetConnectionString("DBPrueba"); +// var connectionString = builder.Configuration.GetConnectionString("DBProd"); + +// Configuración del DbContext +builder.Services.AddDbContext(options => +{ + options.UseOracle( + connectionString, + options => options.UseOracleSQLCompatibility("11") + ); +}); + +// Enable Cors +builder.Services.AddCors(options => { + options.AddPolicy(name: "widthoutCors", + builder => { + builder.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); +}); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment() || app.Environment.IsProduction()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); + app.UseCors("widthoutCors"); +} + +if(app.Environment.IsDevelopment()) +{ + Environment.SetEnvironmentVariable("Mode", "Dev"); +} else +{ + Environment.SetEnvironmentVariable("Mode", "Prod"); +} + +// app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/Microservicios/MsUsuarios/Properties/launchSettings.json b/Microservicios/MsUsuarios/Properties/launchSettings.json new file mode 100644 index 0000000..f25688b --- /dev/null +++ b/Microservicios/MsUsuarios/Properties/launchSettings.json @@ -0,0 +1,32 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:63935", + "sslPort": 44396 + } + }, + "profiles": { + "MicroservicioAdminUsuarios": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7292;http://localhost:5292", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "MySecretKey": "_ll@v3Segur1d4d!123", + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Microservicios/MsUsuarios/appsettings.Development.json b/Microservicios/MsUsuarios/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Microservicios/MsUsuarios/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Microservicios/MsUsuarios/appsettings.json b/Microservicios/MsUsuarios/appsettings.json new file mode 100644 index 0000000..e1a4256 --- /dev/null +++ b/Microservicios/MsUsuarios/appsettings.json @@ -0,0 +1,13 @@ +{ + "ConnectionStrings": { + "DBPrueba": "user id=HIMSCAP;password=ITTASA2017;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=181.129.245.90)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PROYECTOS)))", + "DBProd": "user id=HIMSCAP;password=ITTASA2017;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.0.194)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PROYECTOS)))" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}