public override Task OnAuthorizeAccount() { //Here we go through the OAuth 1.0a sign-in flow // 1.) Request a token from Twitter // 2.) Have the user authorize NinjaTrader to post on their behalf // 3.) Recieve the authorization token that allows us to actually post on their behalf #region Twitter Request Token string oauth_request_token_url = "https://api.twitter.com/oauth/request_token"; string oauth_callback = "http://www.ninjatrader.com"; string oauth_timestamp = Convert.ToInt64((TimeZoneInfo.ConvertTime(Core.Globals.Now, Core.Globals.GeneralOptions.TimeZoneInfo, TimeZoneInfo.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture); string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(Core.Globals.Now.Ticks.ToString())); string oauth_signature_method = "HMAC-SHA1"; string oauth_version = "1.0"; OrderedDictionary sigParameters = new OrderedDictionary { { "oauth_callback=", Core.Globals.UrlEncode(oauth_callback) + "&" }, { "oauth_consumer_key=", Core.Globals.UrlEncode(oauth_consumer_key) + "&" }, { "oauth_nonce=", Core.Globals.UrlEncode(oauth_nonce) + "&" }, { "oauth_signature_method=", Core.Globals.UrlEncode(oauth_signature_method) + "&" }, { "oauth_timestamp=", Core.Globals.UrlEncode(oauth_timestamp) + "&" }, { "oauth_version=", Core.Globals.UrlEncode(oauth_version) } }; string oauth_signature = Core.Globals.GetTwitterSignature(oauth_request_token_url, "POST", sigParameters); string header = "OAuth" + " " + "oauth_callback=\"" + Core.Globals.UrlEncode(oauth_callback) + "\"," + "oauth_consumer_key=\"" + Core.Globals.UrlEncode(oauth_consumer_key) + "\"," + "oauth_nonce=\"" + Core.Globals.UrlEncode(oauth_nonce) + "\"," + "oauth_signature_method=\"" + Core.Globals.UrlEncode(oauth_signature_method) + "\"," + "oauth_timestamp=\"" + Core.Globals.UrlEncode(oauth_timestamp) + "\"," + "oauth_version=\"" + Core.Globals.UrlEncode(oauth_version) + "\"," + "oauth_signature=\"" + Core.Globals.UrlEncode(oauth_signature) + "\""; string result = string.Empty; try { HttpWebRequest r = (HttpWebRequest)WebRequest.Create(oauth_request_token_url); r.Method = "POST"; r.ContentLength = 0; r.ContentType = "application/x-www-form-urlencoded"; r.ServicePoint.Expect100Continue = false; r.Headers.Add("Authorization", header); using (HttpWebResponse s = (HttpWebResponse)r.GetResponse()) using (StreamReader reader = new StreamReader(s.GetResponseStream())) result = reader.ReadToEnd(); } catch (WebException ex) { string message = string.Empty; using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream())) message = reader.ReadToEnd(); IsConfigured = false; SetState(State.Finalized); return(Task.FromResult(0)); } string oauth_token = string.Empty; string oauth_token_secret = string.Empty; string oauth_verifier = string.Empty; if (!string.IsNullOrEmpty(result)) { string[] pairs = result.Split('&'); foreach (string pair in pairs) { string[] keyvalue = pair.Split('='); if (keyvalue[0] == "oauth_token") { oauth_token = keyvalue[1]; } else if (keyvalue[0] == "oauth_token_secret") { oauth_token_secret = keyvalue[1]; } } } #endregion #region Twitter Authorize //We're going to display a webpage in an NTWindow so the user can authorize our app to post on their behalf. //Because of WPF/WinForm airspace issues (see http://msdn.microsoft.com/en-us/library/aa970688.aspx for the gory details), // and because we want to have our pretty NT-styled windows, we need to finagle things a bit. // 1.) Create a modal NTWindow that will pop up when the user clicks "Connect" // 2.) Create a borderless window that will actually host the WebBrowser control // 3.) A window can have one Content object, so add a grid to the Window hosting the WebBrowser, and make the WeBrowser a child of the grid // 4.) Add another grid to the modal NTWindow. We'll use this to place where the WebBrowser goes // 5.) Handle the LocationChanged event for the NTWindow and the SizeChanged event for the placement grid. This will take care of making // the hosted WebBrowser control look like it's part of the NTWindow // 6.) Make sure the Window hosting the WebBrowser is set to be TopMost so it appears on top of the NTWindow. NTWindow authWin = new NTWindow() { Caption = Custom.Resource.GuiAuthorize, IsModal = true, Height = 750, Width = 800, }; Window webHost = new Window() { ResizeMode = System.Windows.ResizeMode.NoResize, ShowInTaskbar = false, WindowStyle = System.Windows.WindowStyle.None, }; WebBrowser browser = new WebBrowser() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch, }; Grid grid = new Grid(); grid.Children.Add(browser); webHost.Content = grid; Grid placementGrid = new Grid(); authWin.Content = placementGrid; authWin.LocationChanged += (o, e) => OnSizeLocationChanged(placementGrid, webHost); placementGrid.SizeChanged += (o, e) => OnSizeLocationChanged(placementGrid, webHost); browser.Navigating += (o, e) => { if (e.Uri.Host == "www.ninjatrader.com") { if (e.Uri.Query.StartsWith("?oauth_token")) { //Successfully authorized! :D string query = e.Uri.Query.TrimStart('?'); string[] pairs = query.Split('&'); foreach (string pair in pairs) { string[] keyvalue = pair.Split('='); if (keyvalue[0] == "oauth_token") { oauth_token = keyvalue[1]; } else if (keyvalue[0] == "oauth_verifier") { oauth_verifier = keyvalue[1]; } } authWin.DialogResult = true; authWin.Close(); } else if (e.Uri.Query.StartsWith("?denied")) { //User denied authorization :'( authWin.DialogResult = false; authWin.Close(); } } }; authWin.Closing += (o, e) => webHost.Close(); browser.Navigate(new Uri("https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token)); webHost.Visibility = System.Windows.Visibility.Visible; webHost.Topmost = true; authWin.ShowDialog(); #endregion #region Twitter Access Token if (authWin.DialogResult == true) { string oauth_access_token_url = "https://api.twitter.com/oauth/access_token"; oauth_timestamp = Convert.ToInt64((TimeZoneInfo.ConvertTime(Core.Globals.Now, Core.Globals.GeneralOptions.TimeZoneInfo, TimeZoneInfo.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture); oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(Core.Globals.Now.Ticks.ToString())); sigParameters.Clear(); sigParameters.Add("oauth_consumer_key=", Core.Globals.UrlEncode(oauth_consumer_key) + "&"); sigParameters.Add("oauth_nonce=", Core.Globals.UrlEncode(oauth_nonce) + "&"); sigParameters.Add("oauth_signature_method=", Core.Globals.UrlEncode(oauth_signature_method) + "&"); sigParameters.Add("oauth_timestamp=", Core.Globals.UrlEncode(oauth_timestamp) + "&"); sigParameters.Add("oauth_token=", Core.Globals.UrlEncode(oauth_token) + "&"); sigParameters.Add("oauth_verifier=", Core.Globals.UrlEncode(oauth_verifier) + "&"); sigParameters.Add("oauth_version=", Core.Globals.UrlEncode(oauth_version)); oauth_signature = Core.Globals.GetTwitterSignature(oauth_access_token_url, "POST", sigParameters); header = "OAuth" + " " + "oauth_consumer_key=\"" + Core.Globals.UrlEncode(oauth_consumer_key) + "\"," + "oauth_nonce=\"" + Core.Globals.UrlEncode(oauth_nonce) + "\"," + "oauth_signature_method=\"" + Core.Globals.UrlEncode(oauth_signature_method) + "\"," + "oauth_timestamp=\"" + Core.Globals.UrlEncode(oauth_timestamp) + "\"," + "oauth_token=\"" + Core.Globals.UrlEncode(oauth_token) + "\"," + "oauth_verifier=\"" + Core.Globals.UrlEncode(oauth_verifier) + "\"," + "oauth_version=\"" + Core.Globals.UrlEncode(oauth_version) + "\"," + "oauth_signature=\"" + Core.Globals.UrlEncode(oauth_signature) + "\""; try { HttpWebRequest r = (HttpWebRequest)WebRequest.Create(oauth_access_token_url + "?oauth_verifier=" + Core.Globals.UrlEncode(oauth_verifier)); r.Method = "POST"; r.ContentLength = 0; r.ContentType = "application/x-www-form-urlencoded"; r.ServicePoint.Expect100Continue = false; r.Headers.Add("Authorization", header); using (HttpWebResponse s = (HttpWebResponse)r.GetResponse()) using (StreamReader reader = new StreamReader(s.GetResponseStream())) result = reader.ReadToEnd(); if (!string.IsNullOrEmpty(result)) { string[] pairs = result.Split('&'); foreach (string pair in pairs) { string[] keyvalue = pair.Split('='); if (keyvalue[0] == "oauth_token") { OAuth_Token = keyvalue[1]; } else if (keyvalue[0] == "oauth_token_secret") { OAuth_Token_Secret = keyvalue[1]; } else if (keyvalue[0] == "screen_name") { UserName = keyvalue[1]; } } } } catch (WebException ex) { string message = string.Empty; using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream())) message = reader.ReadToEnd(); IsConfigured = false; SetState(State.Finalized); return(Task.FromResult(0)); } IsConfigured = !string.IsNullOrEmpty(OAuth_Token) && !string.IsNullOrEmpty(OAuth_Token_Secret) && !string.IsNullOrEmpty(UserName); } else { IsConfigured = false; } #endregion return(Task.FromResult(0)); }
public override Task OnAuthorizeAccount() { //Here we go through the OAuth 2.0 sign-in flow #region StockTwits Login Dialog string oauth_request_token_url = "https://api.stocktwits.com/api/2/oauth/authorize"; string oauth_consumer_key = "5cd7b6bdb6575757"; string oauth_callback = "http://www.ninjatrader.com"; //We're going to display a webpage in an NTWindow so the user can authorize our app to post on their behalf. //Because of WPF/WinForm airspace issues (see http://msdn.microsoft.com/en-us/library/aa970688.aspx for the gory details), // and because we want to have our pretty NT-styled windows, we need to finagle things a bit. // 1.) Create a modal NTWindow that will pop up when the user clicks "Connect" // 2.) Create a borderless window that will actually host the WebBrowser control // 3.) A window can have one Content object, so add a grid to the Window hosting the WebBrowser, and make the WeBrowser a child of the grid // 4.) Add another grid to the modal NTWindow. We'll use this to place where the WebBrowser goes // 5.) Handle the LocationChanged event for the NTWindow and the SizeChanged event for the placement grid. This will take care of making // the hosted WebBrowser control look like it's part of the NTWindow // 6.) Make sure the Window hosting the WebBrowser is set to be TopMost so it appears on top of the NTWindow. NTWindow authWin = new NTWindow() { Caption = Custom.Resource.GuiAuthorize, IsModal = true, Height = 650, Width = 900, }; Window webHost = new Window() { ResizeMode = ResizeMode.NoResize, ShowInTaskbar = false, WindowStyle = WindowStyle.None, }; WebBrowser browser = new WebBrowser() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, }; Grid grid = new Grid(); grid.Children.Add(browser); webHost.Content = grid; Grid placementGrid = new Grid(); authWin.Content = placementGrid; authWin.LocationChanged += (o, e) => OnSizeLocationChanged(placementGrid, webHost); placementGrid.SizeChanged += (o, e) => OnSizeLocationChanged(placementGrid, webHost); string oauth_token = string.Empty; HideScriptErrors(browser); browser.Navigating += async(o, e) => { if (e.Uri.Host == "www.ninjatrader.com") { if (e.Uri.Fragment.StartsWith("#access_token")) { //Successfully authorized! :D string query = e.Uri.Fragment.TrimStart('#'); string[] pairs = query.Split('&'); foreach (string pair in pairs) { string[] keyvalue = pair.Split('='); if (keyvalue[0] == "access_token") { oauth_token = keyvalue[1]; } } OAuth_Token = oauth_token; // Verify the user's account so we can display the UserName string accountVerifyUri = string.Format("{0}{1}", "https://api.stocktwits.com/api/2/account/verify.json?access_token=", OAuth_Token); using (HttpClient client = new HttpClient()) { HttpResponseMessage verifyResponse = await client.GetAsync(accountVerifyUri); string result = new StreamReader(verifyResponse.Content.ReadAsStreamAsync().Result).ReadToEnd(); Dictionary <string, object> results = new JavaScriptSerializer().DeserializeObject(result) as Dictionary <string, object>; if (results == null) { LogAndPrint(typeof(Custom.Resource), "ShareStockTwitsNoAccount", null, Cbi.LogLevel.Error); authWin.DialogResult = false; authWin.Close(); return; } object userinfo; if (results.TryGetValue("user", out userinfo)) { Dictionary <string, object> user = userinfo as Dictionary <string, object>; if (user != null) { object username; if (user.TryGetValue("username", out username)) { UserName = username as string; } else { LogAndPrint(typeof(Custom.Resource), "ShareStockTwitsNoAccount", null, Cbi.LogLevel.Error); authWin.DialogResult = false; authWin.Close(); return; } } else { LogAndPrint(typeof(Custom.Resource), "ShareStockTwitsNoAccount", null, Cbi.LogLevel.Error); authWin.DialogResult = false; authWin.Close(); return; } } else { LogAndPrint(typeof(Custom.Resource), "ShareStockTwitsNoAccount", null, Cbi.LogLevel.Error); authWin.DialogResult = false; authWin.Close(); return; } } authWin.DialogResult = true; } else if (e.Uri.Fragment.StartsWith("#error")) { //User denied authorization :'( authWin.DialogResult = false; } authWin.Close(); } }; authWin.Closing += (o, e) => webHost.Close(); string navigationUri = oauth_request_token_url + "?client_id=" + oauth_consumer_key + "&" + "redirect_uri=" + oauth_callback + "&" + "response_type=" + "token" + "&" + "scope=" + "publish_messages"; browser.Navigate(new Uri(navigationUri)); webHost.Visibility = Visibility.Visible; webHost.Topmost = true; authWin.ShowDialog(); if (authWin.DialogResult != true || string.IsNullOrEmpty(OAuth_Token) || string.IsNullOrEmpty(UserName)) { return(Task.FromResult(0)); } #endregion IsConfigured = true; return(Task.FromResult(0)); }
public async override Task OnAuthorizeAccount() { //Here we go through the OAuth 2.0 sign in flow #region Facebook Invoke Login Dialog const string oauth_request_token_url = "https://www.facebook.com/dialog/oauth?"; const string oauth_app_id = "895600370523827"; const string oauth_callback = "https://www.facebook.com/connect/login_success.html"; const string navigationUri = oauth_request_token_url + "client_id=" + oauth_app_id + "&" + "redirect_uri=" + oauth_callback + "&" + "response_type=" + "token" + "&" + "scope=" + "publish_actions"; //We're going to display a webpage in an NTWindow so the user can authorize our app to post on their behalf. //Because of WPF/WinForm airspace issues (see http://msdn.microsoft.com/en-us/library/aa970688.aspx for the gory details), // and because we want to have our pretty NT-styled windows, we need to finagle things a bit. // 1.) Create a modal NTWindow that will pop up when the user clicks "Connect" // 2.) Create a borderless window that will actually host the WebBrowser control // 3.) A window can have one Content object, so add a grid to the Window hosting the WebBrowser, and make the WeBrowser a child of the grid // 4.) Add another grid to the modal NTWindow. We'll use this to place where the WebBrowser goes // 5.) Handle the LocationChanged event for the NTWindow and the SizeChanged event for the placement grid. This will take care of making // the hosted WebBrowser control look like it's part of the NTWindow // 6.) Make sure the Window hosting the WebBrowser is set to be TopMost so it appears on top of the NTWindow. NTWindow authWin = new NTWindow { Caption = Custom.Resource.GuiAuthorize, IsModal = true, Height = 650, Width = 900, }; Window webHost = new Window { ResizeMode = ResizeMode.NoResize, ShowInTaskbar = false, WindowStyle = WindowStyle.None, }; WebBrowser browser = new WebBrowser { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, }; Grid grid = new Grid(); grid.Children.Add(browser); webHost.Content = grid; Grid placementGrid = new Grid(); authWin.Content = placementGrid; authWin.LocationChanged += (o, e) => OnSizeLocationChanged(placementGrid, webHost); placementGrid.SizeChanged += (o, e) => OnSizeLocationChanged(placementGrid, webHost); string oauth_token = string.Empty; browser.Navigating += (o, e) => { if (e.Uri.Host == "www.facebook.com") { if (e.Uri.Fragment.StartsWith("#access_token")) { //Successfully authorized! :D string query = e.Uri.Fragment.TrimStart('#'); string[] pairs = query.Split('&'); foreach (string pair in pairs) { string[] keyvalue = pair.Split('='); if (keyvalue[0] == "access_token") { oauth_token = keyvalue[1]; } } authWin.DialogResult = true; OAuth_Token = oauth_token; authWin.Close(); } else if (e.Uri.Query.StartsWith("?error")) { //User denied authorization :'( authWin.DialogResult = false; authWin.Close(); } } }; authWin.Closing += (o, e) => webHost.Close(); browser.Navigate(new Uri(navigationUri)); webHost.Visibility = Visibility.Visible; webHost.Topmost = true; authWin.ShowDialog(); if (authWin.DialogResult != true) { return; } #endregion #region Facebook Authorize string result = await Core.Globals.ExchangeFacebookTokenAsync(oauth_token); if (result.StartsWith("ShareNotAuthorized")) { //If facebook can't or won't authenticate the request, you'll get a 401 response LogAndPrint(typeof(Custom.Resource), "ShareNotAuthorized", new[] { result }, Cbi.LogLevel.Error); return; } else if (result.StartsWith("ShareForbidden")) { LogAndPrint(typeof(Custom.Resource), "ShareForbidden", new[] { result }, Cbi.LogLevel.Error); return; } using (HttpClient client = new HttpClient()) { FacebookAuthJsonResultStub jsonResult = new JavaScriptSerializer().Deserialize <FacebookAuthJsonResultStub>(result); if (jsonResult == null || jsonResult.data == null) { LogAndPrint(typeof(Custom.Resource), "ShareFacebookNoResult", null, Cbi.LogLevel.Error); return; } if (jsonResult.data.scopes == null || jsonResult.data.scopes.Length == 0) { LogAndPrint(typeof(Custom.Resource), "ShareFacebookScopesNotFound", null, Cbi.LogLevel.Error); return; } if (!jsonResult.data.scopes.Contains("publish_actions")) { //User approved our app but forbade us to post on their behalf, so we just return LogAndPrint(typeof(Custom.Resource), "ShareFacebookPermissionDenied", null, Cbi.LogLevel.Error); return; } if (string.IsNullOrEmpty(jsonResult.data.app_id) || jsonResult.data.app_id != oauth_app_id) { LogAndPrint(typeof(Custom.Resource), "ShareFacebookCouldNotVerifyToken", null, Cbi.LogLevel.Error); return; } if (string.IsNullOrEmpty(jsonResult.data.user_id)) { LogAndPrint(typeof(Custom.Resource), "ShareFacebookCouldNotRetrieveUser", null, Cbi.LogLevel.Error); return; } FacebookUserId = jsonResult.data.user_id; //Get user name from userId string nameRequestUrl = "https://graph.facebook.com/" + appVersion + "/" + FacebookUserId + "?fields=name&access_token=" + OAuth_Token; HttpResponseMessage facebookResponse = await client.GetAsync(nameRequestUrl); result = new StreamReader(facebookResponse.Content.ReadAsStreamAsync().Result).ReadToEnd(); if (!facebookResponse.IsSuccessStatusCode) { switch (facebookResponse.StatusCode) { case HttpStatusCode.Unauthorized: //If facebook can't or won't authenticate the request, you'll get a 401 response LogAndPrint(typeof(Custom.Resource), "ShareNotAuthorized", new[] { result }, Cbi.LogLevel.Error); break; case HttpStatusCode.Forbidden: LogAndPrint(typeof(Custom.Resource), "ShareForbidden", new[] { result }, Cbi.LogLevel.Error); break; default: LogAndPrint(typeof(Custom.Resource), "ShareNonSuccessCode", new object[] { facebookResponse.StatusCode, result }, Cbi.LogLevel.Error); break; } return; } if (!string.IsNullOrEmpty(result)) { Dictionary <string, object> nameResults = new JavaScriptSerializer().DeserializeObject(result) as Dictionary <string, object>; if (nameResults != null && nameResults.ContainsKey("name")) { UserName = nameResults["name"] as string; } } if (string.IsNullOrEmpty(UserName)) { LogAndPrint(typeof(Custom.Resource), "ShareFacebookCouldNotRetrieveUser", null, Cbi.LogLevel.Error); return; } } #endregion if (!string.IsNullOrEmpty(OAuth_Token)) { IsConfigured = true; } }