Example #1
0
        public async Task <ActionResult> RecuperarContrasena(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            var usuario = await UserManager.FindByEmailAsync(recuperarContrasenaRequest.Email);

            if (usuario != null)
            {
                //var contrasenaTmp = GenerarCodigo.Generar(CuotasCodigos.CuotaInferiorCodigo, CuotasCodigos.CuotaSuperiorCodigo);
                await UserManager.RemovePasswordAsync(usuario.Id);

                await UserManager.AddPasswordAsync(usuario.Id, usuario.Identificacion);

                usuario.EmailConfirmed = false;
                await UserManager.UpdateAsync(usuario);

                string htmlData = InfoMail.RecuperarContrasena();
                htmlData = htmlData.Replace("@NombreUsuario", usuario.UserName);
                htmlData = htmlData.Replace("@Contrasena", usuario.Identificacion);
                //Send email
                EnviarCorreo.Enviar(usuario.Email, Mensaje.RecuperarContrasena, htmlData);

                return(View("RecuperarContrasenaInformacion"));
            }
            ModelState.AddModelError("Email", "El correo electrónico no está registrado");
            return(View());
        }
Example #2
0
        public async Task <Response> EnviarContrasena(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            try
            {
                //Configuring webMail class to send emails
                //gmail smtp server
                WebMail.SmtpServer = CorreoUtil.SmtpServer;
                //gmail port to send emails
                WebMail.SmtpPort = Convert.ToInt32(CorreoUtil.Port);
                WebMail.SmtpUseDefaultCredentials = true;
                //sending emails with secure protocol
                WebMail.EnableSsl = true;
                //EmailId used to send emails from application
                WebMail.UserName = CorreoUtil.UserName;
                WebMail.Password = CorreoUtil.Password;

                //Sender email address.
                WebMail.From = CorreoUtil.UserName;

                //Send email
                WebMail.Send(to: recuperarContrasenaRequest.Email, subject: "Contraseña: " + recuperarContrasenaRequest.Codigo, body: "Contraseña: " + recuperarContrasenaRequest.Codigo, isBodyHtml: true);
                return(new Response {
                    IsSuccess = true
                });
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #3
0
        public async Task <Response> PasswordChange(RecuperarContrasenaRequest data)
        {
            try
            {
                var request = JsonConvert.SerializeObject(data);
                var body    = new StringContent(request, Encoding.UTF8, "application/json");
                var client  = new HttpClient();
                client.BaseAddress = new Uri(Constants.Constants.VentasWEB);
                var url      = "/api/webapi/CambiarContraseña";
                var response = await client.PostAsync(url, body);

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = response.StatusCode.ToString(),
                    });
                }

                var result = await response.Content.ReadAsStringAsync();

                var PasswordData = JsonConvert.DeserializeObject <Response>(result);
                return(PasswordData);
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                });
            }
        }
Example #4
0
        public async Task <Response> IngresarContrasena(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            if (recuperarContrasenaRequest.Contrasena != recuperarContrasenaRequest.ConfirmarContrasena)
            {
                ModelState.AddModelError("", "La contraseña y la confirmación no coinciden...");
            }
            var user = await UserManager.FindByEmailAsync(recuperarContrasenaRequest.Email);

            await UserManager.RemovePasswordAsync(user.Id);

            var pass = await UserManager.AddPasswordAsync(user.Id, recuperarContrasenaRequest.ConfirmarContrasena);

            if (!pass.Succeeded)
            {
                ModelState.AddModelError("", "La contraseña no cumple con el formato establecido ...");
                return(new Response
                {
                    IsSuccess = true,
                    Message = "La contraseña no cumple con el formato establecido ..."
                });
            }

            return(new Response
            {
                IsSuccess = true,
                Message = "Contraseña cambiada satisfactoriamente"
            });
        }
Example #5
0
 public PasswordViewModel()
 {
     datos             = new RecuperarContrasenaRequest();
     navigationService = new NavigationService();
     dialogService     = new DialogService();
     apiService        = new ApiService();
 }
