Beispiel #1
0
        // **************************************
        // URL: /User/TwitterAuth
        // **************************************

        public ActionResult TwitterAuth()
        {
            TwUser usr;

            if (String.IsNullOrEmpty(Session["nickname"] as String))
            {
                return(RedirectToAction("LogOn", "User", new { ReturnUrl = this.HttpContext.Request.RawUrl }));
            }
            else
            {
                usr = userManager.getUser(Session["nickname"] as string);
            }

            if (!String.IsNullOrEmpty(HttpContext.Request.QueryString["oauth_token"]))
            {
                var atoken = OAuthUtility.GetAccessTokenDuringCallback(ConfigurationManager.AppSettings["consumerkey"], ConfigurationManager.AppSettings["consumersecret"]);
                this.userManager.UpdateTwitterAccount(atoken, usr);

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

            var tokens = OAuthUtility.GetRequestToken(ConfigurationManager.AppSettings["consumerkey"], ConfigurationManager.AppSettings["consumersecret"], "http://localhost/User/TwitterAuth");
            var link   = OAuthUtility.BuildAuthorizationUri(tokens.Token).AbsoluteUri;

            return(this.Redirect(link));
        }
Beispiel #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string consumerKey    = "lGHwH8UWgDc4O98M3ocGYg";                //Resources.OAuth.Twitter_App_ID;
        string consumerSecret = "Ha2c5PNlKS9N9Vh04lXBquERBdhL0kUw0PQcc"; //Resources.OAuth.Twitter_App_SecretKey;

        if (Request["oauth_verifier"] == null)
        {
            string redirectTwitterUrl = Request.Url.Scheme + "://" + Request.Url.Host +
                                        @"/Auth/Twitter/TwitterMakeAuth.aspx";

            // Obtain a request token
            OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret,
                                                                           redirectTwitterUrl);

            // Direct or instruct the user to the following address:
            Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);

            Response.Redirect(authorizationUri.AbsoluteUri);
        }
        else if (Request["oauth_token"] != null && Request["oauth_verifier"] != null)
        {
            string oauth_token    = Request["oauth_token"];
            string oauth_verifier = Request["oauth_verifier"];

            OAuthTokenResponse userInfo = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, oauth_token,
                                                                      oauth_verifier);
            string userName = userInfo.ScreenName;

            TwitterResponse <TwitterUser> user = TwitterUser.Show(userName);
            Response.Write(user.ResponseObject.Name);
        }
    }
Beispiel #3
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            if (!string.IsNullOrEmpty(context.Request["denied"]))
            {
                return(LoginProfile.FromError(new Exception("Canceled at provider")));
            }

            if (string.IsNullOrEmpty(context.Request["oauth_token"]))
            {
                var reqToken = OAuthUtility.GetRequestToken(TwitterKey, TwitterSecret, context.Request.GetUrlRewriter().AbsoluteUri);
                var url      = OAuthUtility.BuildAuthorizationUri(reqToken.Token).ToString();
                context.Response.Redirect(url, true);
                return(null);
            }

            var requestToken = context.Request["oauth_token"];
            var pin          = context.Request["oauth_verifier"];

            var tokens = OAuthUtility.GetAccessToken(TwitterKey, TwitterSecret, requestToken, pin);

            var accesstoken = new OAuthTokens
            {
                AccessToken       = tokens.Token,
                AccessTokenSecret = tokens.TokenSecret,
                ConsumerKey       = TwitterKey,
                ConsumerSecret    = TwitterSecret
            };

            var account = TwitterAccount.VerifyCredentials(accesstoken).ResponseObject;

            return(ProfileFromTwitter(account));
        }
Beispiel #4
0
        /// <summary>
        /// Gets the authorize URL.
        /// </summary>
        /// <param name="consumerAppIdent">The consumer app ident.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>Authorize URL.</returns>
        public string GetAuthorizeUrl(ConsumerAppIdent consumerAppIdent, string returnUrl)
        {
            var requestToken = OAuthUtility.GetRequestToken(
                consumerAppIdent.ConsumerKey, consumerAppIdent.ConsumerSecret, returnUrl);

            return(OAuthUtility.BuildAuthorizationUri(requestToken.Token).AbsoluteUri);
        }
