Ejemplo n.º 1
0
        public async Task <bool> Handle(EliminarUsuarioCommand request, CancellationToken cancellationToken)
        {
            string usuario = _identityService.Usuario;

            try
            {
                using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var user = await _userManager.FindByIdAsync(request.UsuarioId);

                        if (user == null)
                        {
                            throw new KeyNotFoundException(nameof(user));
                        }

                        var roles = await _userManager.GetRolesAsync(user);

                        var result = await _userManager.RemoveFromRolesAsync(user, roles);

                        if (!result.Succeeded)
                        {
                            throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                        }

                        result = await _userManager.DeleteAsync(user);

                        if (!result.Succeeded)
                        {
                            throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                        }

                        cancellationToken.ThrowIfCancellationRequested();
                        transaction.Complete();
                    }
                    catch (Exception)
                    {
                        transaction.Dispose();
                        throw;
                    }
                }
                //Integración de eventos
                var evento = new UsuarioEliminadoIntegrationEvent(request.UsuarioId);

                await _integrationEventService.SaveEventAsync(evento);

                await _integrationEventService.PublishThroughEventBusAsync(evento);

                //
                return(true);
            }
            catch (AuthDomainException)
            {
                throw;
            }
            catch (KeyNotFoundException)
            {
                throw;
            }
            catch (Exception ex)
            {
                var result = await _logger.ErrorAsync(ex.Message, ex.Source, ex.StackTrace, usuario);

                throw new AuthDomainException(Constants.MsgDeleteError, result.EventLogId);
            }
        }
Ejemplo n.º 2
0
        public async Task <string> Handle(ActualizarPerfilCommand request, CancellationToken cancellationToken)
        {
            string usuario   = _identityService.Usuario;
            string usuarioId = _identityService.UsuarioId;

            try
            {
                if (usuarioId != request.UsuarioId)
                {
                    throw new AuthDomainException("No es posible actualizar el perfil de otro usuario.");
                }

                bool cambia  = false;
                var  current = await _userManager.FindByIdAsync(request.UsuarioId);

                if (current == null)
                {
                    throw new KeyNotFoundException(nameof(request));
                }

                if (current.Nombre != request.Nombre || current.Email != request.Correo)
                {
                    cambia = true;
                }

                current.Nombre      = request.Nombre;
                current.Email       = request.Correo.ToLowerInvariant();
                current.PhoneNumber = request.Telefono;

                if (request.QuitarImagen)
                {
                    current.Imagen = null;
                }
                else
                {
                    if (request.Imagen != null)
                    {
                        current.Imagen = request.Imagen;
                    }
                }

                var result = await _userManager.UpdateAsync(current);

                if (!result.Succeeded)
                {
                    throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                }

                //Integración de eventos
                if (cambia)
                {
                    var evento = new UsuarioModificadoIntegrationEvent(current.Id, current.Nombre, current.Email, current.Activo);

                    await _integrationEventService.SaveEventAsync(evento);

                    await _integrationEventService.PublishThroughEventBusAsync(evento);
                }
                //
                return(current.Id);
            }
            catch (AuthDomainException)
            {
                throw;
            }
            catch (KeyNotFoundException)
            {
                throw;
            }
            catch (Exception ex)
            {
                var result = await _logger.ErrorAsync(ex.Message, ex.Source, ex.StackTrace, usuario);

                throw new AuthDomainException(Constants.MsgPutError, result.EventLogId);
            }
        }
