Example #1
0
        public async Task <ActionResult> Complete()
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore(HttpContext.Session)
            };

            await auth.CompleteAuthorizeAsync(new Uri(Request.GetDisplayUrl()));

            // This is how you access credentials after authorization.
            // The oauthToken and oauthTokenSecret do not expire.
            // You can use the userID to associate the credentials with the user.
            // You can save credentials any way you want - database,
            //   isolated storage, etc. - it's up to you.
            // You can retrieve and load all 4 credentials on subsequent
            //   queries to avoid the need to re-authorize.
            // When you've loaded all 4 credentials, LINQ to Twitter will let
            //   you make queries without re-authorizing.
            //
            //var credentials = auth.CredentialStore;
            //string oauthToken = credentials.OAuthToken;
            //string oauthTokenSecret = credentials.OAuthTokenSecret;
            //string screenName = credentials.ScreenName;
            //ulong userID = credentials.UserID;
            //

            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult Index()
        {
            /************** Twitter authorize procedures *********************************/

            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
            {
                credentials.ConsumerKey    = ConfigurationManager.AppSettings["twitterConsumerKey"];
                credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
            }

            auth = new MvcAuthorizer {
                Credentials = credentials
            };
            auth.CompleteAuthorization(Request.Url);

            if (!auth.IsAuthorized)
            {
                Uri specialUri = new Uri(Request.Url.ToString());
                return(auth.BeginAuthorization(specialUri));
            }
            twitterCtx = new TwitterContext(auth);

            /***************************************************************************/

            indexModel = new IndexModels();

            return(View());
        }
Example #3
0
        public ActionResult MyProfile(string twitterUserId)
        {
            UserModel     mUser = null;
            MvcAuthorizer auth  = null;

            try
            {
                auth = GetAuthorizer(twitterUserId);

                auth.CompleteAuthorization(Request.Url);

                if (!auth.IsAuthorized)
                {
                    var specialUri = new Uri("/Home/MyProfile");
                    return(auth.BeginAuthorization(specialUri));
                }

                var twitterCtx = new TwitterContext(auth);

                mUser = GetCurrentUser(twitterCtx, auth, twitterUserId);
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = ex.ToString() + " twitterUserId: " + twitterUserId;
            }


            return(View(mUser));
        }
Example #4
0
        /// <summary>
        /// Get Twitter posts
        /// </summary>
        /// <param name="model"></param>
        /// <param name="screenName"></param>
        public static List <SocialFeedItemModel> GetTwitterPosts(SocialMediaAuthorizeModel model, string screenName)
        {
            var authorizer = new MvcAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey       = model.AppId,
                    ConsumerSecret    = model.AppSecret,
                    AccessToken       = model.AccessToken,
                    AccessTokenSecret = model.AccessTokenSecret
                }
            };
            var context = new TwitterContext(authorizer);

            var tweets = (from tweet in context.Status
                          where tweet.Type == StatusType.User &&
                          tweet.ScreenName == screenName
                          select tweet)
                         .ToList();

            return(tweets.Select(t => new SocialFeedItemModel
            {
                Id = t.ID.ToString(CultureInfo.InvariantCulture),
                Message = t.Text,
                Created = t.CreatedAt
            }).ToList());
        }
        public async Task <ActionResult> ListingFollowersAsync()
        {
            List <string>             amigos = new List <string>();
            List <FollowersViewModel> fView  = new List <FollowersViewModel>();



            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };

            var ctx        = new TwitterContext(auth); //UserID = "1068723410757435393"
            var seguidores =
                await
                    (from follower in ctx.Friendship
                    where follower.Type == FriendshipType.FollowerIDs && follower.UserID == CredenciaisAuth.UserID.ToString()
                    select follower).SingleOrDefaultAsync();

            if (seguidores != null &&
                seguidores.IDInfo != null &&
                seguidores.IDInfo.IDs != null)
            {
                seguidores.IDInfo.IDs.ForEach(id => amigos.Add(id.ToString()));
                foreach (var item in amigos)
                {
                    fView.Add(new FollowersViewModel
                    {
                        UserID = item
                    });
                }
            }
            return(View(fView));
        }
        //[EnableCors(origins: "*", headers: "*", methods: "*")]
        public async Task <ActionResult> BeginAsync(string rowId, string url, string publisher, string media)
        {
            //var auth = new MvcSignInAuthorizer

            string pathurl = "";


            if (!string.IsNullOrEmpty(rowId) && !string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(publisher) && !string.IsNullOrEmpty(media))
            {
                string[] CurrentUrl = Request.Url.ToString().Split('?');
                var      auth       = new MvcAuthorizer
                {
                    CredentialStore = new SessionStateCredentialStore
                    {
                        ConsumerKey    = ConfigurationManager.AppSettings["consumerKey"],
                        ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                    }
                };

                // string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
                string twitterCallbackUrl = CurrentUrl[0].Replace("Begin", "Complete");
                // auth.Callback = new Uri(twitterCallbackUrl);
                await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl + "?rowId=" + rowId + "&CRMUrl=" + url + "&PublisherName=" + publisher + "&SocialMediaType=" + media));

                pathurl = "https://api.twitter.com/oauth/authorize?oauth_token=" + auth.Parameters["oauth_token"] + "";
                return(Json(pathurl, JsonRequestBehavior.AllowGet));
            }
            else
            {
                pathurl = "Error";
                return(Json(pathurl, JsonRequestBehavior.AllowGet));
            }
        }