Beispiel #5
0
        public string GetAuthorizationUrl()
        {
            requestToken = OAuthUtility.GetRequestToken(consumerToken.Key, consumerToken.Secret, "oob");
            var authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);

            return(authorizationUri.AbsoluteUri);
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Twitter"/> class.
        /// </summary>
        public Twitter()
        {
            _consumerKey    = Configuration.singleton( )["twitterConsumerKey"];
            _consumerSecret = Configuration.singleton( )["twitterConsumerSecret"];

            _accessToken       = Configuration.singleton( )["twitterAccessToken"];
            _accessTokenSecret = Configuration.singleton( )["twitterAccessTokenSecret"];



            if (Configuration.singleton()["twitterRequestToken"] != "" || (_accessToken != "" && _accessTokenSecret != ""))
            {
                return;
            }

            try
            {
                OAuthTokenResponse tkn = OAuthUtility.GetRequestToken(_consumerKey, _consumerSecret);
                Configuration.singleton( )["twitterRequestToken"] = tkn.Token;


                Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(tkn.Token);



                Helpmebot6.irc.ircPrivmsg(Helpmebot6.debugChannel,
                                          "Please authorise access to Twitter: " + authorizationUri);
            }
            catch (TwitterizerException ex)
            {
                GlobalFunctions.errorLog(ex);
            }
        }
        public ActionResult ConnectToTwitter()
        {
            OAuthTokenResponse response = OAuthUtility.GetRequestToken(ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["consumerSecret"], "http://" + Request.Url.Authority.ToString() + "/Account");

            Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(response.Token);

            return(Redirect(authorizationUri.ToString()));
        }
