From 25ca8289cdcd3c683b55a6d2817f3d134cf86239 Mon Sep 17 00:00:00 2001 From: Jhonatan Pelaez Date: Wed, 25 Oct 2023 09:05:37 -0500 Subject: [PATCH 1/5] se agrega LDap --- BackApiGateway.sln | 7 + LdapLoginLib/LdapLoginLib.csproj | 14 ++ LdapLoginLib/LdapUser.cs | 103 ++++++++++++++ LdapLoginLib/LoginLib.cs | 133 ++++++++++++++++++ .../MsUsuarios/Controllers/AuthController.cs | 40 +++++- .../MsUsuarios/MSAdminUsuarios.csproj | 1 + 6 files changed, 291 insertions(+), 7 deletions(-) create mode 100644 LdapLoginLib/LdapLoginLib.csproj create mode 100644 LdapLoginLib/LdapUser.cs create mode 100644 LdapLoginLib/LoginLib.cs diff --git a/BackApiGateway.sln b/BackApiGateway.sln index c426519..7f79220 100644 --- a/BackApiGateway.sln +++ b/BackApiGateway.sln @@ -17,6 +17,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSAdminUsuarios", "Microser EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegradorBE", "Microservicios\IntegradorBE\IntegradorBE.csproj", "{E3B575F9-4A18-43E6-A542-7CC29B086752}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LdapLoginLib", "LdapLoginLib\LdapLoginLib.csproj", "{6E864339-08B2-4C2F-909C-FCF0392E3F6D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -39,6 +41,10 @@ Global {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 + {6E864339-08B2-4C2F-909C-FCF0392E3F6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6E864339-08B2-4C2F-909C-FCF0392E3F6D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6E864339-08B2-4C2F-909C-FCF0392E3F6D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6E864339-08B2-4C2F-909C-FCF0392E3F6D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -48,6 +54,7 @@ Global {76522272-9D28-4168-8296-AFC933D22650} = {F491CF9B-9CF8-4F3B-BBD7-A282F7DC1D6D} {D0B80363-4C96-413F-8C82-48FCF2CD7F57} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} {E3B575F9-4A18-43E6-A542-7CC29B086752} = {A449A86B-39E4-4EEB-B7C6-B6B12A0CBD2E} + {6E864339-08B2-4C2F-909C-FCF0392E3F6D} = {F491CF9B-9CF8-4F3B-BBD7-A282F7DC1D6D} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {EC576D5A-ADE3-40CC-BF55-7E52E6F18AC4} diff --git a/LdapLoginLib/LdapLoginLib.csproj b/LdapLoginLib/LdapLoginLib.csproj new file mode 100644 index 0000000..4c2dabd --- /dev/null +++ b/LdapLoginLib/LdapLoginLib.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/LdapLoginLib/LdapUser.cs b/LdapLoginLib/LdapUser.cs new file mode 100644 index 0000000..c5a4fde --- /dev/null +++ b/LdapLoginLib/LdapUser.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LdapLoginLib +{ + public class LdapUser + { + /// + /// The unique identifier for the user (mandatory). + /// Example: "jdoe" + /// + public string Uid { get; set; } + + /// + /// The common name of the user. + /// Example: "John Doe" + /// + public string? Cn { get; set; } + + /// + /// The user's given name. + /// Example: "John" + /// + public string? GivenName { get; set; } + + /// + /// The user's surname. + /// Example: "Doe" + /// + public string? Sn { get; set; } + + /// + /// The user's email address. + /// Example: "jdoe@example.com" + /// + public string? Mail { get; set; } + + /// + /// The status of the user's internet account. + /// Example: "Active" + /// + public string? InetUserStatus { get; set; } + + /// + /// The organization the user belongs to. + /// Example: "Acme Inc.", currently "Sede" + /// + public string? O { get; set; } + + /// + /// The status of the user's account as boolean. + /// Example: true or false + /// + public bool? IsActive { get; set; } = null; + + } + + + /******************************************** + * * + * Discared / not in used * + * * + ******************************************** + + /// + /// The user's password. + /// Example: "P@ssw0rd" + /// + public string? UserPassword { get; set; } + + /// + /// The type of employee (e.g., full-time, part-time). + /// Example: "Full-Time", currently numbers + /// + public string? EmployeeType { get; set; } + + /// + /// The business category of the user. + /// Example: "Sales" + /// + public string? BusinessCategory { get; set; } + + /// + /// The employee's unique identification number. + /// Example: "E12345" + /// + public string? EmployeeNumber { get; set; } + + /// + /// The license information for the user. + /// Example: "Licensed for Software X, Y, and Z" + /// + public string? NsLicensedFor { get; set; } + + + ******************************************** + * * + ********************************************/ + +} diff --git a/LdapLoginLib/LoginLib.cs b/LdapLoginLib/LoginLib.cs new file mode 100644 index 0000000..6f9035f --- /dev/null +++ b/LdapLoginLib/LoginLib.cs @@ -0,0 +1,133 @@ +using System.DirectoryServices.Protocols; + +namespace LdapLoginLib +{ + public class LoginLib + { + private const string _ldapServer = "10.31.3.13"; + private const int _ldapPort = 389; + + private const string _ldapDn = "ou=People,o=unal.edu.co"; //uid=pdocente, + //string ldapPassword = "TJBjzn64"; + + + + public static bool Login(string uid, string password, string ldapDn = _ldapDn) + { + + using (LdapConnection ldapConnection = new($"{_ldapServer}:{_ldapPort}")) + { + try + { + string ldapUserDn = $"uid={uid},{_ldapDn}"; + + // Set LDAP connection options + ldapConnection.SessionOptions.SecureSocketLayer = false; + ldapConnection.AuthType = AuthType.Basic; + ldapConnection.Credential = new System.Net.NetworkCredential(ldapUserDn, password); + + // Attempt to bind (authenticate) the user + ldapConnection.Bind(); + + return _userIsActive(ldapConnection, ldapUserDn); + } + catch (LdapException ldapEx) + { + //Console.WriteLine($"Authentication failed: {ldapEx.Message}"); + throw new Exception(_getErrorMessage(ldapEx.ErrorCode, ldapEx.Message)); + } + catch (Exception ex) + { + //Console.WriteLine($"An error occurred: {ex.Message}"); + throw new Exception($"Ocurrió un error: {ex.Message}"); + } + + } + } + + private static bool _userIsActive(LdapConnection ldapConnection, string ldapUserDn) + { + //ldapUserDn = $"uid=acbuitragoc,{_ldapDn}"; + SearchRequest searchRequest = new( + ldapUserDn, + "(objectClass=*)", + SearchScope.Base, + "InetUserStatus" + ); + + SearchResponse searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest); + + if (searchResponse.Entries.Count > 0) + { + SearchResultEntry entry = searchResponse.Entries[0]; + + string? inetUserStatus = entry.Attributes["inetUserStatus"][0].ToString(); + + if (inetUserStatus != null) + { + return inetUserStatus.ToLower().Trim() == "active" ? true : false; + } + throw new Exception(); + } + else + { + throw new Exception($"Usuario o atributo no encontrado."); + } + } + + + private static LdapUser _getUserData(LdapConnection ldapConnection, string ldapUserDn, string[] attributesToReturn) + { + + return new LdapUser(); + + + //SearchRequest searchRequest = new( + // searchBase, + // ldapFilter, + // SearchScope.Subtree, + // attributesToReturn + //); + + //SearchResponse searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest); + + + //if (searchResponse != null && searchResponse.Entries.Count > 0) + //{ + // SearchResultEntry entry = searchResponse.Entries[0]; + + // // Access and process user attributes here + // foreach (DirectoryAttribute attribute in entry.Attributes.Values) + // { + // string attributeName = attribute.Name; + // string[] attributeValues = (string[])attribute.GetValues(typeof(string)); + + // // Process or display attribute values as needed + // Console.WriteLine($"{attributeName}: {string.Join(", ", attributeValues)}"); + // } + //} + //else + //{ + // throw new Exception($"Usuario o atributos no encontrados."); + //} + } + + + private static string _getErrorMessage(int errorCode, string errorMessage) + { + // Map LDAP error codes to error messages + + switch (errorCode) + { + case 49: + return "Error de credenciales: nombre de usuario o contraseña incorrectos"; + case 52: + return "Error de autenticación: cuenta está deshabilitada"; + case 81: + return "Error de servidor: no disponible"; + default: + return errorMessage; + } + } + } +} \ No newline at end of file diff --git a/Microservicios/MsUsuarios/Controllers/AuthController.cs b/Microservicios/MsUsuarios/Controllers/AuthController.cs index 8053c10..e32e902 100644 --- a/Microservicios/MsUsuarios/Controllers/AuthController.cs +++ b/Microservicios/MsUsuarios/Controllers/AuthController.cs @@ -1,6 +1,8 @@ +using LdapLoginLib; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using MSAdminUsuarios.Context; +using Newtonsoft.Json.Linq; using Security; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; @@ -29,16 +31,40 @@ namespace MSAdminUsuarios.Controllers 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)); + USUARIO? userldap = _context.USUARIOSMs.FirstOrDefault(u => u.TX_LOGINNAME_USUMS == login.TX_LOGINNAME_USUMS); + if(userldap.BL_VIENELDAP_USUMS == 1) + { + bool boolldap = LoginLib.Login(login.TX_LOGINNAME_USUMS, login.TX_PASSWORD_USUMS); + if( boolldap == true) { + string token = Token(userldap); + return Ok(new + { + token = token, + user = userldap.TX_PKDOC_USUMS + }); + } + else + { + return BadRequest(); + } + }else if(userldap.BL_VIENELDAP_USUMS != 1) + { + 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"); + if (user == null) return BadRequest("Usuario o contrase�a incorrectos"); - string token = Token(user); + string token = Token(user); + + return Ok(new + { + token = token, + user = user.TX_PKDOC_USUMS + }); + }else + { + return BadRequest("Error"); + } - return Ok(new { - token = token, - user = user.TX_PKDOC_USUMS - }); } catch (Exception e) { diff --git a/Microservicios/MsUsuarios/MSAdminUsuarios.csproj b/Microservicios/MsUsuarios/MSAdminUsuarios.csproj index f58f1e9..954aa91 100644 --- a/Microservicios/MsUsuarios/MSAdminUsuarios.csproj +++ b/Microservicios/MsUsuarios/MSAdminUsuarios.csproj @@ -22,6 +22,7 @@ + From f97a42f296201d62147de14b02c749d576ac0ec7 Mon Sep 17 00:00:00 2001 From: "Dario F. Gomez Z" Date: Tue, 7 Nov 2023 08:35:29 -0500 Subject: [PATCH 2/5] Ajuste Revision 2 Usuarios --- .../MsUsuarios/Context/ModelContext.cs | 39 ++++++++++- .../MsUsuarios/Context/USUARIOSTEMP.cs | 22 ++++++ .../MsUsuarios/Controllers/AuthController.cs | 1 + .../Controllers/UsuariosTempController.cs | 70 +++++++++++++++++++ .../MsUsuarios/Utils/RabbitMQService.cs | 55 +++++++++------ 5 files changed, 165 insertions(+), 22 deletions(-) create mode 100644 Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs create mode 100644 Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs diff --git a/Microservicios/MsUsuarios/Context/ModelContext.cs b/Microservicios/MsUsuarios/Context/ModelContext.cs index a63317d..ab407c8 100644 --- a/Microservicios/MsUsuarios/Context/ModelContext.cs +++ b/Microservicios/MsUsuarios/Context/ModelContext.cs @@ -22,7 +22,8 @@ namespace MSAdminUsuarios.Context public virtual DbSet PERFILESMs { get; set; } = null!; public virtual DbSet PERFILESPORUSUARIOs { get; set; } = null!; public virtual DbSet USUARIOSMs { get; set; } = null!; - public virtual DbSet CORREOSAREAMS { get; set; } = null!; + public virtual DbSet CORREOSAREAMS { get; set; } = null!; + public virtual DbSet USUARIOSTEMP { get; set; } = null!; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { @@ -48,7 +49,7 @@ namespace MSAdminUsuarios.Context } else { - modelBuilder.HasDefaultSchema("ADMIN"); + modelBuilder.HasDefaultSchema("ADMIN"); } @@ -109,6 +110,40 @@ namespace MSAdminUsuarios.Context }); + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.NU_PK_USUTMP) + .HasName("USUARIOSTEMP_PK"); + + entity.ToTable("USUARIOSTEMP"); + + entity.Property(e => e.NU_PK_USUTMP).HasPrecision(10); + + entity.Property(e => e.FE_INICIOACTIVACION_USUTMP).HasColumnType("DATE"); + + entity.Property(e => e.FE_FINACTIVACION_USUTMP).HasColumnType("DATE"); + + entity.Property(e => e.NU_ESTADO_USUTMP).HasPrecision(10); + + entity.Property(e => e.NU_TIPODOC_USUTMP).HasPrecision(10); + + entity.Property(e => e.TX_CORREO_USUTMP).HasMaxLength(200); + + entity.Property(e => e.TX_IDENTIFICACION_USUTMP).HasMaxLength(100); + + entity.Property(e => e.TX_NOMBREPVD_USUTMP).HasMaxLength(1999); + + entity.Property(e => e.TX_PRIMERAPELL_USUTMP).HasMaxLength(200); + + entity.Property(e => e.TX_PRIMERNOM_USUTMP).HasMaxLength(200); + + entity.Property(e => e.TX_SEGUNDOAPELL_USUTMP).HasMaxLength(200); + + entity.Property(e => e.TX_SEGUNDONOM_USUTMP).HasMaxLength(200); + + entity.Property(e => e.TX_TELEFONO_USUTMP).HasMaxLength(100); + }); + OnModelCreatingPartial(modelBuilder); } diff --git a/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs b/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs new file mode 100644 index 0000000..8f47b87 --- /dev/null +++ b/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; + +namespace MSAdminUsuarios.Context +{ + public partial class USUARIOSTEMP + { + public int NU_PK_USUTMP { get; set; } + public int? NU_TIPODOC_USUTMP { get; set; } + public string? TX_IDENTIFICACION_USUTMP { get; set; } + public string? TX_PRIMERNOM_USUTMP { get; set; } + public string? TX_SEGUNDONOM_USUTMP { get; set; } + public string? TX_PRIMERAPELL_USUTMP { get; set; } + public string? TX_SEGUNDOAPELL_USUTMP { get; set; } + public string? TX_NOMBREPVD_USUTMP { get; set; } + public string? TX_CORREO_USUTMP { get; set; } + public string? TX_TELEFONO_USUTMP { get; set; } + public int? NU_ESTADO_USUTMP { get; set; } + public DateTime? FE_INICIOACTIVACION_USUTMP { get; set; } + public DateTime? FE_FINACTIVACION_USUTMP { get; set; } + } +} diff --git a/Microservicios/MsUsuarios/Controllers/AuthController.cs b/Microservicios/MsUsuarios/Controllers/AuthController.cs index e32e902..ad498d8 100644 --- a/Microservicios/MsUsuarios/Controllers/AuthController.cs +++ b/Microservicios/MsUsuarios/Controllers/AuthController.cs @@ -32,6 +32,7 @@ namespace MSAdminUsuarios.Controllers if (login.TX_PASSWORD_USUMS == null) return BadRequest("Es necesario ingresar una contrase�a"); USUARIO? userldap = _context.USUARIOSMs.FirstOrDefault(u => u.TX_LOGINNAME_USUMS == login.TX_LOGINNAME_USUMS); + if (userldap == null) return BadRequest("usuario"); if(userldap.BL_VIENELDAP_USUMS == 1) { bool boolldap = LoginLib.Login(login.TX_LOGINNAME_USUMS, login.TX_PASSWORD_USUMS); diff --git a/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs b/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs new file mode 100644 index 0000000..441cb9f --- /dev/null +++ b/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs @@ -0,0 +1,70 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using MSAdminUsuarios.Context; +using MSAdminUsuarios.Models; + +namespace MSAdminUsuarios.Controllers +{ + [Route("[controller]")] + [ApiController] + public class UsuariosTempController : ControllerBase + { + private readonly ModelContext _context; + private readonly ILogger _logger; + private ErrorModel _errorModel; + + public UsuariosTempController(ModelContext context, ILogger logger) + { + _context = context; + _logger = logger; + _errorModel = new ErrorModel(); + } + + [HttpGet] + public async Task Get() + { + _errorModel = new ErrorModel(); + try + { + List externos = await _context.USUARIOSTEMP.OrderBy(q => q.NU_PK_USUTMP).ToListAsync(); + + return Ok(externos); + } + catch (Exception) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Error con la base de datos."); + return BadRequest(_errorModel); + } + } + + [HttpPost] + public async Task Post(USUARIOSTEMP nuevo) + { + _errorModel = new ErrorModel(); + try + { + if (nuevo == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("No se envió solicitud."); + return Conflict(_errorModel); + } + + _context.USUARIOSTEMP.Add(nuevo); + await _context.SaveChangesAsync(); + + _errorModel.error = false; + _errorModel.cuerpo.Add("Solicitud de usuario temporal guardado correctamente."); + return Ok(_errorModel); + } + catch (Exception) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Error con la base de datos."); + return BadRequest(_errorModel); + } + } + } +} diff --git a/Microservicios/MsUsuarios/Utils/RabbitMQService.cs b/Microservicios/MsUsuarios/Utils/RabbitMQService.cs index a7db11d..4ccd70e 100644 --- a/Microservicios/MsUsuarios/Utils/RabbitMQService.cs +++ b/Microservicios/MsUsuarios/Utils/RabbitMQService.cs @@ -66,6 +66,12 @@ namespace MSAdminUsuarios.Utils ); } + channel.QueueBind( + queue: $"{exchangeName}.Usuarios", + exchange: exchangeName, + routingKey: $"{exchangeName}.Usuarios.*.*" + ); + return channel; } @@ -74,37 +80,46 @@ namespace MSAdminUsuarios.Utils RabbitMQConfig mqConfig = builder.Configuration.GetSection("RabbitMQConfig").Get(); var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog()); - //var logger = loggerFactory.CreateLogger("Rabbit2"); - //logger.LogInformation("Inicia Rabbitmq con"); - - ConnectionFactory factory = new() + try { - HostName = mqConfig.HostName, - UserName = mqConfig.UserName, - Password = mqConfig.Password, - }; + //var logger = loggerFactory.CreateLogger("Rabbit2"); + //logger.LogInformation("Inicia Rabbitmq con"); - IConnection connection = factory.CreateConnection(); - IModel channel = connection.CreateModel(); + ConnectionFactory factory = new() + { + HostName = mqConfig.HostName, + UserName = mqConfig.UserName, + Password = mqConfig.Password, + }; - EventingBasicConsumer consumer = new(channel); + IConnection connection = factory.CreateConnection(); + IModel channel = connection.CreateModel(); - consumer.Received += RabbitMQService.ConsumeRabbitMQEvent; + EventingBasicConsumer consumer = new(channel); - List queues = new() + consumer.Received += RabbitMQService.ConsumeRabbitMQEvent; + + List queues = new() { $"{projectName}.PerfilesPorUsuario", $"{projectName}.Usuarios", }; - foreach (var queue in queues) - { - channel.BasicConsume( - queue: queue, - autoAck: false, - consumer: consumer - ); + foreach (var queue in queues) + { + channel.BasicConsume( + queue: queue, + autoAck: false, + consumer: consumer + ); + } } + catch (Exception ex) + { + + Console.WriteLine(ex.Message); + } + } From 848232b5855f9736bc25d2cf12565f92c23b7c3c Mon Sep 17 00:00:00 2001 From: "Dario F. Gomez Z" Date: Mon, 27 Nov 2023 08:52:45 -0500 Subject: [PATCH 3/5] Ajustes UsuariosTemp v1 --- .../MsUsuarios/Context/ModelContext.cs | 24 ++++++------- .../MsUsuarios/Context/USUARIOSTEMP.cs | 20 +++++------ .../Controllers/UsuariosTempController.cs | 36 +++++++++++++++++++ Microservicios/MsUsuarios/Dto/UsuarioDTO.cs | 1 + 4 files changed, 59 insertions(+), 22 deletions(-) diff --git a/Microservicios/MsUsuarios/Context/ModelContext.cs b/Microservicios/MsUsuarios/Context/ModelContext.cs index ab407c8..f9f9b50 100644 --- a/Microservicios/MsUsuarios/Context/ModelContext.cs +++ b/Microservicios/MsUsuarios/Context/ModelContext.cs @@ -119,29 +119,29 @@ namespace MSAdminUsuarios.Context entity.Property(e => e.NU_PK_USUTMP).HasPrecision(10); - entity.Property(e => e.FE_INICIOACTIVACION_USUTMP).HasColumnType("DATE"); - entity.Property(e => e.FE_FINACTIVACION_USUTMP).HasColumnType("DATE"); - entity.Property(e => e.NU_ESTADO_USUTMP).HasPrecision(10); + entity.Property(e => e.FE_INICIOACTIVACION_USUTMP).HasColumnType("DATE"); - entity.Property(e => e.NU_TIPODOC_USUTMP).HasPrecision(10); + entity.Property(e => e.NU_ESTADO_USUMS).HasPrecision(10); - entity.Property(e => e.TX_CORREO_USUTMP).HasMaxLength(200); + entity.Property(e => e.NU_TIPODOC_USUMS).HasPrecision(10); - entity.Property(e => e.TX_IDENTIFICACION_USUTMP).HasMaxLength(100); + entity.Property(e => e.TX_CORREO_USUMS).HasMaxLength(200); - entity.Property(e => e.TX_NOMBREPVD_USUTMP).HasMaxLength(1999); + entity.Property(e => e.TX_NOMBRE_PVD).HasMaxLength(1999); - entity.Property(e => e.TX_PRIMERAPELL_USUTMP).HasMaxLength(200); + entity.Property(e => e.TX_PKDOC_USUMS).HasMaxLength(200); - entity.Property(e => e.TX_PRIMERNOM_USUTMP).HasMaxLength(200); + entity.Property(e => e.TX_PRIMERAPELL_USUMS).HasMaxLength(200); - entity.Property(e => e.TX_SEGUNDOAPELL_USUTMP).HasMaxLength(200); + entity.Property(e => e.TX_PRIMERNOM_USUMS).HasMaxLength(200); - entity.Property(e => e.TX_SEGUNDONOM_USUTMP).HasMaxLength(200); + entity.Property(e => e.TX_SEGUNDOAPELL_USUMS).HasMaxLength(200); - entity.Property(e => e.TX_TELEFONO_USUTMP).HasMaxLength(100); + entity.Property(e => e.TX_SEGUNDONOM_USUMS).HasMaxLength(200); + + entity.Property(e => e.TX_TELEFONO_USUMS).HasMaxLength(200); }); OnModelCreatingPartial(modelBuilder); diff --git a/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs b/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs index 8f47b87..1c1eaef 100644 --- a/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs +++ b/Microservicios/MsUsuarios/Context/USUARIOSTEMP.cs @@ -6,16 +6,16 @@ namespace MSAdminUsuarios.Context public partial class USUARIOSTEMP { public int NU_PK_USUTMP { get; set; } - public int? NU_TIPODOC_USUTMP { get; set; } - public string? TX_IDENTIFICACION_USUTMP { get; set; } - public string? TX_PRIMERNOM_USUTMP { get; set; } - public string? TX_SEGUNDONOM_USUTMP { get; set; } - public string? TX_PRIMERAPELL_USUTMP { get; set; } - public string? TX_SEGUNDOAPELL_USUTMP { get; set; } - public string? TX_NOMBREPVD_USUTMP { get; set; } - public string? TX_CORREO_USUTMP { get; set; } - public string? TX_TELEFONO_USUTMP { get; set; } - public int? NU_ESTADO_USUTMP { get; set; } + public int? NU_TIPODOC_USUMS { get; set; } + public string? TX_PKDOC_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_NOMBRE_PVD { get; set; } + public string? TX_CORREO_USUMS { get; set; } + public string? TX_TELEFONO_USUMS { get; set; } + public int? NU_ESTADO_USUMS { get; set; } public DateTime? FE_INICIOACTIVACION_USUTMP { get; set; } public DateTime? FE_FINACTIVACION_USUTMP { get; set; } } diff --git a/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs b/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs index 441cb9f..3c50fdd 100644 --- a/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs +++ b/Microservicios/MsUsuarios/Controllers/UsuariosTempController.cs @@ -66,5 +66,41 @@ namespace MSAdminUsuarios.Controllers return BadRequest(_errorModel); } } + + [HttpPatch] + public async Task Patch(USUARIOSTEMP editado) + { + _errorModel = new ErrorModel(); + try + { + if (editado == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("No se envió solicitud."); + return Conflict(_errorModel); + } + + USUARIOSTEMP? existente = await _context.USUARIOSTEMP.FirstOrDefaultAsync(ut => ut.NU_PK_USUTMP == editado.NU_PK_USUTMP); + if (existente == null) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Diseño no encontrado."); + return Conflict(_errorModel); + } + + _context.Entry(existente).CurrentValues.SetValues(editado); + await _context.SaveChangesAsync(); + + _errorModel.error = false; + _errorModel.cuerpo.Add("Solicitud de usuario temporal guardado correctamente."); + return Ok(_errorModel); + } + catch (Exception) + { + _errorModel.error = true; + _errorModel.cuerpo.Add("Error con la base de datos."); + return BadRequest(_errorModel); + } + } } } diff --git a/Microservicios/MsUsuarios/Dto/UsuarioDTO.cs b/Microservicios/MsUsuarios/Dto/UsuarioDTO.cs index 2f26135..b97f07d 100644 --- a/Microservicios/MsUsuarios/Dto/UsuarioDTO.cs +++ b/Microservicios/MsUsuarios/Dto/UsuarioDTO.cs @@ -38,6 +38,7 @@ namespace MSAdminUsuarios.Dto public int? NU_MODALIDADCTT_USUMS { get; set; } public string? TX_SEDES_USUMS { get; set; } public int? NU_BLOQUEO_USUMS { get; set; } + public string? TX_UUID_USUMS { get; set; } public int? NU_TIPOUSUARIO_USUMS { get; set; } } } From d24b526f2f1ed66b84e9c99b215306a0a2853f3b Mon Sep 17 00:00:00 2001 From: "Dario F. Gomez Z" Date: Wed, 6 Dec 2023 14:11:53 -0500 Subject: [PATCH 4/5] Ajustes para MsAgendaMedica --- .../MsUsuarios/Context/ModelContext.cs | 4 +- Microservicios/MsUsuarios/Context/PERFIL.cs | 1 + .../MsUsuarios/Context/PERFILPORUSUARIO.cs | 2 +- .../Controllers/PerfilesController.cs | 7 + .../PerfilesPorUsuarioController.cs | 4 +- .../Controllers/UsuariosController.cs | 47 +++++- .../Dto/Externos/MsAgendaMedica/MedicoDto.cs | 31 ++++ .../MsUsuarios/Utils/GenericTools.cs | 87 ++++++++++ .../MsUsuarios/Utils/RabbitMQMessages.cs | 20 +++ .../MsUsuarios/Utils/RabbitMQService.cs | 154 ++++++++++-------- 10 files changed, 279 insertions(+), 78 deletions(-) create mode 100644 Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs create mode 100644 Microservicios/MsUsuarios/Utils/GenericTools.cs create mode 100644 Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs diff --git a/Microservicios/MsUsuarios/Context/ModelContext.cs b/Microservicios/MsUsuarios/Context/ModelContext.cs index f9f9b50..8e5decb 100644 --- a/Microservicios/MsUsuarios/Context/ModelContext.cs +++ b/Microservicios/MsUsuarios/Context/ModelContext.cs @@ -76,6 +76,8 @@ namespace MSAdminUsuarios.Context .HasName("PERFILESMS_PK"); entity.ToTable("PERFILESMS"); + + entity.Property(e => e.TX_UUID_PFL).HasMaxLength(40); }); @@ -86,7 +88,7 @@ namespace MSAdminUsuarios.Context entity.ToTable("PERFILESPORUSUARIO"); - entity.Property(e => e.TX_UUID_PFLXUSU).HasMaxLength(40); + entity.Property(e => e.TX_UUID_USUMS).HasMaxLength(40); }); diff --git a/Microservicios/MsUsuarios/Context/PERFIL.cs b/Microservicios/MsUsuarios/Context/PERFIL.cs index a002578..2491aed 100644 --- a/Microservicios/MsUsuarios/Context/PERFIL.cs +++ b/Microservicios/MsUsuarios/Context/PERFIL.cs @@ -10,6 +10,7 @@ namespace MSAdminUsuarios.Context public string? TX_PERFIL_PFL { get; set; } public int? BL_ESTADO_PFL { get; set; } = 1; public int? NU_ROL_PFL { get; set; } + public string? TX_UUID_PFL { get; set; } } } diff --git a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs index f13dbfd..f4cf927 100644 --- a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs +++ b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs @@ -9,7 +9,7 @@ namespace MSAdminUsuarios.Context public string? TX_FKDOC_USUMS { get; set; } public int? NU_FK_PFL { get; set; } public int? BL_ESTADO_PFLXUSU { get; set; } = 1; - public string? TX_UUID_PFLXUSU { get; set; } + public string? TX_UUID_USUMS { get; set; } } } diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs index 9e1a6a4..b86f9b0 100644 --- a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs +++ b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs @@ -39,6 +39,13 @@ namespace MSAdminUsuarios.Controllers if (guardado == null) return ValidationProblem(); + if (guardado.TX_UUID_PFL == null) + { + Guid uuid = Guid.NewGuid(); + var UUID = uuid.ToString(); + guardado.TX_UUID_PFL = UUID; + } + _context.PERFILESMs.Add(guardado); await _context.SaveChangesAsync(); return Ok(); diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs index 98e1a3b..0f1cff8 100644 --- a/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs +++ b/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs @@ -53,7 +53,7 @@ namespace MSAdminUsuarios.Controllers var count = 0; // 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(); + var existe_plfxusu = _context.PERFILESPORUSUARIOs.Where(x => x.BL_ESTADO_PFLXUSU == 1 && x.TX_UUID_USUMS == guardar[0].TX_UUID_USUMS).ToList(); foreach (var cu in existe_plfxusu) { @@ -68,7 +68,7 @@ namespace MSAdminUsuarios.Controllers //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 + && dm.TX_UUID_USUMS == pxu.TX_UUID_USUMS select dm).ToList(); if (existe_pxu.Count() > 0) diff --git a/Microservicios/MsUsuarios/Controllers/UsuariosController.cs b/Microservicios/MsUsuarios/Controllers/UsuariosController.cs index 5814db8..6752448 100644 --- a/Microservicios/MsUsuarios/Controllers/UsuariosController.cs +++ b/Microservicios/MsUsuarios/Controllers/UsuariosController.cs @@ -8,6 +8,11 @@ using Microsoft.EntityFrameworkCore; using System.Linq; using Microsoft.IdentityModel.Tokens; using RabbitMQ.Client; +using Newtonsoft.Json; +using System.Threading.Channels; +using MSAdminUsuarios.Dto.Externos.MsAgendaMedica; +using static MSAdminUsuarios.Utils.RabbitMQService; +using MSAdminUsuarios.Utils; namespace MSAdminUsuarios.Controllers { @@ -17,11 +22,12 @@ namespace MSAdminUsuarios.Controllers { private readonly ModelContext _context; private readonly Encripter _encript = new(); - //private readonly IModel _channel; + private readonly IModel _channel; - public UsuariosController(ModelContext context) + public UsuariosController(ModelContext context, IModel channel) { _context = context; + _channel = channel; } //public UsuariosController(ModelContext context, IModel channel) //{ @@ -208,7 +214,7 @@ namespace MSAdminUsuarios.Controllers Guid uuid = Guid.NewGuid(); var UUID = uuid.ToString(); usuario.TX_UUID_USUMS = UUID; - } + } _context.USUARIOSMs.Add(usuario); await _context.SaveChangesAsync(); @@ -284,6 +290,41 @@ namespace MSAdminUsuarios.Controllers _context.USUARIOSMs.Update(existe); _context.SaveChanges(); + /* + * 1. Perfiles del usuario + * 2. Buscar el perfil de medico + * 3. Si existe la relacion + * 3.1. Se hace la actualizacion de datos + * + */ + + List perfilesUsuario = this._context.PERFILESPORUSUARIOs.Where(pxu => pxu.TX_UUID_USUMS == existe.TX_UUID_USUMS).ToList(); + + if (perfilesUsuario.Count > 0 && perfilesUsuario.Exists(pxu => pxu.NU_FK_PFL == 1)) + { + using (_channel) + { + var medico = new MedicoDto() + { + TX_UUID_MDC = existe.TX_UUID_USUMS, + TX_LUGARESATEN_MDC = existe.TX_SEDES_USUMS + }; + + string jsonMedico = JsonConvert.SerializeObject(medico); + + string exchange = MQExchanges.AgendaMedica; + + // Publish Usuario + RabbitMQMessages.PublishToMessageQueue( + channel: _channel, + exchange: exchange, + routingKey: $"{exchange}.{MQueues.medico}.patch", + message: jsonMedico + ); + } + + } + _errorModel.error = false; _errorModel.cuerpo.Add("Usuario actualizado."); dbContextTransaction.Commit(); diff --git a/Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs b/Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs new file mode 100644 index 0000000..3e83a29 --- /dev/null +++ b/Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs @@ -0,0 +1,31 @@ +namespace MSAdminUsuarios.Dto.Externos.MsAgendaMedica +{ + public class MedicoDto + { + public int? NU_TIPOID_MDC { get; set; } + public string TX_DOCUMENTO_MDC { get; set; } = null!; + public string? TX_REGPROF_MDC { get; set; } + public string? TX_CODIGO_MDC { get; set; } + public int? NU_CARGO_MDC { get; set; } + public int? NU_TIPOPROF_MDC { get; set; } + public string? TX_PRINOMBRE_MDC { get; set; } + public string? TX_SEGNOMBRE_MDC { get; set; } + public string? TX_PRIAPELLIDO_MDC { get; set; } + public string? TX_SEGAPELLIDO_MDC { get; set; } + public string? TX_DIRECCION_MDC { get; set; } + public string? TX_EMAIL_MDC { get; set; } + public string? TX_TELEFONO_MDC { get; set; } + public string? NU_CELULAR_MDC { get; set; } + public int? NU_MODCONTRATACION_MDC { get; set; } + public string? TX_ESPECIALIDAD_MDC { get; set; } + public int? BL_ADSCRITO_MDC { get; set; } + public int? BL_PERCITAWEB_MDC { get; set; } + public int? BL_ESTADO_MDC { get; set; } + public int? NU_MAXCITASEXTRA_MDC { get; set; } + public string? TX_GRUPOSCUPS_MDC { get; set; } + public string? CL_AGENDA_MDC { get; set; } + public string? TX_LUGARESATEN_MDC { get; set; } + public string? TX_UUID_MDC { get; set; } + + } +} diff --git a/Microservicios/MsUsuarios/Utils/GenericTools.cs b/Microservicios/MsUsuarios/Utils/GenericTools.cs new file mode 100644 index 0000000..6a55256 --- /dev/null +++ b/Microservicios/MsUsuarios/Utils/GenericTools.cs @@ -0,0 +1,87 @@ +using System.Linq.Expressions; + +namespace MSAdminUsuarios.Utils +{ + public static class GenericTools + { + /// + /// Permite clonar los valores de un objeto recorriendo cada parámetro + /// (,,). + /// + /// Objeto el cual se va a leer sus propiedades y valores + /// Objeto el cual se va a ESCRIBIR los valores del origen basado en el nombre de la propiedad. + /// Lista con nombres de propiedades a excluir de la copia + public static void CloneObj(T origin, T destiny, params Expression>[] exceptions) where T : class + { + var destinyProps = typeof(T).GetProperties(); + var exceptionProps = new HashSet(); + if (exceptions != null) + { + foreach (var exception in exceptions) + { + if (exception.Body is MemberExpression memberExpression) + { + exceptionProps.Add(memberExpression.Member.Name); + } + } + } + + foreach (var prop in typeof(T).GetProperties()) + { + var originName = prop.Name; + if (exceptionProps.Contains(originName)) + continue; + + for (int i = 0; i < destinyProps.Length; i++) + { + if (destinyProps[i].Name == originName) + { + destinyProps[i].SetValue(destiny, prop.GetValue(origin, null)); + i = destinyProps.Length + 1; + } + } + } + } + + /// + /// Permite tomar parcialmente la información de un obejto Origen, validar si existe en el destino y si es diferente de nulo, para setearle el valor asignado + /// (,,). + /// + /// Objeto el cual se va a leer sus propiedades y valores + /// Objeto el cual se va a ESCRIBIR los valores del origen basado en el nombre de la propiedad. + /// Lista con nombres de propiedades a excluir de la copia + public static void ClonePartialObj(TFrom origin, TTo destiny, params Expression>[] exceptions) where TTo : class + { + var destinyProps = typeof(TTo).GetProperties(); + var exceptionProps = new HashSet(); + if (exceptions != null) + { + foreach (var exception in exceptions) + { + if (exception.Body is MemberExpression memberExpression) + { + exceptionProps.Add(memberExpression.Member.Name); + } + } + } + + foreach (var prop in typeof(TFrom).GetProperties()) + { + var originName = prop.Name; + var originValue = prop.GetValue(origin, null); + if (exceptionProps.Contains(originName)) + continue; + + for (int i = 0; i < destinyProps.Length; i++) + { + if (destinyProps[i].Name == originName && originValue != null) + { + destinyProps[i].SetValue(destiny, originValue); + i = destinyProps.Length + 1; + } + } + } + } + + } +} diff --git a/Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs b/Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs new file mode 100644 index 0000000..0a00645 --- /dev/null +++ b/Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs @@ -0,0 +1,20 @@ +using RabbitMQ.Client; +using System.Text; + +namespace MSAdminUsuarios.Utils +{ + public static class RabbitMQMessages + { + public static void PublishToMessageQueue(IModel channel, string exchange, string routingKey, string message) + { + var body = Encoding.UTF8.GetBytes(message); + + channel.BasicPublish( + exchange: exchange, + routingKey: routingKey, + basicProperties: null, + body: body + ); + } + } +} diff --git a/Microservicios/MsUsuarios/Utils/RabbitMQService.cs b/Microservicios/MsUsuarios/Utils/RabbitMQService.cs index 4ccd70e..947c61e 100644 --- a/Microservicios/MsUsuarios/Utils/RabbitMQService.cs +++ b/Microservicios/MsUsuarios/Utils/RabbitMQService.cs @@ -12,17 +12,53 @@ using System.Text; namespace MSAdminUsuarios.Utils { + public readonly struct MQExchanges + { + public static readonly string AgendaMedica = "MsAgendaMedica"; + public static readonly string Usuarios = "MSAdminUsuarios"; + } + + public readonly struct MQueues + { + public static readonly string medico = "UsuarioMedico"; + public static readonly string PerfilesPorUsuario = "PerfilesPorUsuario"; + public static readonly string Usuarios = "Usuarios"; + public static readonly string FirmaUsuario = $"{Usuarios}.Firma"; + + } + public class MsComunicadoresModel + { + public string exchange { get; set; } = ""; + public List queues { get; set; } = new(); + } public static class RabbitMQService { private static string[] _queues = Array.Empty(); private static string _exchange = "MSAdminUsuarios"; + private static string Exchange + { + get { return _exchange; } + set { _exchange = value; } + } + + private static readonly MsComunicadoresModel ExchangePrincipal = new() + { + exchange = Exchange, + queues = { MQueues.PerfilesPorUsuario, MQueues.Usuarios } + + }; + + private static readonly List ListaExchanges = new() { + ExchangePrincipal, + new() { + exchange = MQExchanges.AgendaMedica, + queues = { MQueues.medico } + } + }; public static IModel GetRabbitMQChannel(IServiceProvider serviceProvider, string projectName) { - //var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog()); - //var logger = loggerFactory.CreateLogger("Rabbit1"); - var connection = serviceProvider.GetService(); if (connection == null) @@ -32,45 +68,35 @@ namespace MSAdminUsuarios.Utils //Declare exchange if it doesnt already exist var exchangeName = projectName; - _exchange = exchangeName; + Exchange = exchangeName; - - channel.ExchangeDeclare( - exchange: exchangeName, - type: ExchangeType.Topic, - durable: true, - autoDelete: false, - arguments: null - ); - - _queues = new string[] - { - $"{exchangeName}.PerfilesPorUsuario", - $"{exchangeName}.Usuarios" - }; - - foreach (var queue in _queues) - { - channel.QueueDeclare( - queue: queue, + ListaExchanges.ForEach(ex => { + channel.ExchangeDeclare( + exchange: ex.exchange, + type: ExchangeType.Topic, durable: true, - exclusive: false, autoDelete: false, arguments: null ); - channel.QueueBind( - queue: queue, - exchange: exchangeName, - routingKey: $"{queue}.*" - ); - } + ex.queues.ForEach(q => { + string queue = $"{ex.exchange}.{q}"; - channel.QueueBind( - queue: $"{exchangeName}.Usuarios", - exchange: exchangeName, - routingKey: $"{exchangeName}.Usuarios.*.*" - ); + channel.QueueDeclare( + queue: queue, + durable: true, + exclusive: false, + autoDelete: false, + arguments: null + ); + + channel.QueueBind( + queue: queue, + exchange: ex.exchange, + routingKey: $"{queue}.*" + ); + }); + }); return channel; } @@ -80,46 +106,32 @@ namespace MSAdminUsuarios.Utils RabbitMQConfig mqConfig = builder.Configuration.GetSection("RabbitMQConfig").Get(); var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog()); - try + //var logger = loggerFactory.CreateLogger("Rabbit2"); + //logger.LogInformation("Inicia Rabbitmq con"); + + ConnectionFactory factory = new() { - //var logger = loggerFactory.CreateLogger("Rabbit2"); - //logger.LogInformation("Inicia Rabbitmq con"); - - ConnectionFactory factory = new() - { - HostName = mqConfig.HostName, - UserName = mqConfig.UserName, - Password = mqConfig.Password, - }; - - IConnection connection = factory.CreateConnection(); - IModel channel = connection.CreateModel(); - - EventingBasicConsumer consumer = new(channel); - - consumer.Received += RabbitMQService.ConsumeRabbitMQEvent; - - List queues = new() - { - $"{projectName}.PerfilesPorUsuario", - $"{projectName}.Usuarios", + HostName = mqConfig.HostName, + UserName = mqConfig.UserName, + Password = mqConfig.Password, }; - foreach (var queue in queues) - { - channel.BasicConsume( - queue: queue, - autoAck: false, - consumer: consumer - ); - } - } - catch (Exception ex) - { + IConnection connection = factory.CreateConnection(); + IModel channelReceptor = connection.CreateModel(); - Console.WriteLine(ex.Message); + EventingBasicConsumer consumer = new(channelReceptor); + + consumer.Received += RabbitMQService.ConsumeRabbitMQEvent; + + + foreach (var queue in ExchangePrincipal.queues) + { + channelReceptor.BasicConsume( + queue: $"{ExchangePrincipal.exchange}.{queue}", + autoAck: false, + consumer: consumer + ); } - } @@ -191,7 +203,7 @@ namespace MSAdminUsuarios.Utils try { - var UsuariosCtrl = new UsuariosController(context); + var UsuariosCtrl = new UsuariosController(context, model); if (controller[2] == "post") { var data = JsonConvert.DeserializeObject(message); From 363717156e20250b328e3a8f5109e118cc5e0c97 Mon Sep 17 00:00:00 2001 From: "Dario F. Gomez Z" Date: Fri, 22 Dec 2023 15:55:01 -0500 Subject: [PATCH 5/5] Ajustes de usuarios --- Microservicios/MsUsuarios/Context/ModelContext.cs | 1 + Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs | 3 ++- Microservicios/MsUsuarios/Controllers/PerfilesController.cs | 6 ++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Microservicios/MsUsuarios/Context/ModelContext.cs b/Microservicios/MsUsuarios/Context/ModelContext.cs index 8e5decb..7d98a6a 100644 --- a/Microservicios/MsUsuarios/Context/ModelContext.cs +++ b/Microservicios/MsUsuarios/Context/ModelContext.cs @@ -89,6 +89,7 @@ namespace MSAdminUsuarios.Context entity.ToTable("PERFILESPORUSUARIO"); entity.Property(e => e.TX_UUID_USUMS).HasMaxLength(40); + entity.Property(e => e.TX_UUID_PFL).HasMaxLength(40); }); diff --git a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs index f4cf927..4a9e6cd 100644 --- a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs +++ b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs @@ -6,10 +6,11 @@ namespace MSAdminUsuarios.Context public partial class PERFILPORUSUARIO { public int NU_PK_PFLXUSU { get; set; } - public string? TX_FKDOC_USUMS { get; set; } + //public string? TX_FKDOC_USUMS { get; set; } public int? NU_FK_PFL { get; set; } public int? BL_ESTADO_PFLXUSU { get; set; } = 1; public string? TX_UUID_USUMS { get; set; } + public string? TX_UUID_PFL { get; set; } } } diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs index b86f9b0..818856a 100644 --- a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs +++ b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs @@ -21,6 +21,7 @@ namespace MSAdminUsuarios.Controllers { var consulta = from dm in _context.PERFILESMs where dm.BL_ESTADO_PFL>=0 + orderby dm.NU_PK_PFL ascending select dm; return Ok(consulta); @@ -66,6 +67,11 @@ namespace MSAdminUsuarios.Controllers var existe = _context.PERFILESMs.Find(editado.NU_PK_PFL); + if (existe == null) + { + return BadRequest("Perfil no encontrado"); + } + existe.TX_PERFIL_PFL = editado.TX_PERFIL_PFL; existe.NU_ROL_PFL = editado.NU_ROL_PFL; existe.BL_ESTADO_PFL = editado.BL_ESTADO_PFL;