Example #7
0
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            //return View();
            if (!Request.IsAuthenticated)
            {
                var credentials = new InMemoryCredentials();
                credentials.ConsumerKey    = ConfigurationManager.AppSettings["TwitterCustomerKey"];
                credentials.ConsumerSecret = ConfigurationManager.AppSettings["TwitterCustomerSecret"];
                var auth = new MvcAuthorizer {
                    Credentials = credentials
                };
                auth.CompleteAuthorization(Request.Url);
                if (!auth.IsAuthorized)
                {
                    return(auth.BeginAuthorization(Request.Url));
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(auth.ScreenName, true);
                    PostworthyUser pm = UsersCollection.Single(auth.ScreenName, addIfNotFound: true);
                    if (string.IsNullOrEmpty(pm.AccessToken) && string.IsNullOrEmpty(pm.OAuthToken))
                    {
                        pm.AccessToken = auth.Credentials.AccessToken;
                        pm.OAuthToken  = auth.Credentials.OAuthToken;
                        UsersCollection.Save();
                    }
                    return(RedirectToAction("Index", new { controller = "Home", action = "Index", id = UrlParameter.Optional }));
                }
            }
            else
            {
                return(RedirectToAction("Index", new { controller = "Home", action = "Index", id = UrlParameter.Optional }));
            }
        }
Example #8
0
        private MvcAuthorizer GetAuthorizer(string twitterUserId)
        {
            var twitterKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            var twitterSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];

            IOAuthCredentials credentials = new InMemoryCredentials();

            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
            {
                credentials.ConsumerKey    = twitterKey;
                credentials.ConsumerSecret = twitterSecret;
            }

            if (!string.IsNullOrEmpty(twitterUserId))
            {
                var challengerModel = _repository.Get(twitterUserId);
                credentials.AccessToken =
                    challengerModel.Connections.Single(x => x.ConnectionName == "Twitter").AccessToken;
                credentials.OAuthToken =
                    challengerModel.Connections.Single(x => x.ConnectionName == "Twitter").OAuthToken;
            }


            var auth = new MvcAuthorizer
            {
                Credentials = credentials
            };

            return(auth);
        }