Ejemplo n.º 3
0
        public async Task<string> Handle(CrearUsuarioCommand request, CancellationToken cancellationToken)
        {
            int empresaId = _identityService.EmpresaId;
            string usuario = _identityService.Usuario;
            string token = _identityService.Token;

            try
            {
                if(request == null)
                {
                    throw new ArgumentNullException(nameof(request));
                }

                if(request.Empresas is null  || request.Empresas.Count() == 0)
                {
                    throw new AuthDomainException("No ha seleccionado empresas para el usuario.");
                }

                if(request.Empresas.Count(e => e.Principal) == 0)
                {
                    throw new AuthDomainException("No ha seleccionado empresa principal.");
                }

                //Agregar persona por Grpc
                var headers = new Metadata();
                headers.Add("Authorization", token);
                var httpClientHandler = new HttpClientHandler();
                httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                var httpClient = new HttpClient(httpClientHandler);
                var channel = GrpcChannel.ForAddress(_settings.Value.Services.AdminUrl, new GrpcChannelOptions { HttpClient = httpClient });
                var client = new Expertec.Sigeco.AuthServer.API.Grpc.Persona.PersonaClient(channel);

                var personaReply = await client.CrearSiNoExisteAsync(new PersonaRequest { 
                    TipoPersona = "N", 
                    PrimerNombre = request.PrimerNombre, 
                    SegundoNombre = request.SegundoNombre ?? string.Empty,
                    ApellidoPaterno = request.ApellidoPaterno,
                    ApellidoMaterno = request.ApellidoMaterno ?? string.Empty,
                    Dni = request.NroDocumento
                }, headers);

                var persona = await _personaRepository.ObtenerAsync(personaReply.PersonaId);
                
                if(persona == null)
                {
                    await _personaRepository.AgregarAsync(new Models.Persona {
                        ApellidoMaterno = personaReply.ApellidoMaterno,
                        ApellidoPaterno = personaReply.ApellidoPaterno,
                        NroDocumento = personaReply.NroDocumento,
                        PersonaId = personaReply.PersonaId,
                        PrimerNombre = personaReply.PrimerNombre,
                        SegundoNombre = personaReply.SegundoNombre
                    });
                }
                else
                {
                    persona.ApellidoMaterno = personaReply.ApellidoMaterno;
                    persona.ApellidoPaterno = personaReply.ApellidoPaterno;
                    persona.PrimerNombre = personaReply.PrimerNombre;
                    persona.SegundoNombre = personaReply.SegundoNombre;

                    await _personaRepository.ModificarAsync(persona);
                }

                //
                var newItem = new Usuario {
                    Activo = true,
                    Email = request.Correo.ToLowerInvariant(),
                    ExpiraClave = request.ExpiraClaveHabilitado ? DateTime.UtcNow.AddDays(30) : new DateTime?(),
                    ExpiraClaveHabilitado = request.ExpiraClaveHabilitado,
                    Nombre = request.Nombre,
                    PhoneNumber = request.Telefono,
                    RequiereCambioClave = true,
                    UserName = request.NombreUsuario
                };
                newItem.PersonaId = personaReply.PersonaId;

                using(var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var empresa = await _empresaRepository.ObtenerAsync(empresaId);

                        newItem.EspacioTrabajoId = empresa.EspacioTrabajoId;

                        foreach(var item in request.Empresas)
                        {
                            newItem.AgregarEmpresa(item.EmpresaId, item.Principal);
                        }

                        var result = await _userManager.CreateAsync(newItem, request.Clave);

                        if(!result.Succeeded)
                        {
                            throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                        }

                        result = await _userManager.SetLockoutEnabledAsync(newItem, request.BloqueoHabilitado);

                        if(!result.Succeeded)
                        {
                            throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                        }

                        result = await _userManager.AddToRoleAsync(newItem, "usuario");

                        if(!result.Succeeded)
                        {
                            throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                        }

                        cancellationToken.ThrowIfCancellationRequested();
                        transaction.Complete();
                    }
                    catch (Exception)
                    {
                        transaction.Dispose();
                        throw;
                    }    
                }
                //Integración de eventos
                var evento = new UsuarioCreadoIntegrationEvent(newItem.Id, newItem.UserName, newItem.Nombre, newItem.Email, newItem.Activo);
                    
                await _integrationEventService.SaveEventAsync(evento);
                await _integrationEventService.PublishThroughEventBusAsync(evento);
                //
                return newItem.Id;   
            }
            catch(AuthDomainException)
            {
                throw;
            }
            catch (DbUpdateException ex)
            {
                var result = await _logger.ErrorAsync(ex.InnerException.Message, ex.Source, ex.StackTrace, usuario);

                throw new AuthDomainException(Constants.MsgPutError, result.EventLogId);
            }
            catch (Exception ex)
            {
                var result = await _logger.ErrorAsync(ex.Message, ex.Source, ex.StackTrace, usuario);

                throw new AuthDomainException(Constants.MsgPostError, result.EventLogId);
            }
        }
