Example #1
0
        static void TestAsyncGSRequest()
        {
            string method = "socialize.getUserInfo";

            // Should give response from server
            GSRequest request = new GSRequest(apiKey, secretKey, method, false);

            request.SetParam("uid", "3111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
            request.SetParam("enabledProviders", "*,testnetwork,testnetwork2");
            request.APIDomain = "";

            GSResponse   response = null;
            IAsyncResult iar      = request.BeginSend((IAsyncResult innerIAsyncResult) =>
            {
                response = request.EndSend(innerIAsyncResult);
            }, 123);

            iar.AsyncWaitHandle.WaitOne();

            System.Console.WriteLine("Response: " + response.GetResponseText());
            // Should fail before getting to server

            //request = new GSRequest(apiKey, secretKey+"123", method, false);
            //request.SetParam("uid", "di1");
            //request.SetParam("enabledProviders", "*,testnetwork,testnetwork2");

            //response = null;
            //iar = request.BeginSend((IAsyncResult innerIAsyncResult) => {
            //    response = request.EndSend(innerIAsyncResult);
            //}, 123);

            //iar.AsyncWaitHandle.WaitOne();
        }
Example #2
0
        static void TestGetUserInfo(string[] args)
        {
            // Step 1 - Defining the request
            string    method  = "socialize.getUserInfo";
            GSRequest request = new GSRequest(apiKey, secretKey, method, true);

            // Step 2 - Adding parameters
            request.SetParam("uid", "di1");                   // set the "uid" parameter to user's ID
            request.SetParam("enabledProviders", "*,testnetwork,testnetwork2");
            request.SetParam("status", "I feel great 22222"); // set the "status" parameter to "I feel great"

            // Step 3 - Sending the request
            GSResponse response = request.Send();

            bool validate = SigUtils.ValidateUserSignature(
                response.GetString("UID", ""),
                response.GetString("signatureTimestamp", ""), secretKey,
                response.GetString("UIDSignature", ""));

            // Step 4 - handling the request's response.
            if (response.GetErrorCode() == 0)
            {    // SUCCESS! response status = OK
                Console.WriteLine("Success in setStatus operation.");
            }
            else
            {  // Error
                Console.WriteLine("Got error on setStatus: {0}", response.GetErrorMessage());
            }
        }
Example #3
0
 public static HttpCookie buildCookie(GSResponse res)
 {
     HttpCookie cookie = new HttpCookie(res.GetString("cookieName", string.Empty));
     cookie.Domain = res.GetString("cookieDomain", string.Empty);
     cookie.Path = res.GetString("cookiePath", string.Empty);
     cookie.Value = res.GetString("cookieValue", string.Empty);
     //cookie.Expires = DateTime.MinValue;
     //cookie.HttpOnly = true;
     return cookie;
 }
Example #4
0
 public static void setCookie(GSResponse res, ControllerContext context)
 {
     HttpCookie cookie = new HttpCookie(res.GetString("cookieName", string.Empty));
     //cookie.Domain = res.GetString("cookieDomain", string.Empty);
     //cookie.Path = res.GetString("cookiePath", string.Empty);
     cookie.Value = res.GetString("cookieValue", string.Empty);
     //cookie.Expires = DateTime.MinValue;
     cookie.Expires = DateTime.Now.AddDays(30);
     //cookie.HttpOnly = true;
     context.HttpContext.Response.Cookies.Add(cookie);
 }
Example #5
0
 public void ResponseWithError()
 {
     try
     {
         var r = GSResponse.ResponseWithError(new NSError(new NSString("123"), 1));
     }
     catch (Exception e)
     {
         Assert.Fail(e.Message);
     }
     Assert.Pass();
 }
        private GSResponse LogError(GSResponse response, string method, Exception e)
        {
            dynamic gigyaModel = response != null?JsonConvert.DeserializeObject <ExpandoObject>(response.GetResponseText()) : new ExpandoObject();

            var gigyaError = response != null?response.GetErrorMessage() : string.Empty;

            var gigyaErrorDetail = DynamicUtils.GetValue <string>(gigyaModel, "errorDetails");
            var gigyaCallId      = DynamicUtils.GetValue <string>(gigyaModel, "callId");

            _logger.Error(string.Format("API call: {0}. CallId: {1}. Error: {2}. Error Details: {3}.", method, gigyaCallId, gigyaError, gigyaErrorDetail), e);
            return(response);
        }
Example #7
0
 public void ResponseForMethod()
 {
     try
     {
         var r = GSResponse.ResponseForMethod("method", new NSData());
     }
     catch (Exception e)
     {
         Assert.Fail(e.Message);
     }
     Assert.Pass();
 }
Example #8
0
        private void verifyResponseSignature(GSResponse res, string format)
        {
            if (!format.Equals("xml", StringComparison.InvariantCultureIgnoreCase))
            {
                GSObject data = res.GetData();
                if (null != data)
                {
                    if (cbMethods.Text.IndexOf("getUserInfo", StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        string uid          = data.GetString("UID", "");
                        string uidSig       = data.GetString("UIDSignature", "");
                        string sigTimestamp = data.GetString("signatureTimestamp", "");
                        if (SigUtils.ValidateUserSignature(uid, sigTimestamp, txtSecKey.Text, uidSig))
                        {
                            lblVerifiedSig.Text      = "Signature is verified";
                            lblVerifiedSig.ForeColor = Color.Green;
                        }
                        else
                        {
                            lblVerifiedSig.Text      = "Invalid signature !!!";
                            lblVerifiedSig.ForeColor = Color.Red;
                        }
                    }


                    if (cbMethods.Text.IndexOf("getFriendsInfo", StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        GSArray friends = data.GetArray("friends");
                        if (null != friends && friends.Length > 0)
                        {
                            GSObject firstFriend = friends.GetObject(0);
                            string   friendSig   = firstFriend.GetString("friendshipSignature");
                            string   tsSig       = firstFriend.GetString("signatureTimestamp");
                            string   friendUID   = firstFriend.GetString("UID");
                            if (SigUtils.ValidateFriendSignature(txtUID.Text, tsSig, friendUID, txtSecKey.Text, friendSig))
                            {
                                lblVerifiedSig.Text      = "1ST friend's signature is verified";
                                lblVerifiedSig.ForeColor = Color.Green;
                            }
                            else
                            {
                                lblVerifiedSig.Text      = "Invalid signature (1ST friend's) !!!";
                                lblVerifiedSig.ForeColor = Color.Red;
                            }
                        }
                    }
                }
            }
        }
Example #9
0
        public async Task <bool> Login(string password)
        {
            // Step 1 - Defining the request
            GSRequest request = getGigyaRequest("accounts.login");



            // Step 2 - Adding parameters
            request.SetParam("loginID", Email);     // set the "uid" parameter to user's ID
            request.SetParam("password", password); // set the "status" parameter to "I feel great"

            // Step 3 - Sending the request
            GSResponse response = await Task <GSResponse> .Factory.FromAsync(request.BeginSend, request.EndSend, TaskCreationOptions.None);

            return(response.GetErrorCode() == 0);
        }
Example #10
0
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            Settings.Default.Save();

            string format;

            try {
                lblVerifiedSig.ForeColor = Color.Blue;
                btnSubmit.Text           = "Loading...";
                btnSubmit.Enabled        = false;
                string methodName = cbMethods.Text;
                verifySignature = false;
                if (!string.IsNullOrEmpty(methodName))
                {
                    const string socializeDot = "socialize.";
                    if (!methodName.StartsWith(socializeDot, StringComparison.InvariantCultureIgnoreCase))
                    {
                        methodName = socializeDot + methodName;
                    }

                    if (methodName.IndexOf("getUserInfo", StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        verifySignature = true;
                    }
                    else if (methodName.IndexOf("getFriendsInfo", StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        verifySignature = true;
                    }
                }

                lblVerifiedSig.Text = "Please wait...";
                webBrowser1.Hide();
                this.Refresh();
                GSResponse res = _helper.Send(txtUID.Text, txtAPIKey.Text, txtSecKey.Text, methodName, txtQS.Text, chkHTTPS.Checked, txtApiDomain.Text, out format);
                HandleGSResponse(res, format);
            }
            catch (Exception ex) {
                //raise error.
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnSubmit.Text           = "Submit";
                lblVerifiedSig.Text      = "  <-- Please select a method";
                lblVerifiedSig.ForeColor = Color.Blue;
                btnSubmit.Enabled        = true;
            }
        }
Example #11
0
        private static void GetUserInfoTester()
        {
            GetUserInfoRequestParams reqParams = new GetUserInfoRequestParams
            {
                uid = "31x31",
                enabledProviders = "*,testnetwork,testnetwork2"
            };


            // Typed Class
            GSRequest  req = new GSRequest(apiKey, secretKey, "socialize.getUserInfo", reqParams, false);
            GSResponse res = req.Send();

            GigyaResponse response = res.GetData <GigyaResponse>();

            Debug.Assert(response.errorCode > 0, "failed to cast to GigyaResponse #1");

            // GS Object
            req = new GSRequest(apiKey, secretKey, "socialize.getUserInfo", new GSObject(reqParams), false);
            res = req.Send();

            response = res.GetData <GigyaResponse>();
            Debug.Assert(response.errorCode > 0, "failed to cast to GigyaResponse #2");

            // Anonymous type
            req = new GSRequest(apiKey, secretKey, "socialize.getUserInfo", new
            {
                format = "json",
                uid    = "31x31",
                arr    = new List <string> {
                    "1", "2", "3"
                },
                myClass     = new MyClass(),
                myClassList = new List <MyClass> {
                    new MyClass()
                },
                enabledProviders = "*,testnetwork,testnetwork2"
            }, false);

            res = req.Send();

            // Cast to GigyaResponse
            response = res.GetData <GigyaResponse>();
            Debug.Assert(response.errorCode > 0, "failed to cast to GigyaResponse #3");
        }
Example #12
0
        /// <summary>
        /// Fetch available public key representation validated by the "kid".
        /// </summary>
        /// <param name="kid">The keyId</param>
        /// <param name="apiDomain">The api domain jwt was obtained, for example us1.gigya.com</param>
        internal static string FetchPublicKey(string kid, string apiDomain)
        {
            var resourceUri = $"https://accounts.{apiDomain}/accounts.getJWTPublicKey?V2=true";
            var request     = (HttpWebRequest)WebRequest.Create(resourceUri);

            request.Timeout = 30_000;
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.Method    = "GET";
            request.KeepAlive = false;
            request.ServicePoint.Expect100Continue = false;

            GSResponse response;

            using (var webResponse = (HttpWebResponse)request.GetResponse())
                using (var sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                    response = new GSResponse(method: request.Method, responseText: sr.ReadToEnd(), logSoFar: null);

            if (response.GetErrorCode() == 0)
            {
                GSArray keys = response.GetArray("keys", null);

                if (keys == null || keys.Length == 0)
                {
                    return(null); // Failed to obtain JWK from response data OR data is empty
                }
                foreach (object key in keys)
                {
                    if (key is GSObject)
                    {
                        string jwtKid = ((GSObject)key).GetString("kid", null);
                        if (jwtKid != null && jwtKid == kid)
                        {
                            return(((GSObject)key).ToJsonString());
                        }
                    }
                }
            }

            return(null);
        }
Example #13
0
        private void HandleGSResponse(GSResponse res, string format)
        {
            lblVerifiedSig.Text = "";
            if (!format.Equals("xml", StringComparison.InvariantCultureIgnoreCase))
            {
                format = "txt";
            }

            var filename = Path.Combine(Path.GetTempPath(), "1." + format);

            try {
                if (res.GetErrorCode() > 0)
                {
                    lblVerifiedSig.ForeColor = Color.Red;
                    lblVerifiedSig.Text      = "Error !!!";
                    File.WriteAllText(filename, res.ToString());
                }
                else
                {
                    if (verifySignature)
                    {
                        verifyResponseSignature(res, format);
                    }
                    else
                    {
                        lblVerifiedSig.Text = "Data is ready";
                    }
                    File.WriteAllText(filename, res.GetResponseText());
                }
                webBrowser1.Navigate(filename);
                webBrowser1.Show();
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            btnSubmit.Text    = "Submit";
            btnSubmit.Enabled = true;
        }
Example #14
0
        public async Task <bool> Register(string password)
        {
            // Step 1 - Defining the request

            GSRequest initRequest = getGigyaRequest("accounts.initRegistration");

            GSResponse initResponse = await Task <GSResponse> .Factory.FromAsync(initRequest.BeginSend, initRequest.EndSend, TaskCreationOptions.None);

            if (initResponse.GetErrorCode() != 0)
            {
                return(false);
            }

            string regToken = initResponse.GetString("regToken", null);

            GSRequest regRequest = getGigyaRequest("accounts.register");

            // Step 2 - Adding parameters
            //regRequest.SetParam("username", Email);
            regRequest.SetParam("email", Email); // set the "uid" parameter to user's ID
            regRequest.SetParam("password", password);
            regRequest.SetParam("regToken", regToken);
            regRequest.SetParam("finalizeRegistration", true);

            // Step 3 - Sending the request
            GSResponse regresponse = await Task <GSResponse> .Factory.FromAsync(regRequest.BeginSend, regRequest.EndSend, TaskCreationOptions.None);


            // Step 4 - handling the request's response.
            if (regresponse.GetErrorCode() == 0)
            { // SUCCESS! response status = OK
                return(true);
            }
            else
            { // Error
                return(false);
            }
        }
        private GSResponse Send(GSRequest request, string apiMethod, GigyaModuleSettings settings)
        {
            GSResponse response = null;

            try
            {
                response = request.Send();
            }
            catch (Exception e)
            {
                return(LogError(response, apiMethod, e));
            }

            GigyaApiHelper.LogResponseIfRequired(_logger, settings, apiMethod, response);

            if (response.GetErrorCode() != 0)
            {
                LogError(response, apiMethod, null);
                return(null);
            }

            return(response);
        }
        private void PublishGigyaActions(User user, GSResponse res)
        {
            GigyaHelpers.setCookie(res, this.ControllerContext);
            GigyaUserData userData = new GigyaUserData()
            {
                City = user.City,
                CountryCode = user.CountryCode,
                Email = user.EMail,
                FirstName = user.FirstName,
                LastName = user.LastName,
                State = user.State
            };
            GigyaUserDataInfo userDataInfo = new GigyaUserDataInfo()
            {
                UID = user.UserId.ToString(),
                data = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Newtonsoft.Json.Formatting.None)
            };
            GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo));
            //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj);
            res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj);
            var returnCode = res.GetErrorCode();

            //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, user.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");

        }
Example #17
0
 private bool ValidateExchangeSignatureResponse(GSResponse response)
 {
     // if signature is invalid a null response is returned
     return(response != null && response.GetErrorCode() == 0 && !string.IsNullOrEmpty(response.GetString(Constants.GigyaFields.UserId, null)));
 }
Example #18
0
        /// <summary>
        /// Validates an application key signatures by calling accounts.exchangeUIDSignature and checking the response signature.
        /// </summary>
        public bool ValidateApplicationKeySignature(string userId, IGigyaModuleSettings settings, GSResponse originalResponse)
        {
            // this uses the Send method which validates the signature
            var response = ExchangeSignature(userId, settings, originalResponse.GetString(Constants.GigyaFields.UserIdSignature, null),
                                             originalResponse.GetString(Constants.GigyaFields.SignatureTimestamp, null), settings.ApplicationKey);

            return(ValidateExchangeSignatureResponse(response));
        }
Example #19
0
        public static void LogResponseIfRequired(Logger logger, IGigyaModuleSettings settings, string apiMethod, GSResponse response)
        {
            if (settings.DebugMode)
            {
                dynamic gigyaModel = response != null?JsonConvert.DeserializeObject <ExpandoObject>(response.GetResponseText()) : new ExpandoObject();

                var gigyaError = response != null?response.GetErrorMessage() : string.Empty;

                var gigyaErrorDetail = DynamicUtils.GetValue <string>(gigyaModel, "errorDetails");

                var callId = DynamicUtils.GetValue <string>(gigyaModel, "callId");
                logger.DebugFormat("API call: {0}. CallId: {1}. Error: {2}. Error Details: {3}.", apiMethod, callId, gigyaError, gigyaErrorDetail);
            }
        }
Example #20
0
 private void LogResponseIfRequired(IGigyaModuleSettings settings, string apiMethod, GSResponse response)
 {
     LogResponseIfRequired(_logger, settings, apiMethod, response);
 }
Example #21
0
        /// <summary>
        /// Sends a request to the Gigya API.
        /// </summary>
        /// <param name="request">Request object.</param>
        /// <param name="apiMethod">The Gigya method to call.</param>
        /// <param name="settings">The Gigya module settings.</param>
        /// <param name="validateSignature">If set to true, the signature will be validated.</param>
        /// <returns></returns>
        private GSResponse Send(GSRequest request, string apiMethod, IGigyaModuleSettings settings, bool validateSignature)
        {
            if (apiMethod == "accounts.getAccountInfo")
            {
                var environment = new
                {
                    cms_name      = _settingsHelper.CmsName,
                    cms_version   = _settingsHelper.CmsVersion,
                    gigya_version = _settingsHelper.ModuleVersion
                };

                request.SetParam("environment", JsonConvert.SerializeObject(environment));
            }

            if (!string.IsNullOrEmpty(settings.DataCenter))
            {
                request.APIDomain = settings.DataCenter;
            }

            LogRequestIfRequired(settings, apiMethod);

            GSResponse response = null;

            try
            {
                response = request.Send();
            }
            catch (Exception e)
            {
                dynamic gigyaModel = response != null?JsonConvert.DeserializeObject <ExpandoObject>(response.GetResponseText()) : new ExpandoObject();

                var gigyaError = response != null?response.GetErrorMessage() : string.Empty;

                var gigyaErrorDetail = DynamicUtils.GetValue <string>(gigyaModel, "errorDetails");
                var gigyaCallId      = DynamicUtils.GetValue <string>(gigyaModel, "callId");

                _logger.Error(string.Format("API call: {0}. CallId: {1}. Error: {2}. Error Details: {3}.", apiMethod, gigyaCallId, gigyaError, gigyaErrorDetail), e);
                return(response);
            }

            LogResponseIfRequired(settings, apiMethod, response);

            if (response.GetErrorCode() != 0)
            {
                return(response);
            }

            var userId = response.GetString(Constants.GigyaFields.UserId, null);

            if (string.IsNullOrEmpty(userId))
            {
                return(response);
            }

            // no need to validate server calls unless explicitly required e.g. for signature exchange
            if (validateSignature && !ValidateSignature(userId, settings, response))
            {
                if (settings.DebugMode)
                {
                    dynamic gigyaModel = response != null?JsonConvert.DeserializeObject <ExpandoObject>(response.GetResponseText()) : new ExpandoObject();

                    var gigyaCallId = DynamicUtils.GetValue <string>(gigyaModel, "callId");

                    _logger.DebugFormat("Invalid user signature for login request. API call: {0}. CallId: {1}.", apiMethod, gigyaCallId);
                }
                return(null);
            }

            return(response);
        }
Example #22
0
 public bool ValidateSignature(string userId, IGigyaModuleSettings settings, GSResponse response, bool disableSignatureExchange = false)
 {
     return(SigUtils.ValidateUserSignature(userId, response.GetString(Constants.GigyaFields.SignatureTimestamp, null),
                                           settings.ApplicationSecret, response.GetString(Constants.GigyaFields.UserIdSignature, null)));
 }
Example #23
0
 void ResponseHandler(GSResponse arg0, NSError arg1)
 {
 }
Example #24
0
        protected ExpandoObject GetAccountInfo(object currentSiteId, IGigyaModuleSettings settings, GSResponse userInfoResponse, List <MappingField> mappingFields)
        {
            var userInfo = JsonConvert.DeserializeObject <ExpandoObject>(userInfoResponse.GetResponseText());

            ThrowTestingExceptionIfRequired(settings, userInfo);

            var siteId = ConvertCurrentSiteId(currentSiteId);

            // fire getAccountInfo completed event
            var getAccountInfoCompletedArgs = new GetAccountInfoCompletedEventArgs
            {
                GigyaModel    = userInfo,
                Settings      = settings,
                Logger        = _logger,
                MappingFields = mappingFields,
                CurrentSiteId = siteId
            };

            GigyaEventHub.Instance.RaiseGetAccountInfoCompleted(this, getAccountInfoCompletedArgs);

            // fire merge getAccountInfo completed event
            var accountInfoMergeCompletedArgs = new AccountInfoMergeCompletedEventArgs
            {
                GigyaModel    = getAccountInfoCompletedArgs.GigyaModel,
                Settings      = settings,
                Logger        = _logger,
                CurrentSiteId = siteId
            };

            GigyaEventHub.Instance.RaiseAccountInfoMergeCompleted(this, accountInfoMergeCompletedArgs);
            return(accountInfoMergeCompletedArgs.GigyaModel);
        }
Example #25
0
 public void OnGSResponse(string method, GSResponse response, Java.Lang.Object context)
 {
     tcs.SetResult(response);
 }
 void IGSUIListener.OnError(GSResponse response, Java.Lang.Object context)
 {
     Console.WriteLine("Gigya loginUI had an error - " + response.ErrorMessage);
 }
Example #27
0
 void Method(GSResponse arg0, NSError arg1)
 {
 }
Example #28
0
 void ResponseHandler(GSResponse arg0, NSError arg1)
 {
 }
Example #29
0
 void Method(GSResponse arg0, NSError arg1)
 {
 }