public JsonResult vLogin(string email, string pw)
        {
            SynapseResponse response = new SynapseResponse();
            response.callId = MyUtility.GetSHA1((String.Format("{0}{1}", Guid.NewGuid().ToString(), DateTime.Now.ToString()))).ToLower();
            try
            {
                string EmailAddress = email;
                string Password = pw;
                var context = new IPTV2Entities();

                if (String.IsNullOrEmpty(EmailAddress))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Email address is required.";
                }

                if (String.IsNullOrEmpty(Password))
                {
                    response.errorCode = (int)ErrorCodes.IsMissingRequiredFields;
                    response.errorMessage = "Password is required.";
                }

                var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                if (user == null)
                {
                    response.errorCode = (int)ErrorCodes.UserDoesNotExist;
                    response.errorMessage = "User does not exist";
                }
                else
                {
                    Password = MyUtility.GetSHA1(Password);
                    if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0)
                    {
                        SynapseUserInfo uInfo = new SynapseUserInfo() { firstName = user.FirstName, lastName = user.LastName, email = user.EMail };
                        Dictionary<string, object> collection = new Dictionary<string, object>();
                        collection.Add("client_id", GlobalConfig.GSapikey);
                        collection.Add("client_secret", GlobalConfig.GSsecretkey);
                        collection.Add("grant_type", "none");
                        collection.Add("x_siteUID", user.UserId);
                        collection.Add("x_sessionExpiration", 0);
                        collection.Add("x_userInfo", JsonConvert.SerializeObject(uInfo));
                        GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
                        SynapseCookie cookie = new SynapseCookie()
                        {
                            cookieName = FormsAuthentication.FormsCookieName,
                            cookiePath = FormsAuthentication.FormsCookiePath,
                            cookieDomain = FormsAuthentication.CookieDomain
                        };
                        if (res.GetErrorCode() == 0)
                        { // Successful login to Gigya
                            HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString());
                            cookie.cookieValue = authCookie.Value;
                            ContextHelper.SaveSessionInDatabase(context, user, authCookie.Value);
                            SynapseToken token = new SynapseToken()
                            {
                                uid = user.UserId.ToString(),
                                token = res.GetString("access_token", String.Empty),
                                expire = res.GetInt("expires_in", 0),
                            };
                            response.data = token;
                            response.info = cookie;
                        }
                        else
                        {
                            response.errorCode = res.GetErrorCode();
                            response.errorMessage = "Gigya encountered an error logging you in, please try again";
                            response.errorDetails = res.GetErrorMessage();
                        }
                    }
                    else
                    {
                        response.errorCode = (int)ErrorCodes.IsWrongPassword;
                        response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsWrongPassword);
                    }
                }
            }
            catch (Exception e) { response.errorCode = (int)ErrorCodes.UnknownError; response.errorMessage = "System encountered an unspecified error, please try again"; response.errorDetails = e.Message; }
            return this.Json(response, JsonRequestBehavior.AllowGet);
        }
 private GSResponse GetToken(User user)
 {
     SynapseUserInfo uInfo = new SynapseUserInfo() { firstName = user.FirstName, lastName = user.LastName, email = user.EMail };
     Dictionary<string, object> collection = new Dictionary<string, object>();
     collection.Add("client_id", GlobalConfig.GSapikey);
     collection.Add("client_secret", GlobalConfig.GSsecretkey);
     collection.Add("grant_type", "none");
     collection.Add("x_siteUID", user.UserId);
     collection.Add("x_sessionExpiration", 0);
     collection.Add("x_userInfo", JsonConvert.SerializeObject(uInfo));
     return GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
 }
        public JsonResult GSocialize()
        {
            var ReturnCode = new SocializeReturnCodeObj()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            var registDt = DateTime.Now;
            var skipValidation = false;
            try
            {
                if (!String.IsNullOrEmpty(Request.QueryString["sv"]))
                {
                    var svTemp = Convert.ToInt32(Request.QueryString["sv"]);
                    if (svTemp == 1)
                        skipValidation = true;
                }
            }

            catch (Exception) { }
            try
            {
                NameValueCollection qs = Request.QueryString;
                string gigyaUID = Uri.UnescapeDataString(qs["UID"]);
                bool isRequestValid = SigUtils.ValidateUserSignature(gigyaUID, Uri.UnescapeDataString(qs["timestamp"]), GlobalConfig.GSsecretkey, Uri.UnescapeDataString(qs["signature"]));
                if (isRequestValid || skipValidation)
                {
                    using (var context = new IPTV2Entities())
                    {
                        User user = null;
                        bool isSiteUID = Convert.ToBoolean(qs["isSiteUID"]);
                        if (isSiteUID) //Old user. Signin to site
                        {
                            var UserId = new Guid(gigyaUID);
                            user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                            if (user != null)
                            {
                                if (user.StatusId == GlobalConfig.Visible) //Successful Login
                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                else
                                    ReturnCode.StatusMessage = "Account is not verified in our system.";
                            }
                            else
                            {
                                //ReturnCode.StatusMessage = "Social networking account does not exist in our system.";
                                //Create user                                
                                string FirstName = qs["first_name"];
                                string LastName = qs["last_name"];
                                string EMail = qs["login_email"];
                                string uid = qs["uid"];
                                string provider = qs["provider"];
                                string Password = Membership.GeneratePassword(10, 2);
                                string City = String.Empty;
                                string State = String.Empty;
                                string CountryCode = GlobalConfig.DefaultCountry;
                                var id = UserId;
                                var ip = qs["ip"];

                                try
                                {
                                    var location = MyUtility.GetLocationBasedOnIpAddress(ip);
                                    City = location.city;
                                    CountryCode = location.countryCode;
                                    State = String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0 ? location.region : location.regionName;
                                }
                                catch (Exception) { }

                                user = new User()
                                {
                                    UserId = id,
                                    FirstName = FirstName,
                                    LastName = LastName,
                                    City = City,
                                    State = State,
                                    CountryCode = CountryCode,
                                    EMail = EMail,
                                    Password = MyUtility.GetSHA1(Password),
                                    GigyaUID = id.ToString(),
                                    RegistrationDate = registDt,
                                    LastUpdated = registDt,
                                    RegistrationIp = ip ?? MyUtility.GetClientIpAddress(),
                                    DateVerified = registDt,
                                    StatusId = GlobalConfig.Visible,
                                    ActivationKey = Guid.NewGuid()
                                };

                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0);
                                if (country != null)
                                    CurrencyCode = country.CurrencyCode;

                                var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0);
                                if (wallet == null)
                                {
                                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                                    user.UserWallets.Add(wallet);
                                }

                                var transaction = new RegistrationTransaction()
                                {
                                    RegisteredState = user.State,
                                    RegisteredCity = user.City,
                                    RegisteredCountryCode = user.CountryCode,
                                    Amount = 0,
                                    Currency = CurrencyCode,
                                    Reference = "New Registration (AIR PLUS)",
                                    Date = registDt,
                                    OfferingId = GlobalConfig.offeringId,
                                    UserId = user.UserId,
                                    StatusId = GlobalConfig.Visible
                                };

                                user.Transactions.Add(transaction);
                                context.Users.Add(user);

                                if (context.SaveChanges() > 0)
                                {
                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                    GSResponse res = null;

                                    GigyaUserData2 userData = new GigyaUserData2()
                                    {
                                        city = user.City,
                                        country = user.CountryCode,
                                        email = user.EMail,
                                        firstName = user.FirstName,
                                        lastName = user.LastName,
                                        state = user.State
                                    };

                                    TFCTV.Helpers.UserData privacyData = new UserData() { IsExternalSharingEnabled = "true,false", IsInternalSharingEnabled = "true,false", IsProfilePrivate = "false" };
                                    GigyaUserDataInfo2 userDataInfo = new GigyaUserDataInfo2()
                                    {
                                        UID = user.UserId.ToString(),
                                        profile = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None),
                                        data = Newtonsoft.Json.JsonConvert.SerializeObject(privacyData, Formatting.None)
                                    };

                                    GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo));                                    //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj);
                                    res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj);

                                    //Publish to Activity Feed
                                    List<ActionLink> actionlinks = new List<ActionLink>();
                                    actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) });
                                    //mediaItem
                                    List<MediaItem> mediaItems = new List<MediaItem>();
                                    mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) });
                                    UserAction action = new UserAction()
                                    {
                                        actorUID = user.UserId.ToString(),
                                        userMessage = SNSTemplates.register_usermessage,
                                        title = SNSTemplates.register_title,
                                        subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle),
                                        linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback),
                                        description = String.Format(SNSTemplates.register_description, FirstName),
                                        actionLinks = actionlinks,
                                        mediaItems = mediaItems
                                    };

                                    GigyaMethods.PublishUserAction(action, user.UserId, "external");
                                    action.userMessage = String.Empty;
                                    action.title = String.Empty;
                                    action.mediaItems = null;
                                    GigyaMethods.PublishUserAction(action, user.UserId, "internal");
                                }
                            }
                        }
                        else //New user. allow user to register
                        {
                            bool createUser = true;
                            if (!String.IsNullOrEmpty(qs["email"]))
                            {
                                string email = qs["email"];
                                user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0);
                                if (user != null) // link account
                                {
                                    Dictionary<string, object> collection = new Dictionary<string, object>();
                                    collection.Add("siteUID", user.UserId);
                                    collection.Add("uid", Uri.UnescapeDataString(qs["UID"]));
                                    collection.Add("cid", String.Format("{0} - New User", qs["provider"]));

                                    GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection));
                                    GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", obj);
                                    if (res.GetErrorCode() == 0) //Successful link
                                    {
                                        createUser = false;
                                        var UserId = user.UserId.ToString();
                                        user.StatusId = GlobalConfig.Visible; //activate account
                                        user.DateVerified = DateTime.Now;
                                        if (context.SaveChanges() > 0)
                                            ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                        else
                                            ReturnCode.StatusMessage = "Create user failed";
                                    }
                                    else
                                        ReturnCode.StatusMessage = res.GetErrorMessage();
                                }
                            }

                            if (createUser)
                            {
                                string FirstName = qs["first_name"];
                                string LastName = qs["last_name"];
                                string EMail = qs["login_email"];
                                string uid = qs["uid"];
                                string provider = qs["provider"];
                                string Password = Membership.GeneratePassword(10, 2);
                                string City = String.Empty;
                                string State = String.Empty;
                                string CountryCode = GlobalConfig.DefaultCountry;
                                var id = Guid.NewGuid();
                                var ip = qs["ip"];

                                try
                                {
                                    var location = MyUtility.GetLocationBasedOnIpAddress(ip);
                                    City = location.city;
                                    CountryCode = location.countryCode;
                                    State = String.Compare(CountryCode, GlobalConfig.DefaultCountry, true) == 0 ? location.region : location.regionName;
                                }
                                catch (Exception) { }


                                user = new User()
                                {
                                    UserId = id,
                                    FirstName = FirstName,
                                    LastName = LastName,
                                    City = City,
                                    State = State,
                                    CountryCode = CountryCode,
                                    EMail = EMail,
                                    Password = MyUtility.GetSHA1(Password),
                                    GigyaUID = id.ToString(),
                                    RegistrationDate = registDt,
                                    LastUpdated = registDt,
                                    RegistrationIp = ip ?? MyUtility.GetClientIpAddress(),
                                    ActivationKey = Guid.NewGuid()
                                };

                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0);
                                if (country != null)
                                    CurrencyCode = country.CurrencyCode;

                                var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0);
                                if (wallet == null)
                                {
                                    wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt);
                                    user.UserWallets.Add(wallet);
                                }

                                var transaction = new RegistrationTransaction()
                                {
                                    RegisteredState = user.State,
                                    RegisteredCity = user.City,
                                    RegisteredCountryCode = user.CountryCode,
                                    Amount = 0,
                                    Currency = CurrencyCode,
                                    Reference = "New Registration (AIR PLUS)",
                                    Date = registDt,
                                    OfferingId = GlobalConfig.offeringId,
                                    UserId = user.UserId,
                                    StatusId = GlobalConfig.Visible
                                };

                                user.Transactions.Add(transaction);
                                context.Users.Add(user);

                                if (context.SaveChanges() > 0)
                                {
                                    GSResponse res = null;
                                    if (!String.IsNullOrEmpty(uid) && !String.IsNullOrEmpty(provider))
                                    {
                                        Dictionary<string, object> collection = new Dictionary<string, object>();
                                        collection.Add("siteUID", user.UserId);
                                        collection.Add("uid", Uri.UnescapeDataString(uid));
                                        collection.Add("cid", String.Format("{0} - New User", provider));
                                        res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
                                        if (res.GetErrorCode() == 0) //Successful link
                                        {
                                            if (user != null)
                                            {
                                                var UserId = user.UserId.ToString();
                                                user.StatusId = GlobalConfig.Visible; //activate account
                                                user.DateVerified = DateTime.Now;
                                                if (context.SaveChanges() > 0)
                                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                            }
                                        }
                                    }
                                    else
                                        ReturnCode.StatusMessage = "Missing parameters uid & provider";
                                    //else
                                    //{
                                    //    var info = new GigyaUserInfo()
                                    //    {
                                    //        firstName = FirstName,
                                    //        lastName = LastName,
                                    //        email = EMail
                                    //    };

                                    //    var registrationInfo = new GigyaNotifyLoginInfo()
                                    //    {
                                    //        siteUID = user.UserId.ToString(),
                                    //        cid = "TFCTV - Registration",
                                    //        sessionExpiration = 0,
                                    //        newUser = true,
                                    //        userInfo = Newtonsoft.Json.JsonConvert.SerializeObject(info)
                                    //    };
                                    //    GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(registrationInfo));
                                    //    res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", obj);
                                    //    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                    //}

                                    if (ReturnCode.StatusCode == (int)ErrorCodes.Success)
                                    {
                                        GigyaUserData2 userData = new GigyaUserData2()
                                        {
                                            city = user.City,
                                            country = user.CountryCode,
                                            email = user.EMail,
                                            firstName = user.FirstName,
                                            lastName = user.LastName,
                                            state = user.State
                                        };

                                        TFCTV.Helpers.UserData privacyData = new UserData() { IsExternalSharingEnabled = "true,false", IsInternalSharingEnabled = "true,false", IsProfilePrivate = "false" };

                                        GigyaUserDataInfo2 userDataInfo = new GigyaUserDataInfo2()
                                        {
                                            UID = user.UserId.ToString(),
                                            profile = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None),
                                            data = Newtonsoft.Json.JsonConvert.SerializeObject(privacyData, Formatting.None)
                                        };

                                        GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo));                                    //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj);
                                        res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj);

                                        //Publish to Activity Feed
                                        List<ActionLink> actionlinks = new List<ActionLink>();
                                        actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) });
                                        //mediaItem
                                        List<MediaItem> mediaItems = new List<MediaItem>();
                                        mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) });
                                        UserAction action = new UserAction()
                                        {
                                            actorUID = user.UserId.ToString(),
                                            userMessage = SNSTemplates.register_usermessage,
                                            title = SNSTemplates.register_title,
                                            subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle),
                                            linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback),
                                            description = String.Format(SNSTemplates.register_description, FirstName),
                                            actionLinks = actionlinks,
                                            mediaItems = mediaItems
                                        };

                                        GigyaMethods.PublishUserAction(action, user.UserId, "external");
                                        action.userMessage = String.Empty;
                                        action.title = String.Empty;
                                        action.mediaItems = null;
                                        GigyaMethods.PublishUserAction(action, user.UserId, "internal");
                                    }
                                }
                            }
                        }

                        if (ReturnCode.StatusCode == (int)ErrorCodes.Success)
                        {
                            ReturnCode.StatusMessage = "Success!";

                            //GenerateToken
                            SynapseUserInfo uInfo = new SynapseUserInfo() { firstName = user.FirstName, lastName = user.LastName, email = user.EMail };
                            Dictionary<string, object> collection = new Dictionary<string, object>();
                            collection.Add("client_id", GlobalConfig.GSapikey);
                            collection.Add("client_secret", GlobalConfig.GSsecretkey);
                            collection.Add("grant_type", "none");
                            collection.Add("x_siteUID", user.UserId);
                            collection.Add("x_sessionExpiration", 0);
                            collection.Add("x_userInfo", JsonConvert.SerializeObject(uInfo));
                            GSResponse res = GigyaHelpers.createAndSendRequest("socialize.getToken", GigyaHelpers.buildParameter(collection));
                            SynapseCookie cookie = new SynapseCookie()
                            {
                                cookieName = FormsAuthentication.FormsCookieName,
                                cookiePath = FormsAuthentication.FormsCookiePath,
                                cookieDomain = FormsAuthentication.CookieDomain
                            };

                            if (res.GetErrorCode() == 0)
                            {
                                HttpCookie authCookie = SetCookie(user.UserId.ToString());
                                cookie.cookieValue = authCookie.Value;
                                ContextHelper.SaveSessionInDatabase(context, user, authCookie.Value);
                                SynapseToken token = new SynapseToken()
                                {
                                    uid = user.UserId.ToString(),
                                    token = res.GetString("access_token", String.Empty),
                                    expire = res.GetInt("expires_in", 0),
                                };

                                ReturnCode.tk = token;
                                ReturnCode.gs = cookie;
                            }
                            else
                            {
                                ReturnCode.StatusCode = res.GetErrorCode();
                                ReturnCode.StatusMessage = res.GetErrorMessage();
                            }
                        }
                    }
                }
                else
                    ReturnCode.StatusMessage = "Request is not valid";
            }
            catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusMessage = String.Format("Exception: {0} | Inner Exception: {1}", e.Message, e.InnerException.Message); }
            return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }