public async Task <ActionResult <ViewModelResponse> > DeleteUser(string id)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id);

                if (user != null)
                {
                    var ldapDelete = await ServiceLDAP.DeleteAsync(user.UserName);

                    if (ldapDelete)
                    {
                        await _userManager.DeleteAsync(user);

                        _dbContext.SaveChanges();
                        return(Json(new ViewModelResponse()
                        {
                            Error = false, Response = "Cuenta Eliminada Satisfactoriamente."
                        }));
                    }
                    else
                    {
                        return(Json(new ViewModelResponse()
                        {
                            Error = true, Response = "Usuario no encontrado."
                        }));
                    }
                }
                return(Json(new ViewModelResponse()
                {
                    Error = true, Response = "Usuario no encontrado."
                }));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new ViewModelResponse()
                {
                    Error = true, Response = String.Format("Ocurrio un error al eliminar el usuario, intenta nueva mente. {0}", e.Message)
                }));
            }
        }
        public async Task <ActionResult <ViewModelResponse> > Login([FromBody] ViewModelLogin model)
        {
            try
            {
                var ldap = await ServiceLDAP.LoginAsync(model.UserName, model.Password);

                if (ldap)
                {
                    var us = await _userManager.FindByNameAsync(model.UserName);

                    if (us != null)
                    {
                        if (us.Verified)
                        {
                            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

                            if (result.Succeeded)
                            {
                                var appUser = _userManager.Users.SingleOrDefault(u => u.UserName == model.UserName);
                                var token   = GenerateJwtToken(model.UserName, appUser);

                                var    httpClient = new WebClient();
                                byte[] bytes;
                                try
                                {
                                    bytes = await httpClient.DownloadDataTaskAsync(appUser.Picture);
                                }
                                catch (TaskCanceledException)
                                {
                                    System.Console.WriteLine("Task Canceled!");
                                    bytes = null;
                                }
                                catch (Exception e)
                                {
                                    bytes = null;
                                }

                                ViewModelUser user = new ViewModelUser()
                                {
                                    Id         = new Guid(appUser.Id),
                                    Name       = appUser.Name,
                                    LastName   = appUser.LastName,
                                    UserName   = appUser.UserName,
                                    Email      = appUser.Email,
                                    Country    = appUser.Country,
                                    ImageBytes = bytes,
                                    Picture    = appUser.Picture
                                };

                                return(Json(new ViewModelResponse()
                                {
                                    Error = false, Response = "Ha iniciado sesión satisfactoriamente", User = user, Token = token
                                }));
                            }
                            else
                            {
                                return(Json(new ViewModelResponse()
                                {
                                    Error = true, Response = "Valide sus credenciales."
                                }));
                            }
                        }
                        return(Json(new ViewModelResponse()
                        {
                            Error = true, Response = "Debe verificar primero su cuenta, revise su correo."
                        }));
                    }
                    return(Json(new ViewModelResponse()
                    {
                        Error = true, Response = "Valide sus credenciales. Usuario no encontrado"
                    }));
                }
                else
                {
                    return(Json(new ViewModelResponse()
                    {
                        Error = true, Response = "Valide sus credenciales. Usuario no encontrado"
                    }));
                }
            }
            catch (Exception e)
            {
                string error = String.Format("Ocurrion un error. Intente nuevamente. {0}", e.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError, new ViewModelResponse {
                    Error = true, Response = error
                }));
            }
        }
        public async Task <ActionResult <ViewModelResponse> > Register([FromBody] ViewModelUser model)
        {
            try
            {
                var user = new ApplicationUser
                {
                    UserName   = model.UserName,
                    Name       = model.Name,
                    LastName   = model.LastName,
                    Email      = model.Email,
                    Country    = model.Country,
                    Picture    = model.Picture,
                    Verified   = true,
                    WonGames   = 0,
                    LostGames  = 0,
                    TotalGames = 0
                };

                if (!model.Password.Equals(model.ConfirmedPassword))
                {
                    return(Json(new ViewModelResponse()
                    {
                        Error = true, Response = "Las contraseñas no coinciden"
                    }));
                }

                //crear entry en organizacion hangeddraw, gid number user

                var result = _userManager.CreateAsync(user, model.Password);
                if (result.Result.Succeeded)
                {
                    var aLdap = await ServiceLDAP.RegisterAsync(user.UserName, model.Password, model.Name, model.LastName, model.Email);

                    if (aLdap)
                    {
                        //// enviar correo para verificar usuario registrado
                        //string email = model.Email;
                        //string subject = "Confirmación de registro en Hanged Draw";
                        //string url = Request.Scheme + "://" + Request.Host.Value + "/api/User/Verify";
                        //string link = String.Format("<a target=\"_blank\" href=\"{1}/{0}\"> link </a>", user.Id, url);
                        //string style = "style=\"color: red;\"";
                        //string styleP = "style=\"color: black;\"";

                        //string htmlString =
                        //                $@"<html>
                        //    <body>
                        //        <h2 {style}>Hanged Draw</h2>
                        //        <p {styleP} >por favor verifique su cuenta dando click en el siguiente {link} </p>
                        //        <br>
                        //    </body>
                        //</html>";


                        //bool a = await SendEmailAsync(email, subject, htmlString);
                        //if (a)
                        //    return Json(new ViewModelResponse() { Error = false, Response = "Usuario registrado satisfactoriamente." });
                        return(Json(new ViewModelResponse()
                        {
                            Error = false, Response = "Usuario registrado satisfactoriamente."
                        }));
                    }
                    else
                    {
                        return(Json(new ViewModelResponse()
                        {
                            Error = true, Response = "Ocurrio un error en ldap"
                        }));
                    }
                }

                string error = string.Empty;
                foreach (var e in result.Result.Errors)
                {
                    error += "{" + e.Code + "}-" + e.Description + Environment.NewLine;
                }

                return(Json(new ViewModelResponse()
                {
                    Error = true, Response = error
                }));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new ViewModelResponse()
                {
                    Error = true,
                    Response = String.Format("Ocurrio un error al intentar verificar el correo electrónico, intenta nueva mente. {0}", e.Message)
                }));
            }
        }
        public async Task <ActionResult <ViewModelResponse> > ChangePassword([FromBody] ViewModelPassword model, int id, string token)
        {
            try
            {
                // verificar token de solicitud
                var pr = _dbContext.PasswordReminder.FirstOrDefault(x => x.Id == id && x.Token.Equals(new Guid(token)));
                if (pr != null)
                {
                    if (DateTime.Now.CompareTo(pr.ExpiresAt) < 0)
                    {
                        if (!model.NewPassword.Equals(model.ConfirmedNewPassword))
                        {
                            return(Json(new ViewModelResponse()
                            {
                                Error = true, Response = "Las contraseñas no coinciden."
                            }));
                        }

                        var user = await _userManager.FindByIdAsync(pr.IdUser.ToString());

                        if (user != null)
                        {
                            var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword);

                            if (result.Succeeded)
                            {
                                var aLdap = await ServiceLDAP.ModifyAsync(user.UserName, user.UserName, model.NewPassword, user.Name, user.LastName, user.Email);

                                if (aLdap)
                                {
                                    _dbContext.PasswordReminder.Remove(pr);
                                    _dbContext.SaveChanges();
                                    return(Json(new ViewModelResponse()
                                    {
                                        Error = false, Response = "Contraseña modificada exitosamente."
                                    }));
                                }
                                else
                                {
                                    return(Json(new ViewModelResponse()
                                    {
                                        Error = true, Response = "Ocurrio un error"
                                    }));
                                }
                            }
                            else
                            {
                                string error = string.Empty;
                                foreach (var e in result.Errors)
                                {
                                    error += "{" + e.Code + "}-" + e.Description + Environment.NewLine;
                                }
                                return(Json(new ViewModelResponse()
                                {
                                    Error = true, Response = error
                                }));
                            }
                        }
                        return(Json(new ViewModelResponse()
                        {
                            Error = true, Response = "Usuario no encontrado"
                        }));
                    }
                    return(Json(new ViewModelResponse()
                    {
                        Error = true, Response = "Token de cambio de contraseña ya expiró, solicite uno nuevo."
                    }));
                }
                return(Json(new ViewModelResponse()
                {
                    Error = true, Response = "Token de cambio de contraseña no encontrado o éste ya espiró."
                }));
            }
            catch (Exception e)
            {
                return(Json(new ViewModelResponse()
                {
                    Error = true, Response = String.Format("Ocurrio un error al intentar verificar el correo electrónico, intenta nueva mente. {0}", e.Message)
                }));
            }
        }
        public async Task <ActionResult <ViewModelResponse> > ChangePasswordUser([FromBody] ViewModelPassword model, string id)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id);

                if (user != null)
                {
                    if (!model.NewPassword.Equals(model.ConfirmedNewPassword))
                    {
                        return(StatusCode(StatusCodes.Status400BadRequest, new ViewModelResponse()
                        {
                            Error = true, Response = "Las contraseñas no coinciden."
                        }));
                    }


                    var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword);

                    if (result.Succeeded)
                    {
                        var aLdap = await ServiceLDAP.ModifyAsync(user.UserName, user.UserName, model.NewPassword, user.Name, user.LastName, user.Email);

                        if (aLdap)
                        {
                            return(Json(new ViewModelResponse()
                            {
                                Error = false, Response = "Contraseña modificada exitosamente."
                            }));
                        }
                        else
                        {
                            return(Json(new ViewModelResponse()
                            {
                                Error = true, Response = "Ocurrio un error"
                            }));
                        }
                    }
                    else
                    {
                        string error = string.Empty;
                        foreach (var e in result.Errors)
                        {
                            error += "{" + e.Code + "}-" + e.Description + Environment.NewLine;
                        }
                        return(Json(new ViewModelResponse()
                        {
                            Error = true, Response = error
                        }));
                    }
                }
                return(Json(new ViewModelResponse()
                {
                    Error = true, Response = "El usuario no existe"
                }));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new ViewModelResponse()
                {
                    Error = true, Response = String.Format("Ocurrio un error al intentar verificar el correo electrónico, intenta nueva mente. {0}", e.Message)
                }));
            }
        }