Example #6
0
        public ActionResult IngresarContrasena(string Email)
        {
            var vista = new RecuperarContrasenaRequest {
                Email = Email
            };

            return(View(vista));
        }
Example #7
0
        public async Task <ActionResult> IntroducirCodigo(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            var response = await ApiServicio.ObtenerElementoAsync1 <Response>(recuperarContrasenaRequest, new Uri(WebApp.BaseAddress)
                                                                              , "api/Usuarios/VerificarCodigo");

            if (response.IsSuccess)
            {
                return(RedirectToAction("IngresarContrasena", new { recuperarContrasenaRequest.Email }));
            }
            ModelState.AddModelError("", "El código no es correcto");
            return(View(recuperarContrasenaRequest));
        }
Example #8
0
        public async Task <ActionResult> RecuperarContrasena(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            if (string.IsNullOrEmpty(recuperarContrasenaRequest.Email))
            {
                ModelState.AddModelError("", "Debe introducir el correo electrónico");
            }

            var response = await ApiServicio.ObtenerElementoAsync1 <Response>(recuperarContrasenaRequest, new Uri(WebApp.BaseAddress)
                                                                              , "api/Usuarios/GenerarCodigo");

            if (response.IsSuccess)
            {
                return(RedirectToAction("IntroducirCodigo", new { recuperarContrasenaRequest.Email }));
            }
            ModelState.AddModelError("Email", "El correo electrónico no está registrado");
            return(View());
        }
