Exemplo n.º 1
0
        public ActionResult LinkTwitter(string oauth_token, string oauth_verifier)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId <= 0)
            {
                return(GetErrorResult("Oh noes! An error happened."));
            }

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    return(GetErrorResult("Oh noes! This really shouldn't happen."));
                }

                // Initialize the OAuth client
                TwitterOAuthClient client = new TwitterOAuthClient();
                client.ConsumerKey    = WebConfigurationManager.AppSettings["twitterConsumerKey"];
                client.ConsumerSecret = WebConfigurationManager.AppSettings["twitterConsumerSecret"];

                // Grab the request token from the session
                SocialOAuthRequestToken requestToken = Session[oauth_token] as SocialOAuthRequestToken;
                if (requestToken == null)
                {
                    return(GetErrorResult("Session expired? Please click the link below and try to link with your Twitter account again ;)"));
                }

                // Update the OAuth client with information from the request token
                client.Token       = requestToken.Token;
                client.TokenSecret = requestToken.TokenSecret;

                // Make the request to the Twitter API to get the access token
                SocialOAuthAccessTokenResponse response = client.GetAccessToken(oauth_verifier);

                // Get the access token from the response body
                TwitterOAuthAccessToken accessToken = (TwitterOAuthAccessToken)response.Body;

                // Update the OAuth client properties
                client.Token       = accessToken.Token;
                client.TokenSecret = accessToken.TokenSecret;

                // Initialize a new service instance from the OAUth client
                var service = Skybrud.Social.Twitter.TwitterService.CreateFromOAuthClient(client);

                // Get some information about the authenticated Twitter user
                TwitterAccount user;
                try
                {
                    // Initialize the options for the request (we don't need the status)
                    var options = new TwitterVerifyCrendetialsOptions
                    {
                        SkipStatus = true
                    };

                    // Make the request to the Twitter API
                    var userResponse = service.Account.VerifyCredentials(options);

                    // Update the "user" variable
                    user = userResponse.Body;
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to get user information from the Twitter API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Get a reference to the member searcher
                BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];

                // Initialize new search criteria for the Twitter screen name
                ISearchCriteria criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery($"twitter:{user.ScreenName}");

                // Check if there are other members with the same Twitter screen name
                foreach (var result in searcher.Search(criteria))
                {
                    if (result.Id != memberId)
                    {
                        LogHelper.Info <ProfileController>("Failed setting Twitter screen name for user with ID " + memberId + ". Username is already used by member with ID " + result.Id + ".");
                        return(GetErrorResult("Another member already exists with the same Twitter screen name."));
                    }
                }

                // Get the member from the member service
                var ms  = ApplicationContext.Services.MemberService;
                var mem = ms.GetById(memberId);

                // Update the "twitter" property and save the value
                mem.SetValue("twitter", user.ScreenName);
                mem.SetValue("twitterId", user.IdStr);
                mem.SetValue("twitterData", user.JObject.ToString());
                ms.Save(mem);

                // Clear the runtime cache for the member
                ApplicationContext.ApplicationCache.RuntimeCache.ClearCacheItem("MemberData" + mem.Username);

                // Redirect the member back to the profile page
                return(RedirectToUmbracoPage(1057));
            }
            catch (Exception ex)
            {
                LogHelper.Error <ProfileController>("Unable to link with Twitter user for member with ID " + memberId, ex);
                return(GetErrorResult("Oh noes! An error happened."));
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Gets a represenation of the authenticated user (requires an access token).
 /// </summary>
 /// <param name="options">The options for the call to the API.</param>
 /// <returns>Returns an instance of <see cref="TwitterVerifyCredentialsResponse"/> representing the response.</returns>
 /// <see>
 ///     <cref>https://dev.twitter.com/rest/reference/get/account/verify_credentials</cref>
 /// </see>
 public TwitterVerifyCredentialsResponse VerifyCredentials(TwitterVerifyCrendetialsOptions options)
 {
     return(TwitterVerifyCredentialsResponse.ParseResponse(Raw.VerifyCredentials(options)));
 }
Exemplo n.º 3
0
 /// <summary>
 /// Gets a represenation of the authenticated user (requires an access token).
 /// </summary>
 /// <param name="options">The options for the call to the API.</param>
 /// <returns>An instance of <see cref="SocialHttpResponse"/> representing the raw response.</returns>
 /// <see>
 ///     <cref>https://dev.twitter.com/rest/reference/get/account/verify_credentials</cref>
 /// </see>
 public SocialHttpResponse VerifyCredentials(TwitterVerifyCrendetialsOptions options)
 {
     return(Client.DoHttpGetRequest("https://api.twitter.com/1.1/account/verify_credentials.json", options));
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Initialize a new OAuth client with information about your app
            TwitterOAuthClient oauth = new TwitterOAuthClient
            {
                ConsumerKey    = "1RA07SxkMPDrnTf5wx4fNQU9v",
                ConsumerSecret = "zsalItDzjWcAg3KWEQPv7UeVCRwR2neLQD0dihlKZ6WYJDnNA7",
                Callback       = "https://b7b326cf8125.ngrok.io/WebForm1.aspx"
            };

            if (Request.QueryString["do"] == "login")
            {
                // Get a request token from the Twitter API
                OAuthRequestToken token = oauth.GetRequestToken();

                // Save the token information to the session so we can grab it later
                Session[token.Token] = token;

                // Redirect the user to the authentication page at Twitter.com
                Response.Redirect(token.AuthorizeUrl);
            }
            else if (Request.QueryString["oauth_token"] != null)
            {
                // Get OAuth parameters from the query string
                string oAuthToken    = Request.QueryString["oauth_token"];
                string oAuthVerifier = Request.QueryString["oauth_verifier"];

                // Grab the request token from the session
                OAuthRequestToken token = Session[oAuthToken] as OAuthRequestToken;

                if (token == null)
                {
                    // Content.Text = "<p>An error occured. Timeout?</p>";
                }
                else
                {
                    // Some information for development purposes
                    //     Content.Text += "<p>Request Token: " + token.Token + "</p>";
                    //      Content.Text += "<p>Request Token Secret: " + token.TokenSecret + "</p>";

                    // Update the OAuth client with information from the request token
                    oauth.Token       = token.Token;
                    oauth.TokenSecret = token.TokenSecret;

                    try
                    {
                        // Obtain an access token from the request token and OAuth verifier
                        OAuthAccessToken accessToken = oauth.GetAccessToken(oAuthVerifier);

                        // Update the OAuth client with the access token and access token secret
                        oauth.Token       = accessToken.Token;
                        oauth.TokenSecret = accessToken.TokenSecret;

                        TwitterVerifyCrendetialsOptions options = new TwitterVerifyCrendetialsOptions
                        {
                            IncludeEmail = true
                        };
                        // Initialize a new TwitterService instance based on the OAuth client
                        TwitterService service = TwitterService.CreateFromOAuthClient(oauth);

                        // Get information about the authenticated user
                        var user = service.Account.VerifyCredentials(options);


                        // Some information for development purposes
                        //  Content.Text += "<b>Hi " + (user.Name ?? user.ScreenName) + "</b> (" + user.Id + ")<br />";
                        //  Content.Text += "<p>Access Token: " + accessToken.Token + "</p>";
                        //  Content.Text += "<p>Access Token Secret: " + accessToken.TokenSecret + "</p>";
                    }
                    catch (Exception ex)
                    {
                        // Content.Text += "<pre style=\"color: red;\">" + ex.GetType().FullName + ": " + ex.Message + "\r\n\r\n" + ex.StackTrace + "</pre>";
                    }
                }
            }
            else if (Request.QueryString["denied"] != null)
            {
                // Get OAuth parameters from the query string
                string oAuthToken = Request.QueryString["denied"];

                // Remove the request token from the session
                Session.Remove(oAuthToken);

                // Write some output for the user
                ///  Content.Text += "<p>It seems that you cancelled the login!</p>";/
                /// / Content.Text += "<p><a href=\"OAuth.aspx?do=login\">Try again?</a></p>";
            }
            else
            {
                //   Content.Text += "<p><a href=\"OAuth.aspx?do=login\">Login with Twitter</a></p>";
            }
        }