Beispiel #8
0
        internal static string GetLoginUrl(out string requestToken)
        {
            var token = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, "oob");

            var url = OAuthUtility.BuildAuthorizationUri(token.Token);

            requestToken = token.Token;

            return(url.AbsoluteUri);
        }
        protected string getTwitterLink()
        {
            var TwitterRequestToken = GetTwitterRequestToken();

            if (TwitterRequestToken != null)
            {
                Uri authenticationUri = OAuthUtility.BuildAuthorizationUri(TwitterRequestToken.Token, true);
                return(authenticationUri.AbsoluteUri);
            }
            return(null);
        }
 protected void btn_signuptwitter_Click(object sender, EventArgs e)
 {
     if (!TwitterConnect.IsAuthorized)
     {
         /*
          * TwitterConnect twitter = new TwitterConnect();
          * twitter.Authorize(Request.Url.AbsoluteUri.Split('?')[0]);
          */
         OAuthTokenResponse otr = OAuthUtility.GetRequestToken("CtuSySDU4l4VVuWG7CRHva81N", "srDIZEDCWvXf4CoIGjPornn5MGW5YCk1lul1ZNftWnXmk4sE34",
                                                               "http://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + Request.RawUrl);
         Uri uri = OAuthUtility.BuildAuthorizationUri(otr.Token);
         Response.Redirect(uri.AbsoluteUri);
     }
 }
Beispiel #11
0
        public static void TwitterOpenAuth()
        {
            try
            {
                //redirect url должен совпадать с тем что прописан в приложении, в приложении в twitter необходимо заполнять callbackurl!обязательно!
                var authorizationTokens = OAuthUtility.GetRequestToken(SettingsOAuth.TwitterConsumerKey, SettingsOAuth.TwitterConsumerSecret, HttpContext.Current.Request.Url.ToString());

                var token = authorizationTokens.Token;
                HttpContext.Current.Response.Redirect(OAuthUtility.BuildAuthorizationUri(token).AbsoluteUri, true);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }
Beispiel #12
0
        // Starts your default internet browser and takes you to a twitter page where you can
        // login with any account and allow Rapid Reporter to use the account for Twitter posting.
        // You then get a PIN code to enter in Rapid Reporter.
        public static void TwitterLogin()
        {
            requestToken = OAuthUtility.GetRequestToken("WxOSthlIyUDQzWiGzY7F5Q", "TD3TbCa9BshneTMJTgdTmm57wzfQrQdXa8Ex2Sd7BkM", "oob").Token;

            Process browserProcess = new Process();

            browserProcess.StartInfo.FileName = OAuthUtility.BuildAuthorizationUri(requestToken).AbsoluteUri;
            if (browserProcess.Start())
            {
                browserProcess.WaitForExit();
            }
            else
            {
                //Could not start your browser
            }
        }
Beispiel #13
0
        public ActionResult InitiatePreview(BadgeType previewType)
        {
            OAuthTokens tokens = new OAuthTokens();

            string             twitterLoginCallbackUrl = new Uri(Request.Url, string.Concat("/twitter/callback?previewType=", previewType)).ToString();
            OAuthTokenResponse response = OAuthUtility.GetRequestToken(ConfigurationManager.AppSettings[CUSTOMER_KEY], ConfigurationManager.AppSettings[CUSTOMER_SECRET], twitterLoginCallbackUrl);

            Uri twitterLoginUrl = OAuthUtility.BuildAuthorizationUri(response.Token, false);

            if (User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                Session.Abandon();
            }

            return(Redirect(twitterLoginUrl.ToString()));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string consumerKey    = Session["consumerkey"] as string;
        string consumerSecret = Session["consumersecret"] as string;

        if (string.IsNullOrEmpty(consumerKey) || string.IsNullOrEmpty(consumerSecret))
        {
            Response.Redirect("~/", true);
        }

        if (IsPostBack)
        {
            return;
        }

        if (Request.QueryString.AllKeys.Contains("oauth_token"))
        {
            CallbackPanel.Visible = true;
            SetupPanel.Visible    = false;

            OAuthTokenResponse accessTokenResponse = OAuthUtility.GetAccessTokenDuringCallback(consumerKey, consumerSecret);
            AccessTokenLabel.Text  = accessTokenResponse.Token;
            AccessSecretLabel.Text = accessTokenResponse.TokenSecret;
            ScreenNameLabel.Text   = accessTokenResponse.ScreenName;
            UserIdLabel.Text       = accessTokenResponse.UserId.ToString();
        }
        else
        {
            string callbackUrl = "http://localhost:59813/Twitterizer-Web/3-Popup/callback.htm";

            string requestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callbackUrl).Token;
            RequestTokenLabel.Text = requestToken;

            Uri authenticationUri = OAuthUtility.BuildAuthorizationUri(requestToken);
            AuthenticationUrlLink.Text        = authenticationUri.AbsoluteUri;
            AuthenticationUrlLink.NavigateUrl = authenticationUri.AbsoluteUri;

            AuthenticationUrlLink.Attributes.Add("onclick",
                                                 "window.open(this.href, \"twitter-auth-window\", \"status=0,toolbar=0,location=1,menubar=0\"); return false;");

            AuthenticationUrl = authenticationUri.AbsoluteUri;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string consumerKey    = Session["consumerkey"] as string;
        string consumerSecret = Session["consumersecret"] as string;

        if (string.IsNullOrEmpty(consumerKey) || string.IsNullOrEmpty(consumerSecret))
        {
            Response.Redirect("~/", true);
        }

        string callbackUrl  = "http://localhost:59813/Twitterizer-Web/2-MultipleUser/callback.aspx";
        string requestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callbackUrl).Token;

        RequestTokenLabel.Text = requestToken;

        Uri authenticationUri = OAuthUtility.BuildAuthorizationUri(requestToken);

        AuthenticationUrlLink.Text        = authenticationUri.AbsoluteUri;
        AuthenticationUrlLink.NavigateUrl = authenticationUri.AbsoluteUri;
    }
Beispiel #16
0
        private void getTwitterPin()
        {
            // Obtain a request token
            _requestToken = OAuthUtility.GetRequestToken(_consumerKey, _consumerSecret, "oob", new WebProxy());

            // Direct or instruct the user to the following address:
            Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(_requestToken.Token);

            browser.Dispose();
            browser = new WebBrowser();
            //browser.Width = (double)300;

            browser.LoadCompleted += new LoadCompletedEventHandler(browser_LoadCompleted);
            TwitterPinOverlay.Children.Add(browser);

            browser.Navigate(authorizationUri);

            //For debug uncoment
            browser.Visibility = System.Windows.Visibility.Hidden;
            //ExtendedVisualStateManager.GoToElementState(this.AccountAddTwitterOverlay as FrameworkElement, AddTwitterUser2.Name, true);
        }
Beispiel #17
0
        public virtual TwitterAuthorizationModel GetAuthorization()
        {
            try
            {
                OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, "oob", null);
                Uri authorizationUri            = OAuthUtility.BuildAuthorizationUri(requestToken.Token);

                return(new TwitterAuthorizationModel
                {
                    Token = requestToken.Token,
                    Url = authorizationUri.ToString()
                });
            }
            catch (Exception ex)
            {
                Logger.Warn("Failed to get Twitter authorization URL.");
                Logger.TraceException(ex.Message, ex);

                return(null);
            }
        }