Example #9
0
        public async Task <IActionResult> CompleteAsync()
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore(HttpContext.Session)
            };

            // It's important to make sure that the "oauth_verifier" is appended to the query string
            // because CompleteAuthorizeAsync uses it to finish the OAuth sequence with Twitter.
            string callingUrl = Url.Action(nameof(CompleteAsync), "OAuth", new { oauth_verifier = Request.Query["oauth_verifier"] }, Request.Scheme);

            await auth.CompleteAuthorizeAsync(new Uri(callingUrl));

            // This is how you access credentials after authorization.
            // The oauthToken and oauthTokenSecret do not expire.
            // You can use the userID to associate the credentials with the user.
            // You can save credentials any way you want - database,
            //   isolated storage, etc. - it's up to you.
            // You can retrieve and load all 4 credentials on subsequent
            //   queries to avoid the need to re-authorize.
            // When you've loaded all 4 credentials, LINQ to Twitter will let
            //   you make queries without re-authorizing.
            //
            //var credentials = auth.CredentialStore;
            //string oauthToken = credentials.OAuthToken;
            //string oauthTokenSecret = credentials.OAuthTokenSecret;
            //string screenName = credentials.ScreenName;
            //ulong userID = credentials.UserID;
            //

            return(RedirectToAction(nameof(HomeController.Index), "Home"));
        }
Example #10
0
        protected string GetImageInfo(string twitterName, string defaultURL)
        {
            if (twitterName == null)
            {
                return(defaultURL);
            }
            string twitterURL         = defaultURL;
            var    auth               = new MvcAuthorizer();
            SessionStateCredentials s = new SessionStateCredentials();

            s.ConsumerKey    = "fUpi8KuU3hMWsCHueZIww";
            s.ConsumerSecret = "4gCFXwi5zW5CYIoGSNgydL9dmqVM9T9BUS9ElrMI";
            auth.Credentials = s;
            var twitterCtx = new TwitterContext(auth);

            try
            {
                var userResponse =
                    (from user in twitterCtx.User
                     where user.Type == UserType.Lookup &&
                     user.ScreenName == twitterName.Replace("@", "")
                     select user).ToList();

                if (userResponse == null)
                {
                    return(defaultURL);
                }
                twitterURL = userResponse.FirstOrDefault().ProfileImageUrl;
            }
            catch
            {
                return(defaultURL);
            }
            return(twitterURL);
        }
Example #11
0
        public ActionResult Tweets(string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return HttpNotFound();
            }

            var authorizer = new MvcAuthorizer {Credentials = new SessionStateCredentials()};

            if (!authorizer.IsAuthorized)
            {
                return RedirectToAction("BeginAuthorization", "OAuth", new {query});
            }

            var ctx = new TwitterContext(authorizer);
            var searchResponse = (from search in ctx.Search
                                  where search.Type == SearchType.Search
                                  where search.Query == query
                                  where search.Count == 50
                                  where search.SearchLanguage == "en"
                                  where search.ResultType == ResultType.Mixed
                                  select search).Single();

            return new JsonNetResult {Data = searchResponse.Statuses, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
        }