Example #9
0
        public async Task <Response> GenerarCodigo(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            try
            {
                var aspNetUsers = await db.AspNetUsers.Where(x => x.Email == recuperarContrasenaRequest.Email).FirstOrDefaultAsync();

                if (aspNetUsers == null)
                {
                    return(new Response {
                        IsSuccess = false
                    });
                }

                aspNetUsers.TokenContrasena = Convert.ToString(GenerarCodigo(Constantes.CuotaInferiorCodigo, Constantes.CuotaSuperiorCodigo));
                db.Entry(aspNetUsers).State = EntityState.Modified;
                await db.SaveChangesAsync();

                //Configuring webMail class to send emails
                //gmail smtp server
                WebMail.SmtpServer = CorreoUtil.SmtpServer;
                //gmail port to send emails
                WebMail.SmtpPort = Convert.ToInt32(CorreoUtil.Port);
                WebMail.SmtpUseDefaultCredentials = true;
                //sending emails with secure protocol
                WebMail.EnableSsl = true;
                //EmailId used to send emails from application
                WebMail.UserName = CorreoUtil.UserName;
                WebMail.Password = CorreoUtil.Password;

                //Sender email address.
                WebMail.From = CorreoUtil.UserName;

                //Send email
                WebMail.Send(to: aspNetUsers.Email, subject: "Código: " + aspNetUsers.TokenContrasena, body: "Código: " + aspNetUsers.TokenContrasena, isBodyHtml: true);
                return(new Response {
                    IsSuccess = true
                });
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #10
0
        public async Task <Response> VerificarCodigo(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            var aspNetUsers = await db.AspNetUsers.Where(x => x.Email == recuperarContrasenaRequest.Email && x.TokenContrasena == recuperarContrasenaRequest.Codigo).FirstOrDefaultAsync();

            if (aspNetUsers == null)
            {
                return(new Response {
                    IsSuccess = false
                });
            }

            aspNetUsers.TokenContrasena = null;
            db.Entry(aspNetUsers).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return(new Response {
                IsSuccess = true
            });
        }
Example #11
0
        public async Task <ActionResult> IngresarContrasena(RecuperarContrasenaRequest recuperarContrasenaRequest)
        {
            if (recuperarContrasenaRequest.Contrasena != recuperarContrasenaRequest.ConfirmarContrasena)
            {
                ModelState.AddModelError("", "La contraseña y la confirmación no coinciden...");
            }
            var user = await UserManager.FindByEmailAsync(recuperarContrasenaRequest.Email);

            await UserManager.RemovePasswordAsync(user.Id);

            var pass = await UserManager.AddPasswordAsync(user.Id, recuperarContrasenaRequest.ConfirmarContrasena);

            if (!pass.Succeeded)
            {
                ModelState.AddModelError("", "La contraseña no cumple con el formato establecido ...");
                return(View(recuperarContrasenaRequest));
            }

            return(RedirectToAction("Login"));
        }
Example #12
0
        public IHttpActionResult Authenticate(RecuperarContrasenaRequest recuperarContrasena)
        {
            if (recuperarContrasena.Email.Contains("@") && recuperarContrasena.Email.Contains(".com") || recuperarContrasena.Email.Contains("@") && recuperarContrasena.Email.Contains(".co"))
            {
                ResponseContrasena responseContrasena = new ResponseContrasena
                {
                    Ok = 1
                };

                return(Ok(responseContrasena));
            }
            else
            {
                ResponseContrasena responseContrasena = new ResponseContrasena
                {
                    Ok = 0
                };

                return(Ok(responseContrasena));
            }

            //if (recuperarContrasena.Email == "*****@*****.**")
            //{
            //    ResponseDTO responseDTO = new ResponseDTO
            //    {
            //        Exitoso = 1
            //    };

            //    return Ok(responseDTO);
            //}
            //else
            //{
            //    ResponseDTO responseDTO = new ResponseDTO
            //    {
            //        Exitoso = 0
            //    };

            //    return Ok(responseDTO);
            //}
        }
Example #13
0
        public async Task <Response> VerificarCodigo(RecuperarContrasenaRequest Codigo)
        {
            try
            {
                var request = JsonConvert.SerializeObject(Codigo);
                var content = new StringContent(request, Encoding.UTF8, "application/json");
                var client  = new HttpClient();
                client.BaseAddress = new Uri(Constants.Constants.VentasWS);
                var url      = "api/Usuarios/VerificarCodigo";
                var response = await client.PostAsync(url, content);

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = "error",
                    });;
                }

                var result = await response.Content.ReadAsStringAsync();

                var codedata = JsonConvert.DeserializeObject <Response>(result);


                return(codedata);
                //  var log = JsonConvert.DeserializeObject<LogPosition>(result);
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = "",
                });
            }
        }
        public async Task <ActionResult> CrearVendedor(HttpPostedFileBase fileUpload, VendedorRequest vendedorRequest)
        {
            InicializarMensaje("");

            int idEmpresaInt = 0;

            SupervisorRequest supervisorRequest = new SupervisorRequest();

            var guardar = false;



            try
            {
                var userWithClaims = (ClaimsPrincipal)User;
                var idEmpresa      = userWithClaims.Claims.First(c => c.Type == Constantes.Empresa).Value;


                idEmpresaInt = Convert.ToInt32(idEmpresa);
                vendedorRequest.idEmpresa         = idEmpresaInt;
                vendedorRequest.TiempoSeguimiento = 5;
            }
            catch (Exception ex)
            {
                InicializarMensaje(Mensaje.ErrorIdEmpresa);
                return(View(vendedorRequest));
            }


            if (!ModelState.IsValid)
            {
                InicializarMensaje(Mensaje.ModeloInvalido);
                return(View(vendedorRequest));
            }


            ApplicationDbContext db       = new ApplicationDbContext();
            Response             response = new Response();


            try
            {
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));


                var idUsuarioActual = User.Identity.GetUserId();

                supervisorRequest.IdUsuario = idUsuarioActual;
                supervisorRequest.IdEmpresa = idEmpresaInt;

                if (userManager.IsInRole(idUsuarioActual, "Supervisor"))
                {
                    response = await ApiServicio.InsertarAsync(supervisorRequest,
                                                               new Uri(WebApp.BaseAddress),
                                                               "api/Vendedores/obtenerSupervisorPorIdUsuario");

                    supervisorRequest            = JsonConvert.DeserializeObject <SupervisorRequest>(response.Resultado.ToString());
                    vendedorRequest.IdSupervisor = supervisorRequest.IdSupervisor;

                    guardar = true;
                }

                else if (userManager.IsInRole(idUsuarioActual, "GerenteGeneral"))
                {
                    guardar = true;
                }


                if (guardar == false)
                {
                    InicializarMensaje("No tiene permisos para agregar un nuevo vendedor");
                    return(View(vendedorRequest));
                }

                var userManager2     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
                var InstanciaUsuario = await userManager2.FindByEmailAsync(vendedorRequest.Correo);

                if (InstanciaUsuario != null)
                {
                    InicializarMensaje(Mensaje.ExisteCorreo);
                    return(View(vendedorRequest));
                }

                var ExisteUsuario = await ApiServicio.ObtenerElementoAsync1 <List <VendedorRequest> >(vendedorRequest,
                                                                                                      new Uri(WebApp.BaseAddress),
                                                                                                      "api/Vendedores/BuscarUsuariosVendedoresPorEmpresaEIdentificacion");

                if (ExisteUsuario.Count > 0)
                {
                    InicializarMensaje(Mensaje.ExisteIdentificacionUsuario);
                    return(View(vendedorRequest));
                }

                var user = new ApplicationUser
                {
                    UserName       = vendedorRequest.Correo,
                    Email          = vendedorRequest.Correo,
                    Identificacion = vendedorRequest.Identificacion,

                    Nombres   = vendedorRequest.Nombres,
                    Apellidos = vendedorRequest.Apellidos,
                    Direccion = vendedorRequest.Direccion,
                    Telefono  = vendedorRequest.Telefono,

                    Estado = 1,

                    IdEmpresa = idEmpresaInt
                };



                var result = await userManager.CreateAsync(user, "A123345.1a");

                db.SaveChanges();

                if (result != null)
                {
                    InstanciaUsuario = await userManager2.FindByEmailAsync(vendedorRequest.Correo);

                    vendedorRequest.IdUsuario = InstanciaUsuario.Id;


                    userManager.AddToRole(InstanciaUsuario.Id, "Vendedor");



                    response = await ApiServicio.InsertarAsync(vendedorRequest,
                                                               new Uri(WebApp.BaseAddress),
                                                               "api/Vendedores/InsertarVendedor");



                    if (response.IsSuccess)
                    {
                        if (fileUpload != null)
                        {
                            var idVendedor = response.Resultado;


                            var fichero = readFileContents(fileUpload);
                            var foto    = new ArchivoRequest {
                                Id = Convert.ToString(idVendedor), Array = fichero, Tipo = 3
                            };


                            var fotoRequest = await ApiServicio.InsertarAsync <Response>(foto, new Uri(WebApp.BaseAddress)
                                                                                         , "Api/Archivos/Insertar");

                            if (fotoRequest.IsSuccess)
                            {
                                user.Foto = fotoRequest.Resultado.ToString();

                                db.Entry(user).State = EntityState.Modified;
                                await db.SaveChangesAsync();


                                var recuperarContrasenaRequest0 = new RecuperarContrasenaRequest();
                                recuperarContrasenaRequest0.Email = user.Email;

                                var response0 = await ApiServicio.ObtenerElementoAsync1 <Response>(recuperarContrasenaRequest0, new Uri(WebApp.BaseAddress)
                                                                                                   , "api/Usuarios/GenerarCodigo");

                                return(RedirectToAction("VendedorIndex", new { mensaje = response.Message }));
                            }
                            else
                            {
                                InicializarMensaje(Mensaje.Error);
                                return(View(vendedorRequest));
                            }
                        }

                        var recuperarContrasenaRequest = new RecuperarContrasenaRequest();
                        recuperarContrasenaRequest.Email = user.Email;

                        var response2 = await ApiServicio.ObtenerElementoAsync1 <Response>(recuperarContrasenaRequest, new Uri(WebApp.BaseAddress)
                                                                                           , "api/Usuarios/GenerarCodigo");

                        return(RedirectToAction("VendedorIndex", new { mensaje = response.Message }));
                    }
                }

                InicializarMensaje("No se ha podido crear un usuario");
                return(View(vendedorRequest));
            }
            catch (Exception ex)
            {
                ViewData["Error"] = Mensaje.Error;
                return(View(vendedorRequest));
            }
        }