Ejemplo n.º 4
0
        public async Task <string> Handle(ActualizarUsuarioCommand request, CancellationToken cancellationToken)
        {
            string usuario = _identityService.Usuario;
            string token   = _identityService.Token;

            try
            {
                if (request == null)
                {
                    throw new ArgumentNullException(nameof(request));
                }
                if (request.Empresas is null || request.Empresas.Count() == 0)
                {
                    throw new AuthDomainException("No ha seleccionado empresas para el usuario.");
                }

                if (request.Empresas.Count(e => e.Principal) == 0)
                {
                    throw new AuthDomainException("No ha seleccionado empresa principal.");
                }

                //Agregar persona por Grpc
                var headers = new Metadata();
                headers.Add("Authorization", token);
                var httpClientHandler = new HttpClientHandler();
                httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                var httpClient = new HttpClient(httpClientHandler);
                var channel    = GrpcChannel.ForAddress(_settings.Value.Services.AdminUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                var client = new Expertec.Sigeco.AuthServer.API.Grpc.Persona.PersonaClient(channel);

                var personaReply = await client.CrearSiNoExisteAsync(new PersonaRequest {
                    TipoPersona     = "N",
                    PrimerNombre    = request.PrimerNombre,
                    SegundoNombre   = request.SegundoNombre ?? string.Empty,
                    ApellidoPaterno = request.ApellidoPaterno,
                    ApellidoMaterno = request.ApellidoMaterno ?? string.Empty,
                    Dni             = request.NroDocumento
                }, headers);

                var persona = await _personaRepository.ObtenerAsync(personaReply.PersonaId);

                if (persona == null)
                {
                    await _personaRepository.AgregarAsync(new Models.Persona {
                        ApellidoMaterno = personaReply.ApellidoMaterno,
                        ApellidoPaterno = personaReply.ApellidoPaterno,
                        NroDocumento    = personaReply.NroDocumento,
                        PersonaId       = personaReply.PersonaId,
                        PrimerNombre    = personaReply.PrimerNombre,
                        SegundoNombre   = personaReply.SegundoNombre
                    });
                }
                else
                {
                    persona.ApellidoMaterno = personaReply.ApellidoMaterno;
                    persona.ApellidoPaterno = personaReply.ApellidoPaterno;
                    persona.PrimerNombre    = personaReply.PrimerNombre;
                    persona.SegundoNombre   = personaReply.SegundoNombre;

                    await _personaRepository.ModificarAsync(persona);
                }

                //

                Usuario current = null;
                bool    cambia  = false;

                using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        current = await _userManager.FindByIdAsync(request.UsuarioId);

                        if (current == null)
                        {
                            throw new KeyNotFoundException(nameof(request));
                        }

                        if (current.Nombre != request.Nombre || current.Email != request.Correo || current.Activo != request.Activo)
                        {
                            cambia = true;
                        }

                        current.Nombre                = request.Nombre;
                        current.Email                 = request.Correo.ToLowerInvariant();
                        current.PhoneNumber           = request.Telefono;
                        current.ExpiraClaveHabilitado = request.ExpiraClaveHabilitado;
                        current.LockoutEnabled        = request.BloqueoHabilitado;
                        current.RequiereCambioClave   = request.ReiniciarClave ? true : current.RequiereCambioClave;
                        current.Activo                = request.Activo;
                        current.PersonaId             = personaReply.PersonaId;

                        var empresas = new List <UsuarioEmpresa>();

                        foreach (var item in request.Empresas)
                        {
                            empresas.Add(new UsuarioEmpresa {
                                EmpresaId = item.EmpresaId, UsuarioId = request.UsuarioId, Principal = item.Principal
                            });
                        }

                        await _empresaRepository.AsignarEmpresasAsync(request.UsuarioId, empresas);

                        if (current.ExpiraClaveHabilitado != request.ExpiraClaveHabilitado)
                        {
                            current.ExpiraClave = request.ExpiraClaveHabilitado ? DateTime.UtcNow.AddDays(30) : new DateTime?();
                        }

                        var result = await _userManager.UpdateAsync(current);

                        if (!result.Succeeded)
                        {
                            throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                        }

                        if (request.ReiniciarClave)
                        {
                            var pToken = await _userManager.GeneratePasswordResetTokenAsync(current);

                            result = await _userManager.ResetPasswordAsync(current, pToken, request.Clave);

                            if (!result.Succeeded)
                            {
                                throw new AuthDomainException(result.Errors.FirstOrDefault().Description);
                            }
                        }
                        cancellationToken.ThrowIfCancellationRequested();
                        transaction.Complete();
                    }
                    catch (Exception)
                    {
                        transaction.Dispose();
                        throw;
                    }
                }
                //Integración de eventos
                if (cambia)
                {
                    var evento = new UsuarioModificadoIntegrationEvent(current.Id, current.Nombre, current.Email, current.Activo);

                    await _integrationEventService.SaveEventAsync(evento);

                    await _integrationEventService.PublishThroughEventBusAsync(evento);
                }
                //
                return(current.Id);
            }
            catch (AuthDomainException)
            {
                throw;
            }
            catch (KeyNotFoundException)
            {
                throw;
            }
            catch (DbUpdateException ex)
            {
                var result = await _logger.ErrorAsync(ex.InnerException.Message, ex.Source, ex.StackTrace, usuario);

                throw new AuthDomainException(Constants.MsgPutError, result.EventLogId);
            }
            catch (Exception ex)
            {
                var result = await _logger.ErrorAsync(ex.Message, ex.Source, ex.StackTrace, usuario);

                throw new AuthDomainException(Constants.MsgPutError, result.EventLogId);
            }
        }