Example #12
0
        /// <summary>
        /// Get twitter account info
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static SocialMediaResponseModel GetTwitterAccountInfo(SocialMediaResponseModel model)
        {
            var authorizer = new MvcAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey       = model.AppId,
                    ConsumerSecret    = model.AppSecret,
                    AccessToken       = model.AccessToken,
                    AccessTokenSecret = model.AccessTokenSecret
                }
            };

            var context = new TwitterContext(authorizer);

            var account = (from a in context.Account
                           where a.Type == AccountType.VerifyCredentials
                           select a).SingleOrDefault();

            if (account != null)
            {
                model.FullName = account.User.ScreenNameResponse;
            }

            return(model);
        }
        public async Task <List <TweetSearchModel> > GetTweets(string query, int count, ResultType type)
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };

            var ctx = new TwitterContext(auth);

            var listOfTweets = new List <TweetSearchModel>();

            ulong maxId = 0;

            while (listOfTweets.Count < count)
            {
                var numberToRequest = Math.Max(count, 100);

                var searchResponse =
                    await
                        (from search in ctx.Search
                        where search.Type == SearchType.Search &&
                        search.Query == query &&
                        search.Count == numberToRequest &&
                        search.ResultType == type &&
                        search.MaxID == maxId
                        select search)
                    .SingleOrDefaultAsync();


                maxId = searchResponse.Statuses.Last().StatusID - 1;


                if (searchResponse.Count < 1)
                {
                    break;
                }


                listOfTweets.AddRange(
                    from tweet in searchResponse.Statuses
                    where tweet.RetweetedStatus.RetweetCount < 1
                    select new TweetSearchModel
                {
                    ID            = tweet.StatusID,
                    ImageUrl      = tweet.User.ProfileImageUrl,
                    ScreenName    = tweet.User.Name,
                    Text          = tweet.Text,
                    CreatedAt     = tweet.CreatedAt,
                    IsVerified    = tweet.User.Verified,
                    RetweetCount  = tweet.RetweetCount,
                    FavoriteCount = tweet.FavoriteCount,
                    FollowerCount = tweet.User.FollowersCount,
                    StatusesCount = tweet.User.StatusesCount,
                    Lang          = tweet.Lang
                });
            }


            return(listOfTweets.Take(count).ToList());
        }
        public void BeginAuthorization_Sets_Callback()
        {
            var auth             = new MvcAuthorizer();
            Uri linqToTwitterUri = new Uri("http://linqtotwitter.codeplex.com");

            auth.BeginAuthorization(linqToTwitterUri);

            Assert.Equal(linqToTwitterUri, auth.Callback);
        }
Example #15
0
        public TweetController(ILogger <TweetController> logger, ApplicationDbContext dbCtx)
        {
            _dbCtx  = dbCtx;
            _logger = logger;
            var auth = new MvcAuthorizer();

            _twtCtx        = new TwitterContext(auth);
            _messageHelper = new MessageDeliveryHelper(_logger);
        }
Example #16
0
 public ActionResult CompleteAuthorization(string query)
 {
     var authorizer = new MvcAuthorizer {Credentials = new SessionStateCredentials()};
     if (authorizer.CompleteAuthorization(Request.Url))
     {
         return RedirectToAction("Index", "Twitter", new {query});
     }
     return View("Error");
 }