Example #15
0
        public async Task <ActionResult> Create(SupervisorRequest supervisorRequest)
        {
            //Seteando el id de la empresa
            var userWithClaims = (ClaimsPrincipal)User;
            var idEmpresa      = userWithClaims.Claims.First(c => c.Type == Constantes.Empresa).Value;

            InicializarMensaje(null);
            if (!ModelState.IsValid)
            {
                InicializarMensaje(null);
                return(View(supervisorRequest));
            }
            Response response = new Response();

            try
            {
                ApplicationDbContext db = new ApplicationDbContext();
                supervisorRequest.IdEmpresa = int.Parse(idEmpresa);

                //VALIDA SI EXITE EL CORREO AL CREAR
                var userManager2     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
                var InstanciaUsuario = await userManager2.FindByEmailAsync(supervisorRequest.Correo);

                if (InstanciaUsuario != null)
                {
                    InicializarMensaje(Mensaje.ExisteCorreo);
                    return(View(supervisorRequest));
                }


                //VALIDA SI EXITE LA IDENTIFICACION AL CREAR

                var ExisteUsuario = await ApiServicio.ObtenerElementoAsync1 <SupervisorRequest>(supervisorRequest,
                                                                                                new Uri(WebApp.BaseAddress),
                                                                                                "api/Supervisor/BuscarSupervisorPorEmpresaEIdentificacion");

                if (ExisteUsuario != null)
                {
                    InicializarMensaje(Mensaje.ExisteIdentificacionUsuario);
                    return(View(supervisorRequest));
                }

                //Inserta el supervisor
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));


                var empresaActual = new EmpresaActual {
                    IdEmpresa = Convert.ToInt32(idEmpresa)
                };
                var user = new ApplicationUser
                {
                    UserName       = supervisorRequest.Correo,
                    Email          = supervisorRequest.Correo,
                    Identificacion = supervisorRequest.Identificacion,
                    Apellidos      = supervisorRequest.Apellidos,
                    Nombres        = supervisorRequest.Nombres,
                    Estado         = 1,
                    Direccion      = supervisorRequest.Direccion,
                    Telefono       = supervisorRequest.Telefono,
                    IdEmpresa      = empresaActual.IdEmpresa
                };
                var result = await userManager.CreateAsync(user, "A12345.1a");

                db.SaveChanges();
                var enviarContrasenaRequest = new RecuperarContrasenaRequest();
                enviarContrasenaRequest.Email  = user.Email;
                enviarContrasenaRequest.Codigo = "A12345.1a";
                var response2 = await ApiServicio.ObtenerElementoAsync1 <Response>(enviarContrasenaRequest, new Uri(WebApp.BaseAddress)
                                                                                   , "api/Usuarios/EnviarContrasena");

                //varifica el rol
                userManager.AddToRoles(user.Id, "Supervisor");
                if (result != null)
                {
                    supervisorRequest.IdEmpresa = Convert.ToInt32(idEmpresa);
                    supervisorRequest.IdUsuario = user.Id;
                    response = await ApiServicio.InsertarAsync(supervisorRequest,
                                                               new Uri(WebApp.BaseAddress),
                                                               "api/Supervisor/InsertarSupervisor");

                    if (response.IsSuccess)
                    {
                        var idsuper = JsonConvert.DeserializeObject <SupervisorRequest>(response.Resultado.ToString());

                        return(RedirectToAction("Edit", new { id = idsuper.IdSupervisor }));
                    }
                }
            }

            catch (Exception ex)
            {
                ex.ToString();
            }
            ViewData["Error"] = response.Message;

            return(View(supervisorRequest));
        }