Beispiel #18
0
        private void GetAccessKey()
        {
            try
            {
                OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(Classes.AppSetting.ConsumerKey, Classes.AppSetting.ConsumerSecret, "oob");
                // Direct or instruct the user to the following address:
                Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
                lbltoken.BeginInvoke(new MethodInvoker(delegate()
                {
                    lbltoken.Text = requestToken.Token;
                }));
                TwitterBrowser B = new TwitterBrowser();
                B.Open(authorizationUri);
                if (B.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.BeginInvoke(new MethodInvoker(delegate()
                    {
                        txtPassword.Text     = B.VerificationCode;
                        txtPassword.Enabled  = true;
                        statusStrip1.Visible = false;
                        groupBox1.Enabled    = true;
                    }));
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);

                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    txtPassword.Enabled  = true;
                    statusStrip1.Visible = false;
                    groupBox1.Enabled    = true;
                }));
            }
        }
        public static bool LoginUser(string username, string password, string proxyaddress = "")
        {
            try
            {
                #region Login Part

                WebProxy P = GetProxy(proxyaddress);

                OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(Classes.AppSetting.ConsumerKey, Classes.AppSetting.ConsumerSecret, "oob");
                // Direct or instruct the user to the following address:
                Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
                //authenticity_token=aa84db7931040b1ed321372ae2b001ccf4f6e20e&oauth_token=uT3RaA72ld4sIZMwtUxlx1021VRjCkS0VEPyeYj3Fys&session%5Busername_or_email%5D=omidam81&session%5Bpassword%5D=omidomid

                HttpWebRequest R = (HttpWebRequest)HttpWebRequest.Create(authorizationUri);
                R.Proxy = P;
                CookieContainer Cookies = new CookieContainer();
                R.CookieContainer = Cookies;
                using (HttpWebResponse W = (HttpWebResponse)R.GetResponse())
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(W.GetResponseStream());

                    var str1111 = sr.ReadToEnd();
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(str1111);
                    var    authenticity_token = doc.DocumentNode.SelectSingleNode("//input[@name='authenticity_token']").Attributes["value"].Value;
                    string url = string.Format("authenticity_token={0}&oauth_token={1}&session%5Busername_or_email%5D={2}&session%5Bpassword%5D={3}",
                                               authenticity_token, requestToken.Token, username, password);
                    url = "https://twitter.com/oauth/authorize?" + System.Web.HttpUtility.HtmlDecode(url);

                    HttpWebRequest RP = (HttpWebRequest)HttpWebRequest.Create(url);
                    RP.Proxy = P;


                    RP.Method          = "POST";
                    RP.CookieContainer = new CookieContainer();
                    foreach (Cookie item in W.Cookies)
                    {
                        RP.CookieContainer.Add(item);
                    }
                    HttpWebResponse WP = (HttpWebResponse)RP.GetResponse();
                    sr      = new System.IO.StreamReader(WP.GetResponseStream());
                    str1111 = sr.ReadToEnd();
                    doc     = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(str1111);
                    #endregion
                    var code = doc.DocumentNode.SelectSingleNode("//kbd[@aria-labelledby='code-desc']/code").InnerHtml;
                    OAuthTokenResponse resp = OAuthUtility.GetAccessToken(Classes.AppSetting.ConsumerKey, Classes.AppSetting.ConsumerSecret, requestToken.Token, code);
                    #region Save To Database
                    var db      = new TwitterAtomationWa.DataEntities();
                    var account = db.Accounts.FirstOrDefault(aa => aa.ScreenName == username);
                    if (account == null)
                    {
                        account = new Account()
                        {
                            DateCreated  = DateTime.Now,
                            TokenSecret  = resp.TokenSecret,
                            Token        = resp.Token,
                            ScreenName   = resp.ScreenName,
                            Name         = password,
                            ProxyAddress = proxyaddress
                        };
                        db.Accounts.AddObject(account);
                        db.SaveChanges();
                    }
                    else
                    {
                        account.Token        = resp.Token;
                        account.TokenSecret  = resp.TokenSecret;
                        account.ProxyAddress = proxyaddress;
                        db.SaveChanges();
                    }
                }



                return(true);

                #endregion
            }
            catch
            {
                return(false);
            }
        }
