public ActionResult ReturnFrom(RedSocial tipo, string code)
        {
            var goTo = CacheHelper.GetKey(CacheHelper.GetNotLoggedUserKey());

            try
            {
                using (WebClient client = new WebClient())
                {
                    ISocialUser user;
                    byte[]      response;
                    switch (tipo)
                    {
                    case RedSocial.Google:
                        throw new Exception("Loggeo incorrecto con Google");
                        break;

                    case RedSocial.Instagram:
                        response =
                            client.UploadValues("https://api.instagram.com/oauth/access_token", new NameValueCollection()
                        {
                            { "client_id", SocialIds.InstagramClientId },
                            { "client_secret", SocialIds.InstagramClientSecret },
                            { "grant_type", SocialIds.InstagramGrantType },
                            { "redirect_uri", (WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["urlInstagramRedirect"]) },
                            { "code", code },
                        });

                        InstagramResponseValidationCode responseI = JsonConvert.DeserializeObject <InstagramResponseValidationCode>(System.Text.Encoding.UTF8.GetString(response));
                        user = responseI.user;
                        ((InstagramUser)user).Token = responseI.access_token;

                        break;

                    case RedSocial.FaceBook:
                        response = client.UploadValues("https://graph.facebook.com/v2.9/oauth/access_token", new NameValueCollection()
                        {
                            { "client_id", SocialIds.FacebookAppId },
                            { "redirect_uri", WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["urlFacebookRedirect"] },
                            { "client_secret", SocialIds.FacebookSecret },
                            { "code", code }
                        });

                        FacebookResponseValidationCode obj = JsonConvert.DeserializeObject <FacebookResponseValidationCode>(System.Text.Encoding.UTF8.GetString(response));

                        //No se por que no anda de esta forma
                        //byte[] userResponse = client.UploadValues("https://graph.facebook.com/v2.9/me", new NameValueCollection()
                        //{
                        //    { "fields", "email,id,first_name,last_name,name,picture.type(large)" },
                        //    { "access_token", obj.access_token }
                        //});

                        //FacebookUser fbUser = JsonConvert.DeserializeObject<FacebookUser>(System.Text.Encoding.UTF8.GetString(response));
                        //user = fbUser;
                        using (HttpClient cliente = new HttpClient())
                        {
                            var mess = cliente.GetStringAsync("https://graph.facebook.com/me?fields=email,name,picture.type(large),id&access_token=" + obj.access_token);
                            user = JsonConvert.DeserializeObject <FacebookUser>(mess.Result);
                            ((FacebookUser)user).Token = obj.access_token;
                        }
                        break;

                    case RedSocial.Spotify:
                        SpotifyResponseValidationCode responseS;
                        using (HttpClient cliente = new HttpClient())
                        {
                            Dictionary <string, string> postData = new Dictionary <string, string>();
                            postData.Add("grant_type", "authorization_code");
                            postData.Add("code", code);
                            postData.Add("redirect_uri", WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["urlSpotifyRedirect"]);
                            postData.Add("client_id", SocialIds.SpotifyClientId);
                            postData.Add("client_secret", SocialIds.SpotifySecret);
                            var content      = new FormUrlEncodedContent(postData);
                            var httpResponse = cliente.PostAsync("https://accounts.spotify.com/api/token", content).Result.Content.ReadAsStringAsync().Result;
                            responseS = JsonConvert.DeserializeObject <SpotifyResponseValidationCode>(httpResponse);
                        }
                        using (HttpClient cliente = new HttpClient())
                        {
                            cliente.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", responseS.access_token);

                            var mess = cliente.GetAsync("https://api.spotify.com/v1/me").Result.Content.ReadAsStringAsync();
                            user = JsonConvert.DeserializeObject <SpotifyUser>(mess.Result);
                            ((SpotifyUser)user).accessToken = responseS.access_token;
                        }
                        break;

                    case RedSocial.SoundCloud:
                        throw new Exception("Loggeo incorrecto con SoundCloud");
                        break;

                    default:
                        throw new Exception("Loggeo incorrecto con Random");
                        break;
                    }


                    if (ExisteUsuarioSocial(user.GetId()))
                    {
                        //existe el user, loguearlo
                        var id         = user.GetId();
                        var userSocial = new Repositorio <UsuarioSocial>(new ApplicationDbContext()).TraerTodos().Single(u => u.IdSocial == id);
                        var usuarios   = new Repositorio <Clubber>(db).TraerTodos()
                                         .Where(r => r.CredencialesSociales.Any(c => c.IdSocial == userSocial.IdSocial));

                        SignInManager.SignIn(usuarios.First().UsuarioApplicacion, true, true);

                        if (string.IsNullOrEmpty(goTo))
                        {
                            return(RedirectToAction("Index", "Frontend"));
                        }
                        else
                        {
                            return(RedirectToLocal(goTo.ToString()));
                        }
                    }
                    else
                    {
                        //no existe el user -> crearlo
                        var nuevo = new RegisterFrontViewModel();
                        nuevo.Name     = user.GetName();
                        nuevo.IdSocial = user.GetId();
                        nuevo.Email    = string.IsNullOrWhiteSpace(user.GetEmail()) ? user.GetName().Replace(" ", "") + "@danzfloor.com.ar" : user.GetEmail();

                        var clubberRepo = new Repositorio <Clubber>(db);
                        if (clubberRepo.TraerTodos().Any(u => u.UsuarioApplicacion.UserName == nuevo.Email))
                        {
                            var clubber    = clubberRepo.TraerTodos().First(u => u.UsuarioApplicacion.UserName == nuevo.Email);
                            var userSocial = new UsuarioSocial
                            {
                                AccessToken = user.GetAccessToken(),
                                Apellido    = "",
                                Email       = user.GetEmail(),
                                Nombre      = user.GetName(),
                                IdSocial    = user.GetId(),
                                RedSocial   = user is FacebookUser ? RedSocial.FaceBook : user is SpotifyUser ? RedSocial.Spotify : RedSocial.Instagram,
                            };

                            clubber.CredencialesSociales = new List <Models.Dominio.UsuarioSocial>();
                            clubber.CredencialesSociales.Add(userSocial);
                            clubberRepo.GuardarCambios();



                            SignInManager.SignIn(clubber.UsuarioApplicacion, true, true);

                            return(RedirectToAction("Index", "Frontend"));
                        }

                        var appUser = new ApplicationUser
                        {
                            UserName = nuevo.Email,
                            Email    = nuevo.Email,
                            Name     = nuevo.Name,
                            Lastname = "",
                            TokenFechaVencimiento = DateTime.Now.AddDays(7),
                        };


                        var usuario = new Clubber();
                        usuario.UsuarioApplicacion = appUser;
                        usuario.Nombre             = nuevo.Name;
                        usuario.Apellido           = "";
                        usuario.Email           = nuevo.Email;
                        usuario.FechaNacimiento = DateTime.Now;
                        usuario.Sexo            = new Repositorio <Sexo>(db).TraerTodos().First();

                        if (!string.IsNullOrWhiteSpace(user.GetId()))
                        {
                            var userSocial = new UsuarioSocial
                            {
                                Apellido  = "",
                                Email     = nuevo.Email,
                                Nombre    = nuevo.Name,
                                IdSocial  = nuevo.IdSocial,
                                RedSocial = RedSocial.Instagram,
                            };

                            usuario.CredencialesSociales = new List <Models.Dominio.UsuarioSocial>();
                            usuario.CredencialesSociales.Add(userSocial);
                        }
                        new Repositorio <Usuario>(db).Crear(usuario);
                        UserManager.AddPassword(usuario.UsuarioApplicacion.Id, "qweQWE123!#");

                        UserManager.AddToRole(appUser.Id, RoleConst.Clubber);

                        SignInManager.SignIn(appUser, true, true);

                        return(RedirectToAction("Index", "Frontend"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public ActionResult Registrar(RegisterFrontViewModel model)
        {
            string ContraseñaError = "La contraseña debe tener al menos: <br>- 6 caracteres</br>- 1 minúscula</br>- 1 mayúscula</br>- 1 símbolo (ej: $, % o !)</br>- 1 número";

            try
            {
                if (string.IsNullOrWhiteSpace(model.Email))
                {
                    ViewBag.Error = "No ha completado el mail";
                    return(View("Registrar", model));
                }
                if (string.IsNullOrWhiteSpace(model.Name))
                {
                    ViewBag.Error = "No ha completado el nombre";
                    return(View("Registrar", model));
                }
                if (string.IsNullOrWhiteSpace(model.IdSocial))
                {
                    if (string.IsNullOrWhiteSpace(model.Password) || string.IsNullOrWhiteSpace(model.ConfirmPassword))
                    {
                        ViewBag.Error = "No ha completado la contraseña y su confirmación";
                        return(View("Registrar", model));
                    }
                    if (model.Password != model.ConfirmPassword)
                    {
                        ViewBag.Error = "La contraseña y su confirmación no son iguales";
                        return(View("Registrar", model));
                    }
                    if (model.Password.Length < 6)
                    {
                        ViewBag.Error = ContraseñaError;
                        return(View("Registrar", model));
                    }
                    if (!model.Password.Any(c => char.IsLower(c)))
                    {
                        ViewBag.Error = ContraseñaError;
                        return(View("Registrar", model));
                    }
                    if (!model.Password.Any(c => char.IsUpper(c)))
                    {
                        ViewBag.Error = ContraseñaError;
                        return(View("Registrar", model));
                    }
                    if (!model.Password.Any(c => char.IsNumber(c)))
                    {
                        ViewBag.Error = ContraseñaError;
                        return(View("Registrar", model));
                    }
                    //Regex RgxUrl = new Regex("[^a-z0-9]");
                    if (model.Password.All(Char.IsLetterOrDigit))
                    {
                        ViewBag.Error = ContraseñaError;
                        return(View("Registrar", model));
                    }
                }
                else
                {
                    model.Password        = "******";
                    model.ConfirmPassword = "******";
                }
                if (new Repositorio <Usuario>(db).TraerTodos().Any(u => u.UsuarioApplicacion.UserName == model.Email))
                {
                    ViewBag.Error = "El email ingresado ya se encuentra en uso";
                    return(View("Registrar", model));
                }

                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    Name     = model.Name,
                    Lastname = "",
                    TokenFechaVencimiento = DateTime.Now.AddDays(7),
                };


                var usuario = new Clubber();
                usuario.UsuarioApplicacion = user;
                usuario.Nombre             = model.Name;
                usuario.Apellido           = "";
                usuario.Email           = model.Email;
                usuario.FechaNacimiento = DateTime.Now;
                usuario.Sexo            = new Repositorio <Sexo>(db).TraerTodos().First();

                if (!string.IsNullOrWhiteSpace(model.IdSocial))
                {
                    var userSocial = new UsuarioSocial
                    {
                        Apellido  = "",
                        Email     = model.Email,
                        Nombre    = model.Name,
                        IdSocial  = model.IdSocial,
                        RedSocial = RedSocial.Instagram,
                    };

                    usuario.CredencialesSociales = new List <Models.Dominio.UsuarioSocial>();
                    usuario.CredencialesSociales.Add(userSocial);
                }
                new Repositorio <Usuario>(db).Crear(usuario);
                UserManager.AddPassword(usuario.UsuarioApplicacion.Id, model.Password);

                UserManager.AddToRole(user.Id, RoleConst.Clubber);

                SignInManager.SignIn(user, true, true);

                return(RedirectToAction("Index", "Frontend"));
            }
            catch (Exception ex)
            {
                ViewBag.Error = "Ha ocurrido un error!";
                return(View("Registrar", model));
            }
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl, string provider)
        {
            var goTo = CacheHelper.GetKey(CacheHelper.GetNotLoggedUserKey());

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (ExisteUsuarioSocial(loginInfo.Email))
            {
                //existe el user, loguearlo
                var userSocial = new Repositorio <UsuarioSocial>(new ApplicationDbContext()).TraerTodos().Single(u => u.IdSocial == loginInfo.Email);
                var usuarios   = new Repositorio <Clubber>(db).TraerTodos()
                                 .Where(r => r.CredencialesSociales.Any(c => c.IdSocial == userSocial.IdSocial));

                SignInManager.SignIn(usuarios.First().UsuarioApplicacion, true, true);

                if (string.IsNullOrEmpty(goTo))
                {
                    return(RedirectToAction("Index", "Frontend"));
                }
                else
                {
                    return(RedirectToLocal(goTo.ToString()));
                }
            }
            else
            {
                //no existe el user -> crearlo
                var user = new ApplicationUser
                {
                    UserName = loginInfo.Email,
                    Email    = loginInfo.Email,
                    Name     = loginInfo.DefaultUserName,
                    Lastname = "",
                    TokenFechaVencimiento = DateTime.Now.AddDays(7),
                };

                var userSocial = new UsuarioSocial
                {
                    Apellido  = "",
                    Email     = loginInfo.Email,
                    Nombre    = loginInfo.DefaultUserName,
                    IdSocial  = loginInfo.Email,
                    RedSocial = provider == "Google" ? RedSocial.Google : RedSocial.FaceBook,
                };

                var usuario = new Clubber();
                usuario.UsuarioApplicacion = user;
                usuario.Nombre             = loginInfo.DefaultUserName;
                usuario.Apellido           = "";
                usuario.Email           = loginInfo.Email;
                usuario.FechaNacimiento = DateTime.Now;
                usuario.Sexo            = new Repositorio <Sexo>(db).TraerTodos().First();

                usuario.CredencialesSociales = new List <Models.Dominio.UsuarioSocial>();
                usuario.CredencialesSociales.Add(userSocial);

                new Repositorio <Usuario>(db).Crear(usuario);
                UserManager.AddPassword(usuario.UsuarioApplicacion.Id, "qweQWE123!#");

                UserManager.AddToRole(user.Id, RoleConst.Clubber);

                SignInManager.SignIn(user, true, true);

                return(RedirectToAction("Index", "Frontend"));
            }
        }