Example #17
0
 public async Task<ActionResult> BeginAsync()
 {
     var auth = new MvcAuthorizer
     {
         CredentialStore = new SessionStateCredentialStore
         {
             ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
             ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
         }
     };
        public async Task <ActionResult> HomeTimelineAsync(string id, string mediaType)
        {
            try
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var auth = new MvcAuthorizer
                    {
                        CredentialStore = new SessionStateCredentialStore()
                    };

                    Guid Id = Guid.Empty;
                    if (id != null)
                    {
                        Id = Guid.Parse(id);
                    }

                    var credentials = auth.CredentialStore;
                    var twitterUser = Obj.tbl_Twitter.SingleOrDefault(o => o.Id == Id && o.SocialMediaType == mediaType);
                    credentials.ConsumerKey      = ConfigurationManager.AppSettings["consumerKey"];
                    credentials.ConsumerSecret   = ConfigurationManager.AppSettings["consumerSecret"];
                    credentials.OAuthToken       = twitterUser.OauthToken;
                    credentials.OAuthTokenSecret = twitterUser.OauthTokenSecret;
                    credentials.ScreenName       = twitterUser.ScreenName;
                    credentials.UserID           = Convert.ToUInt64(twitterUser.UserID);


                    auth.CredentialStore = credentials;

                    var ctx = new TwitterContext(auth);

                    var tweets =
                        await
                            (from tweet in ctx.Status
                            where tweet.Type == StatusType.Home && tweet.Count == 50
                            select new TweetViewModel
                    {
                        ImageUrl   = tweet.User.ProfileImageUrl,
                        ScreenName = tweet.User.ScreenNameResponse,
                        Text       = tweet.Text,
                    })
                        .ToListAsync();

                    return(Json(new { IsSuccess = true, Message = "Success", UserTweet = tweets }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { IsSuccess = false, Message = "Failed" }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #19
0
 private void SetAuthorizationOptions(ISession session)
 {
     Auth = new MvcAuthorizer
     {
         CredentialStore = new SessionStateCredentialStore(session)
         {
             ConsumerKey    = _twitterConfig.ConsumerKey,
             ConsumerSecret = _twitterConfig.ConsumerSecret
         }
     };
 }
Example #20
0
        /// <summary>
        /// Get twitter oauth tokens
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public dynamic GetTwitterTokens(Uri uri)
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };
            Task task = auth.CompleteAuthorizeAsync(uri);

            task.Wait(3000);
            return(auth);
        }
Example #21
0
        private static List <Status> searchUserTweet(string screenName, int maxPagination, DateTime startDate)
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore
                {
                    ConsumerKey    = ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                }
            };

            var           twitterCtx      = new TwitterContext(auth);
            List <Status> searchResults   = new List <Status>();
            int           maxNumberToFind = 500;
            ulong         lastId          = 0;
            DateTime      lastDateTime    = DateTime.UtcNow;

            var tweets = (from tweet in twitterCtx.Status
                          where tweet.Type == StatusType.User &&
                          tweet.ScreenName == screenName &&
                          tweet.Count == maxNumberToFind &&
                          tweet.CreatedAt > startDate
                          select tweet).ToList();

            if (tweets.Count > 0)
            {
                lastId = ulong.Parse(tweets.Last().StatusID.ToString());
                searchResults.AddRange(tweets);
            }

            do
            {
                var id = lastId - 1;
                tweets = (from tweet in twitterCtx.Status
                          where tweet.Type == StatusType.User &&
                          tweet.ScreenName == screenName &&
                          tweet.CreatedAt > startDate &&
                          tweet.MaxID == id
                          select tweet).ToList();

                if (tweets.Count > 0)
                {
                    lastId = tweets.Min(x => x.StatusID);
                    searchResults.AddRange(tweets);
                    lastDateTime = tweets.Min(x => x.CreatedAt);
                }
                else
                {
                    lastDateTime = startDate;
                }
            } while (lastDateTime > startDate);

            return(searchResults);
        }
        public async Task <ActionResult> AccountEntityAsync()
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };
            var ctx = new TwitterContext(auth);



            return(View());
        }
Example #23
0
        public ActionResult Challenge(string twitterUserId)
        {
            //pull back a list of melee users with their stats.
            MvcAuthorizer auth       = GetAuthorizer(twitterUserId);
            var           twitterCtx = new TwitterContext(auth);

            var listOfFriends = FriendList(twitterCtx, twitterUserId);



            return(listOfFriends);
        }
Example #24
0
        public ActionResult Index(string query)
        {
            var authorizer = new MvcAuthorizer {Credentials = new SessionStateCredentials()};

            if (!authorizer.IsAuthorized)
            {
                return RedirectToAction("BeginAuthorization", "OAuth", new {query});
            }

            var viewModel = new IndexViewModel {Query = query};
            return View(viewModel);
        }
Example #25
0
        public MvcAuthorizer GetAuthorizer(ISession session)
        {
            if (Auth == null)
            {
                Auth = new MvcAuthorizer
                {
                    CredentialStore = new SessionStateCredentialStore(session)
                };
            }

            return(Auth);
        }
Example #26
0
        public double GetScore(string twitterId)
        {
            Authorizer = GetAuthorizer(null);
            TwitterCtx = new TwitterContext(Authorizer);

            double score = (1 * GetTwitterFollowerCount(twitterId));

            score += (0.5 * GetTwitterFriendCount(twitterId));
            score += (0.25 * GetStatusUpdateCount(twitterId));
            score += (3 * GetFavouritesCount(twitterId));
            score += (1 * GetLatestTweet(twitterId));

            return(score);
        }
