public ITwitterAuthorizer Auth() { var credentials = new InMemoryCredentials { ConsumerKey = this.consumerKey, ConsumerSecret = this.consumerSecret }; if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(oAuthToken)) { credentials.AccessToken = this.accessToken; credentials.OAuthToken = this.oAuthToken; } var auth = new PinAuthorizer { Credentials = credentials, UseCompression = true, GoToTwitterAuthorization = pageLink => Process.Start(pageLink), GetPin = () => { Console.WriteLine("\nAfter you authorize this application, Twitter will give you a 7-digit PIN Number.\n"); Console.Write("Enter the PIN number here: "); return(Console.ReadLine()); } }; auth.Authorize(); return(auth); }
public void Authorize_Gets_Access_Token() { string screenName = "JoeMayo"; string userID = "123"; const string PinCode = "1234567"; const string AuthToken = "token"; const string AuthLink = "https://authorizationlink?oauth_token=" + AuthToken; var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials() }; var oAuthMock = new Mock <IOAuthTwitter>(); oAuthMock.Setup(oAuth => oAuth.AuthorizationLinkGet(It.IsAny <string>(), It.IsAny <string>(), "oob", false, AuthAccessType.NoChange)) .Returns(AuthLink); oAuthMock.Setup(oAuth => oAuth.AccessTokenGet(AuthToken, PinCode, It.IsAny <string>(), string.Empty, out screenName, out userID)); pinAuth.OAuthTwitter = oAuthMock.Object; pinAuth.GetPin = () => PinCode; string destinationUrl = string.Empty; pinAuth.GoToTwitterAuthorization = link => destinationUrl = link; pinAuth.Authorize(); oAuthMock.Verify(oauth => oauth.AccessTokenGet(AuthToken, PinCode, It.IsAny <string>(), string.Empty, out screenName, out userID), Times.Once()); Assert.Equal(screenName, pinAuth.ScreenName); Assert.Equal(userID, pinAuth.UserId); Assert.Equal(AuthLink, destinationUrl); }
static async Task <TwitterContext> GetTwitterContext() { var auth = new PinAuthorizer() { CredentialStore = new InMemoryCredentialStore { ConsumerKey = "", ConsumerSecret = "" }, GoToTwitterAuthorization = pageLink => { var psi = new ProcessStartInfo { FileName = pageLink, UseShellExecute = true }; Process.Start(psi); }, GetPin = () => { Console.WriteLine( "\nAfter authorizing this application, Twitter " + "will give you a 7-digit PIN Number.\n"); Console.Write("Enter the PIN number here: "); return(Console.ReadLine() ?? string.Empty); } }; await auth.AuthorizeAsync(); var twitterCtx = new TwitterContext(auth); return(twitterCtx); }
/** * In this function we firstly load the auth pin authorizer with the application credentials. * We also load the login twitter page in order to obtain the pin. */ void OAuthPage_Loaded(object sender, RoutedEventArgs e) { //Auth definition with our application credentials auth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = Constants.getConsumerKey(), ConsumerSecret = Constants.getConsumerSecret() }, UseCompression = true, //Browser authentication webpage GoToTwitterAuthorization = pageLink => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute))) }; auth.BeginAuthorize(resp => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { switch (resp.Status) { case TwitterErrorStatus.Success: break; case TwitterErrorStatus.RequestProcessingException: case TwitterErrorStatus.TwitterApiError: //new MessageDialog(resp.Error.ToString(), resp.Message).ShowAsync(); break; } })); }
public void BeginAuthorize_Returns_If_Already_Authorized() { var oAuthMock = new Mock <IOAuthTwitter>(); TwitterAsyncResponse <object> twitterResp = null; var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = "consumerkey", ConsumerSecret = "consumersecret", OAuthToken = "oauthtoken", AccessToken = "accesstoken" }, OAuthTwitter = oAuthMock.Object, GetPin = () => "1234567", GoToTwitterAuthorization = link => { } }; pinAuth.BeginAuthorize(resp => twitterResp = resp); oAuthMock.Verify(oauth => oauth.GetRequestTokenAsync(It.IsAny <Uri>(), It.IsAny <Uri>(), "oob", AuthAccessType.NoChange, false, It.IsAny <Action <string> >(), It.IsAny <Action <TwitterAsyncResponse <object> > >()), Times.Never()); Assert.Null(twitterResp); }
public void CompleteAuthorize_Returns_If_Already_Authorized() { const string Pin = "1234567"; Action <TwitterAsyncResponse <UserIdentifier> > callback = resp => { }; var oauthAccessTokenUrl = new Uri("https://api.twitter.com/oauth/access_token"); var oAuthMock = new Mock <IOAuthTwitter>(); var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = "consumerkey", ConsumerSecret = "consumersecret", OAuthToken = "oauthtoken", AccessToken = "accesstoken" }, OAuthTwitter = oAuthMock.Object, GoToTwitterAuthorization = link => { } }; pinAuth.CompleteAuthorize(Pin, callback); oAuthMock.Verify(oAuth => oAuth.GetAccessTokenAsync(Pin, oauthAccessTokenUrl, "oob", AuthAccessType.NoChange, callback), Times.Never()); }
static PinAuthorizer LoadOAuth(string path) { if (!File.Exists(path)) { return(null); } var lines = File.ReadAllLines(path); if (lines.Count() != 2) { return(null); } var auth = new PinAuthorizer(); auth.CredentialStore = new InMemoryCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["consumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"], OAuthToken = lines[0], OAuthTokenSecret = lines[1] }; return(auth); }
static PinAuthorizer Authorize(string path) { var auth = new PinAuthorizer(); auth.CredentialStore = new InMemoryCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["consumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"] }; auth.GoToTwitterAuthorization = pageLink => Process.Start(pageLink); auth.GetPin = () => { Console.WriteLine( "\nAfter authorizing this application, Twitter " + "will give you a 7-digit PIN Number.\n"); Console.Write("Enter the PIN number here: "); return(Console.ReadLine()); }; auth.AuthorizeAsync().Wait(); var lines = new List <string> { auth.CredentialStore.OAuthToken, auth.CredentialStore.OAuthTokenSecret }; File.WriteAllLines(path, lines); return(auth); }
public async Task <bool> Connect() { if (this.token != null) { try { SingleUserAuthorizer singleUserAuth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = TwitterService.ClientID, ConsumerSecret = ChannelSession.SecretManager.GetSecret("TwitterSecret"), AccessToken = this.token.accessToken, AccessTokenSecret = this.token.refreshToken, UserID = ulong.Parse(this.token.clientID), ScreenName = this.token.authorizationCode, } }; await singleUserAuth.AuthorizeAsync(); if (await this.InitializeInternal(singleUserAuth)) { return(true); } } catch (Exception ex) { Logger.Log(ex); } } try { PinAuthorizer pinAuth = new PinAuthorizer() { CredentialStore = new InMemoryCredentialStore { ConsumerKey = TwitterService.ClientID, ConsumerSecret = ChannelSession.SecretManager.GetSecret("TwitterSecret"), }, GoToTwitterAuthorization = pageLink => Process.Start(pageLink), GetPin = () => { while (string.IsNullOrEmpty(this.authPin)) { Task.Delay(1000).Wait(); } return(this.authPin); } }; await pinAuth.AuthorizeAsync(); this.authPin = null; return(await this.InitializeInternal(pinAuth)); } catch (Exception ex) { Logger.Log(ex); } return(false); }
public void InitializeRequest_Sets_Request_Headers() { var req = new Request("https://api.twitter.com/statuses/public.json"); const string UserAgent = "LINQ to Twitter v2.0"; var pinAuth = new PinAuthorizer(); var oAuthMock = new Mock <IOAuthTwitter>(); string outUrl; string queryString = "oauth_token=token"; oAuthMock.Setup(oAuth => oAuth.GetOAuthQueryString(HttpMethod.GET, req, string.Empty, out outUrl, out queryString)); pinAuth.OAuthTwitter = oAuthMock.Object; pinAuth.UserAgent = UserAgent; pinAuth.ReadWriteTimeout = new TimeSpan(0, 0, 1); pinAuth.Timeout = new TimeSpan(0, 0, 2); pinAuth.UseCompression = true; var httpReq = pinAuth.Get(req) as HttpWebRequest; Assert.NotNull(httpReq); Assert.Equal(UserAgent, httpReq.UserAgent); Assert.Equal(1000, httpReq.ReadWriteTimeout); Assert.Equal(2000, httpReq.Timeout); Assert.Equal("gzip, deflate", httpReq.Headers[HttpRequestHeader.AcceptEncoding]); Assert.Equal(DecompressionMethods.Deflate | DecompressionMethods.GZip, httpReq.AutomaticDecompression); }
private void DoPinAuth() { pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = "", ConsumerSecret = "" }, UseCompression = true, GoToTwitterAuthorization = pageLink => Dispatcher.BeginInvoke(() => WebBrowser.Navigate(new Uri(pageLink))) }; pinAuth.BeginAuthorize(resp => Dispatcher.BeginInvoke(() => { switch (resp.Status) { case TwitterErrorStatus.Success: break; case TwitterErrorStatus.TwitterApiError: case TwitterErrorStatus.RequestProcessingException: MessageBox.Show( resp.Exception.ToString(), resp.Message, MessageBoxButton.OK); break; } })); twitterCtx = new TwitterContext(pinAuth); }
private static TwitterContext CreateContext(string accessToken, string oAuthToken) { var auth = new PinAuthorizer() { Credentials = new InMemoryCredentials { ConsumerKey = "rgRMroMnWQ8IoUNYcNIX0BsLV", ConsumerSecret = "vfX2T7V9kwmwDzCyBW8ZP91jElRhGnCNnG6fbfcvz1ysOrt8Bz", AccessToken = accessToken, OAuthToken = oAuthToken }, GoToTwitterAuthorization = pageLink => Process.Start(pageLink), GetPin = () => { Console.WriteLine( "\nAfter authorizing this application, Twitter " + "will give you a 7-digit PIN Number.\n"); Console.Write("Enter the PIN number here: "); var pin = Console.ReadLine(); return(pin); } }; auth.AuthAccessType = AuthAccessType.Write; auth.Authorize(); return(new TwitterContext(auth)); }
static IAuthorizer DoPinOAuth() { var auth = new PinAuthorizer() { CredentialStore = new InMemoryCredentialStore { ConsumerKey = Environment.GetEnvironmentVariable(OAuthKeys.TwitterConsumerKey), ConsumerSecret = Environment.GetEnvironmentVariable(OAuthKeys.TwitterConsumerSecret) }, GoToTwitterAuthorization = pageLink => { var psi = new ProcessStartInfo { FileName = pageLink, UseShellExecute = true }; Process.Start(psi); }, GetPin = () => { Console.WriteLine( "\nAfter authorizing this application, Twitter " + "will give you a 7-digit PIN Number.\n"); Console.Write("Enter the PIN number here: "); return(Console.ReadLine()); } }; return(auth); }
public void Authorize_Requires_Credentials() { var pinAuth = new PinAuthorizer(); var ex = Assert.Throws <ArgumentNullException>(() => pinAuth.Authorize()); Assert.Equal("Credentials", ex.ParamName); }
ITwitterAuthorizer PerformAuthorization() { // validate that credentials are present if (string.IsNullOrWhiteSpace(twitterConsumerKey) || string.IsNullOrWhiteSpace(twitterConsumerSecret)) { MessageBox.Show(@"Error while setting " + "App.config/appSettings. \n\n" + "You need to provide your twitterConsumerKey and twitterConsumerSecret in App.config \n" + "Please visit http://dev.twitter.com/apps for more info.\n"); return(null); } // configure the OAuth object var auth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = twitterConsumerKey, ConsumerSecret = twitterConsumerSecret }, UseCompression = true, GoToTwitterAuthorization = pageLink => Process.Start(pageLink), GetPin = () => { // this executes after user authorizes, which begins with the call to auth.Authorize() below. PinWindow pinw = new PinWindow(); pinw.Owner = this; if (pinw.ShowDialog() == true) { return(pinw.Pin); } else { return(""); } } }; // start the authorization process (launches Twitter authorization page). try { auth.Authorize(); } catch (WebException ex) { /*MessageBox.Show("Unable to authroize with Twitter right now. Please check pin number", "Twitter Archive Eraser", * MessageBoxButton.OK, MessageBoxImage.Information); */ MessageBox.Show(ex.Message); return(null); } return(auth); }
public void TwitterContext_Single_Param_Constructor_Sets_Defaults() { const string BaseUrl = "https://api.twitter.com/1.1/"; const string SearchUrl = "https://api.twitter.com/1.1/search/"; ITwitterAuthorizer authorizedClient = new PinAuthorizer(); var ctx = new TwitterContext(authorizedClient); Assert.Same(authorizedClient, ctx.AuthorizedClient); Assert.Equal(BaseUrl, ctx.BaseUrl); Assert.Equal(SearchUrl, ctx.SearchUrl); }
public void CompleteAuthorize_Requires_Pin() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials(), OAuthTwitter = new OAuthTwitterMock(), GoToTwitterAuthorization = link => { } }; var ex = Assert.Throws <ArgumentNullException>(() => pinAuth.CompleteAuthorize(null, resp => { })); Assert.Equal("pin", ex.ParamName); }
public void BeginAuthorize_Requires_GoToTwitterAuthorization_Handler() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials(), OAuthTwitter = new OAuthTwitterMock(), GetPin = () => "1234567", }; var ex = Assert.Throws <InvalidOperationException>(() => pinAuth.BeginAuthorize(resp => { })); Assert.True(ex.Message.Contains("GoToTwitterAuthorization")); }
public void CompleteAuthorize_Invokes_AuthorizationCompleteCallback() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials(), OAuthTwitter = new OAuthTwitterMock(), GoToTwitterAuthorization = link => { } }; TwitterAsyncResponse <UserIdentifier> twitterResp = null; pinAuth.CompleteAuthorize("1234567", resp => twitterResp = resp); Assert.NotNull(twitterResp); }
void Page_Loaded(object sender, RoutedEventArgs e) { pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = "", ConsumerSecret = "" }, UseCompression = true, GoToTwitterAuthorization = pageLink => Dispatcher.BeginInvoke(() => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute))) }; this.pinAuth.BeginAuthorize(resp => Dispatcher.BeginInvoke(() => { switch (resp.Status) { case TwitterErrorStatus.Success: break; case TwitterErrorStatus.TwitterApiError: case TwitterErrorStatus.RequestProcessingException: MessageBox.Show( resp.Exception.ToString(), resp.Message, MessageBoxButton.OK); break; } })); // // comment out the code above and uncomment this code to use SingleUserAuthorizer // //var auth = new SingleUserAuthorizer //{ // Credentials = new SingleUserInMemoryCredentials // { // ConsumerKey = "", // twitter Consumer key // ConsumerSecret = "", // twitter Consumer secret // TwitterAccessToken = "", // twitter Access token // TwitterAccessTokenSecret = "" // twitter Access token secret // } //}; //SharedState.Authorizer = auth; //NavigationService.GoBack(); }
public void Get_Calls_GetOAuthQueryString() { var req = new Request("https://api.twitter.com/statuses/public.json"); var pinAuth = new PinAuthorizer(); var oAuthMock = new Mock <IOAuthTwitter>(); string outUrl; string queryString = "oauth_token=token"; oAuthMock.Setup(oAuth => oAuth.GetOAuthQueryString(HttpMethod.GET, req, string.Empty, out outUrl, out queryString)); pinAuth.OAuthTwitter = oAuthMock.Object; pinAuth.Get(req); oAuthMock.Verify(oAuth => oAuth.GetOAuthQueryString(HttpMethod.GET, req, string.Empty, out outUrl, out queryString), Times.Once()); }
private async void navigate() { this.pinAuthorizer = new PinAuthorizer { CredentialStore = new InMemoryCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["consumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"] }, GoToTwitterAuthorization = pageLink => this.webBrowser.Navigate(new Uri(pageLink, UriKind.Absolute)) }; await this.pinAuthorizer.BeginAuthorizeAsync(); }
public void BeginAuthorize_Invokes_AuthorizationCompleteCallback() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials(), OAuthTwitter = new OAuthTwitterMock(), GetPin = () => "1234567", GoToTwitterAuthorization = link => { } }; TwitterAsyncResponse <object> twitterResp = null; pinAuth.BeginAuthorize(resp => twitterResp = resp); Assert.NotNull(twitterResp); }
public IAuthorizer GetAuthorizer(string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret) { var cred = new InMemoryCredentialStore { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, OAuthToken = oAuthToken, OAuthTokenSecret = oAuthTokenSecret }; var auth0 = new PinAuthorizer() { CredentialStore = cred, }; return(auth0); }
private IAuthorizer Authorise() { IAuthorizer auth = null; string consumerKey = Config.Get <string>("Bot", "ConsumerKey"); string consumerSecret = Config.Get <string>("Bot", "ConsumerSecret"); if (Config.Contains(ConfigSection, "OAToken") && Config.Contains(ConfigSection, "OASecret")) { auth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, OAuthToken = Config.Get <string>(ConfigSection, "OAToken"), OAuthTokenSecret = Config.Get <string>(ConfigSection, "OASecret"), } } } ; else { auth = new PinAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, }, GoToTwitterAuthorization = x => Log.Add($"Go to '{x}' in a web browser.", LogLevel.Important), GetPin = () => { Log.Add("After authorising you will receive a 7-digit pin number, enter this here:", LogLevel.Info); return(Console.ReadLine()); } }; auth.AuthorizeAsync().GetAwaiter().GetResult(); Config.Set(ConfigSection, "OAToken", auth.CredentialStore.OAuthToken); Config.Set(ConfigSection, "OASecret", auth.CredentialStore.OAuthTokenSecret); Config.Save(); } return(auth); }
public void StreamUsersTweets(IList <RetreaveIndex> indexesToStream) { Running = true; DoUserStreams(indexesToStream); return; StringBuilder usersToFollow = new StringBuilder(); bool first = true; //foreach uesr get the associated users //should only be one anyway. foreach (RetreaveIndex index in indexesToStream) { foreach (RegisteredUser user in index.AssociatedUsers) { if (!first) { usersToFollow.Append(","); } usersToFollow.Append(user.TwitterId); first = false; } } Console.WriteLine("Starting stream for " + usersToFollow.ToString()); InMemoryCredentials credentials = new InMemoryCredentials(); //user credentials credentials.AccessToken = AuthenticationTokens.AppOwnerAccessTokenSecret; credentials.OAuthToken = AuthenticationTokens.AppOwnerAccessToken; //app specific credentials credentials.ConsumerKey = AuthenticationTokens.TwitterConsumerKey; credentials.ConsumerSecret = AuthenticationTokens.TwitterConsumerSecret; //save to pin authorizer PinAuthorizer authorizer = new PinAuthorizer(); authorizer.Credentials = credentials; TwitterContext twitterCtx = new TwitterContext(authorizer); //DoSiteStream(twitterCtx, usersToFollow.ToString()); }
public void IsAuthorized_Returns_False_When_1_Credential_Is_Null() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { AccessToken = "A", ConsumerKey = "C", ConsumerSecret = "S", OAuthToken = null } }; bool isAuth = pinAuth.IsAuthorized; Assert.False(isAuth); }
public void IsAuthorized_Returns_True_When_Credentials_Are_Present() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { AccessToken = "A", ConsumerKey = "C", ConsumerSecret = "S", OAuthToken = "O" } }; bool isAuth = pinAuth.IsAuthorized; Assert.True(isAuth); }
public void IsAuthorized_Returns_False_When_4_Credentials_Are_Empty() { var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { AccessToken = "", ConsumerKey = "", ConsumerSecret = "", OAuthToken = "" } }; bool isAuth = pinAuth.IsAuthorized; Assert.False(isAuth); }
public void Authorize_Requires_GoToTwitterAuthorization_Handler() { const string AuthLink = "https://authorizationlink"; var pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials() }; var oAuthMock = new Mock <IOAuthTwitter>(); oAuthMock.Setup(oAuth => oAuth.AuthorizationLinkGet(It.IsAny <string>(), It.IsAny <string>(), "oob", false, AuthAccessType.NoChange)) .Returns(AuthLink); pinAuth.OAuthTwitter = oAuthMock.Object; pinAuth.GetPin = () => { return("1234567"); }; var ex = Assert.Throws <InvalidOperationException>(() => pinAuth.Authorize()); Assert.True(ex.Message.Contains("GoToTwitterAuthorization")); }