Beispiel #20
0
 public Uri autorizar()
 {
     tk = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, "oob");
     return(OAuthUtility.BuildAuthorizationUri(tk.Token));
 }
Beispiel #21
0
        static void Main(string[] args)
        {
            Growler.Initialize();
            bool quiet = false;

            try
            {
                if (args.Contains("-q") || args.Contains("-quiet"))
                {
                    quiet = true;
                }
                if (args.Contains("-config"))
                {
                    OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, "oob");
                    Uri authorizationUri            = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
                    System.Diagnostics.Process.Start(authorizationUri.AbsoluteUri);
                    string verifier = String.Empty;
                    if (InputBox("Enter authorization pin for twt", "Please enter the PIN number from the opened webpage to authorize twt:", ref verifier) == DialogResult.OK)
                    {
                        OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken.Token, verifier);
                        Cfg.cmDoConfig     cfg         = new Cfg.cmDoConfig()
                        {
                            AccessToken = accessToken, QuietMode = false
                        };
                        cfg.Save();
                    }

                    if (!Growler.Growl(Growler.GeneralNotification, "Configuration Complete", "The configuration for twt is now set."))
                    {
                        System.Windows.Forms.MessageBox.Show("The configuration for twt is now set.", "Configuration Complete");
                    }
                }
                else
                {
                    if (!Cfg.cmDoConfig.Exists)
                    {
                        throw new System.IO.FileNotFoundException("Could not find the configuration file with authentication information.\nPlease run twt with the -config argument.", Cfg.cmDoConfig.ConfigPath);
                    }
                    Cfg.cmDoConfig cfg = Cfg.cmDoConfig.Load();

                    if (args.Length > 2 && args[0].ToLower() == "-set")
                    {
                        switch (args[1].ToLower())
                        {
                        case "quiet":
                            bool quietparam;
                            if (bool.TryParse(args[2], out quietparam))
                            {
                                cfg.QuietMode = quietparam;
                                cfg.Save();
                                if (!Growler.Growl(Growler.GeneralNotification, "Settings", "Quiet mode is now " + (quietparam ? "on" : "off") + "."))
                                {
                                    System.Windows.Forms.MessageBox.Show("Quiet mode is now " + (quietparam ? "on" : "off") + ".", "twt Settings");
                                }
                            }
                            else
                            {
                                throw new Exception("'-set quiet' expects 'true' or 'false' as a parameter.");
                            }
                            break;
                        }
                        return;
                    }


                    if (!quiet)
                    {
                        quiet = cfg.QuietMode;
                    }

                    string tweet = string.Empty;
                    foreach (string word in args)
                    {
                        if (word.StartsWith("-") && string.IsNullOrEmpty(tweet))
                        {
                            continue;
                        }
                        tweet = string.Concat(tweet, word, " ");
                    }
                    tweet = tweet.Trim();

                    OAuthTokens token = new OAuthTokens()
                    {
                        AccessToken       = cfg.AccessToken.Token,
                        AccessTokenSecret = cfg.AccessToken.TokenSecret,
                        ConsumerKey       = ConsumerKey,
                        ConsumerSecret    = ConsumerSecret
                    };

                    TwitterResponse <TwitterStatus> response = TwitterStatus.Update(token, tweet);
                    if (!quiet)
                    {
                        if (response.Result == RequestResult.Success)
                        {
                            if (!Growler.Growl(Growler.SuccessNotification, tweet))
                            {
                                System.Windows.Forms.MessageBox.Show("Tweeted!", tweet);
                            }
                        }
                        else
                        {
                            if (!Growler.Growl(Growler.ErrorNotification, "Tweet not posted: " + response.ErrorMessage))
                            {
                                System.Windows.Forms.MessageBox.Show("Tweet was not posted.", response.ErrorMessage);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (!quiet)
                {
                    if (!Growler.Growl(Growler.ErrorNotification, e.Message))
                    {
                        System.Windows.Forms.MessageBox.Show(e.Message, "Error");
                    }
                }
            }
        }