Example #27
0
        public double GetScore(UserModel meleeUser)
        {
            Authorizer = GetAuthorizer(meleeUser);
            TwitterCtx = new TwitterContext(Authorizer);

            double score = (1 * GetTwitterFollowerCount(meleeUser.TwitterUserId));

            score += (0.5 * GetTwitterFriendCount(meleeUser.TwitterUserId));
            score += (0.25 * GetStatusUpdateCount(meleeUser.TwitterUserId));
            score += (3 * GetFavouritesCount(meleeUser.TwitterUserId));
            score += (1 * GetLatestTweet(meleeUser.TwitterUserId));

            return(score);
        }
Example #28
0
        public static async Task <List <Tweet> > GetTweetsAsync(TwitterSearchParam searchParam)
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };

            var ctx = new TwitterContext(auth);

            var query = ctx.Search.Where(w => w.Type == SearchType.Search && w.Query == searchParam.searchKeyWord);

            if (searchParam.Longitude != null && searchParam.Latitude != null && searchParam.Radius != null && searchParam.ZipCode != null)
            {
                query = query.Where(w => w.GeoCode == (searchParam.Latitude + "," + searchParam.Longitude + "," + searchParam.Radius + "mi"));
            }
            if (searchParam.ZipCode != null)
            {
                if (searchParam.Radius == null)
                {
                    searchParam.Radius = "50";
                }
                var longLat = await GetLongLatFromMapQuestAsync(searchParam.ZipCode);

                query = query.Where(w => w.GeoCode == (longLat.results.FirstOrDefault().locations.FirstOrDefault().latLng.lat + ","
                                                       + longLat.results.FirstOrDefault().locations.FirstOrDefault().latLng.lng + ","
                                                       + searchParam.Radius + "mi"));
            }
            if (searchParam.Language != null)
            {
                query = query.Where(w => w.SearchLanguage == searchParam.Language);
            }

            var searchResponse = query.Where(w => w.Count == 100).SingleOrDefaultAsync();
            var tweets         = await SearchResponseToTweetsAsync(await searchResponse);

            if (!searchParam.IncludeRetweet)
            {
                tweets = tweets.Where(w => w.StatusId == 0).ToList();
            }
            if (searchParam.MustContainVideo)
            {
                tweets = tweets.Where(w => w.Media != null).ToList();
            }
            if (searchParam.MustContainPhoto)
            {
                tweets = tweets.Where(w => w.MediaImage != null).ToList();
            }

            return(tweets);
        }
        public async Task <ActionResult> CompleteAsync()
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };
            await auth.CompleteAuthorizeAsync(Request.Url);

            var authCredentials = auth.CredentialStore;

            // É assim que você acessa as credenciais após a autorização.
            // O oauthToken e oauthTokenSecret não expiram.
            // Você pode usar o userID para associar as credenciais ao usuário.
            // Você pode salvar credenciais da maneira que quiser - banco de dados,
            // armazenamento isolado, etc. - depende de você.
            // Você pode recuperar e carregar todas as 4 credenciais em subseqüentes
            // consultas para evitar a necessidade de autorizar novamente.
            // Quando você tiver carregado todas as 4 credenciais, o LINQ to Twitter permitirá
            // você fazer consultas sem re-autorizar.
            //================================================================================

            Credenciais credenciais = new Credenciais
            {
                ConsumerKey      = authCredentials.ConsumerKey,
                ConsumerSecret   = authCredentials.ConsumerSecret,
                OAuthToken       = authCredentials.OAuthToken,
                OAuthTokenSecret = authCredentials.OAuthTokenSecret,
                ScreenName       = authCredentials.ScreenName,
                UserID           = authCredentials.UserID
            };

            // Carreegando propriedades static da class CredenciaisAuth
            // ========================================================
            CredenciaisAuth.ConsumerKey      = authCredentials.ConsumerKey;
            CredenciaisAuth.ConsumerSecret   = authCredentials.ConsumerSecret;
            CredenciaisAuth.OAuthToken       = authCredentials.OAuthToken;
            CredenciaisAuth.OAuthTokenSecret = authCredentials.OAuthTokenSecret;
            CredenciaisAuth.ScreenName       = authCredentials.ScreenName;
            CredenciaisAuth.UserID           = authCredentials.UserID;

            //Carreegando propriedades num Cokie
            //==================================
            HttpCookie httpcookie = new HttpCookie("twitterdesk");

            httpcookie.Value   = credenciais.ToString();
            httpcookie.Expires = DateTime.Now.AddMonths(1);
            Response.Cookies.Add(httpcookie);

            return(RedirectToAction("Index", "StatusDemos"));
        }
    public async Task <ActionResult> BeginAsync()
    {
        //var auth = new MvcSignInAuthorizer
        var auth = new MvcAuthorizer
        {
            CredentialStore = new SessionStateCredentialStore
            {
                ConsumerKey    = ConfigurationManager.AppSettings["consumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
            }
        };
        string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");

        return(await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl)));
    }
Example #31
0
        public ActionResult ExternalLogin(string returnUrl)
        {
            MvcAuthorizer auth             = GetAuthorizer(null);
            var           twitterReturnUrl = ConfigurationManager.AppSettings["TwitterAutorizationReturnUrl"];


            if (!auth.CompleteAuthorization(Request.Url))
            {
                var          specialUri = new Uri(twitterReturnUrl);
                ActionResult res        = auth.BeginAuthorization(specialUri);
                return(res);
            }

            return(AppAuthorizationConfirmation(null));
        }
        public async Task <ActionResult> SeguidoresAsync()
        {
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore()
            };
            var ctx        = new TwitterContext(auth);
            var friendship =
                await
                    (from friend in ctx.Friendship
                    where friend.Type == FriendshipType.FollowersList &&
                    //friend.ScreenName == "desk_tw"
                    friend.ScreenName == CredenciaisAuth.ScreenName
                    select friend).SingleOrDefaultAsync();
            List <SeguidoresViewModel> seguidores = new List <SeguidoresViewModel>();

            if (friendship != null && friendship.Users != null)
            {
                UserServices userServices = new UserServices();
                userServices.GetListaDeUsuarios(friendship.Users);

                foreach (var item in friendship.Users)
                {
                    var seguidor = new SeguidoresViewModel
                    {
                        ProfileImageUrl    = item.ProfileImageUrl,
                        UserIDResponse     = item.UserIDResponse,
                        ScreenNameResponse = item.ScreenNameResponse,
                        Description        = item.Description,
                        Verified           = item.Verified,
                        Name               = item.Name,
                        Protected          = item.Protected,
                        FriendsCount       = item.FriendsCount,
                        FollowersCount     = item.FollowersCount,
                        Following          = item.Following,
                        ShowAllInlineMedia = item.ShowAllInlineMedia,
                        LangResponse       = item.LangResponse
                    };
                    seguidores.Add(seguidor);
                }

                //var jsonSeguidores = JsonConvert.SerializeObject(friendship);
                //var jsonSeguidoresUser = JsonConvert.SerializeObject(seguidores);

                return(View(seguidores));
            }
            return(RedirectToAction("Index", "StatusDemos"));
        }
Example #33
0
        public async Task <ActionResult> Begin()
        {
            //var auth = new MvcSignInAuthorizer
            var auth = new MvcAuthorizer
            {
                CredentialStore = new SessionStateCredentialStore(HttpContext.Session)
                {
                    ConsumerKey    = configuration["Twitter:ConsumerKey"],
                    ConsumerSecret = configuration["Twitter:ConsumerSecret"]
                }
            };

            string twitterCallbackUrl = Request.GetDisplayUrl().Replace("Begin", "Complete");

            return(await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl)));
        }
Example #34
0
        public ActionResult BeginAuthorization(string query)
        {
            var authorizer = new MvcAuthorizer
            {
                Credentials = new SessionStateCredentials
                {
                    ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"]
                }
            };

            var url = Url.Action("CompleteAuthorization", "OAuth", new {query}, Uri.UriSchemeHttps);
            var callback = new Uri(url);
            return authorizer.IsAuthorized
                       ? RedirectToAction("CompleteAuthorization")
                       : authorizer.BeginAuthorization(callback);
        }