public dynamic GetTestWithAccessToken(string accessToken)
 {
     return Test("get test with access token", () =>
                                                   {
                                                       var fb = new FacebookClient(accessToken);
                                                       return fb.Get("/me");
                                                   });
 }
        public dynamic GetTestWithoutAccessToken()
        {
            return Test("get test without access token", () =>
            {
                var fb = new FacebookClient();

                return fb.Get("4");
            });
        }
Example #3
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }


                // added the following lines
                if (info.Login.LoginProvider == "Facebook")
                {
                    var     identity     = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                    var     access_token = identity.FindFirstValue("FacebookAccessToken");
                    var     fb           = new FacebookClient(access_token);
                    dynamic myInfo       = fb.Get("/me?fields=email"); // specify the email field
                    info.Email = myInfo.email;
                }


                var user = new ApplicationUser {
                    UserName = info.DefaultUserName, Email = info.Email, EmailConfirmed = true
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Example #4
0
        private void BtnGetPageLikes_Click(object sender, EventArgs e)
        {
            FacebookClient fbclient  = new FacebookClient(SelectedToken);
            dynamic        pageLikes = fbclient.Get("me/likes?fields=name,fan_count&limit=100");
            int            counter   = Convert.ToInt32(pageLikes.data.Count);

            for (var i = 0; i < counter; i++)
            {
                ListViewItem ls = new ListViewItem();
                ls.Text = pageLikes.data[i].name;
                ls.SubItems.Add(pageLikes.data[i].fan_count.ToString());
                listViewpageLikes.Items.Add(ls);
            }
        }
Example #5
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current)
                    {
                        RedirectUri = new Uri(RedirectUrl)
                    };
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    var expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("me?fields=id,name");
                    long    facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
        // [TestCategory("RequiresOAuth")]
        public void Read_Permissions()
        {
            string appId      = "";
            string appSecret  = "";
            var    query      = string.Format("SELECT {0} FROM permissions WHERE uid == '{1}'", "email", "120625701301347");
            var    parameters = new Dictionary <string, object>();

            parameters["query"]        = query;
            parameters["method"]       = "fql.query";
            parameters["access_token"] = string.Concat(appId, "|", appSecret);
            dynamic result = app.Get(parameters);

            Assert.NotNull(result);
        }
        public async Task <IActionResult> FacebookLogin([FromForm] ExternalUserLogin obj)
        {
            FacebookClient _facebook = new FacebookClient();

            _facebook.AppId       = _externalProvider.Value.Facebook.AppId;
            _facebook.AppSecret   = _externalProvider.Value.Facebook.AppSecret;
            _facebook.AccessToken = obj.AccessToken;

            string result  = _facebook.Get("/me?fields=id,name,picture.width(240).height(240),email").ToString();
            var    tmpUser = JsonConvert.DeserializeObject <ExternalUserModel>(result);

            if (tmpUser.id == 0)
            {
                var responseEr = new ResponseError();
                responseEr.status = "Có lỗi xảy ra không liên kết được với Facebook!";
                return(Ok(responseEr));
            }

            var user = new ApplicationUser();

            user.Email        = (tmpUser.email == null ? obj.Email : tmpUser.email);
            user.UserName     = "******" + tmpUser.id;
            user.FullName     = tmpUser.name;
            user.PasswordHash = tmpUser.id.ToString();
            user.Avatar       = tmpUser.picture.data.url;

            var userEmail = await _userStoreExtend.FindByEmailAsync(tmpUser.email);

            if (userEmail != null)
            {
                var response    = new Response();
                var permissions = await _roleStoreExtend.ReadByUser(userEmail.Id);

                //Mapping
                var userInfo = _mapper.Map <UserInfo>(userEmail);
                userInfo.Permissions = permissions;
                string[] output = userInfo.FullName.Split(' ');
                foreach (string s in output)
                {
                    userInfo.LetterAvatar += s[0];
                }
                userInfo.Avatar       = (userInfo.Avatar == null ? "" : _imagePath.Value.URL + userInfo.Avatar);
                userInfo.PhoneNumber  = (userInfo.PhoneNumber == null ? "" : userInfo.PhoneNumber);
                userInfo.LetterAvatar = userInfo.LetterAvatar.ToUpper();
                response.response     = userInfo;
                return(Ok(response));
            }

            return(await ExternalUser(user));
        }
Example #8
0
        public static dynamic conversations(string accessToken)
        {
            FacebookClient fb = new FacebookClient();

            fb.AccessToken = accessToken;
            try
            {
                return(fb.Get($"{FbConstants.FacebookApiVersion}/me/conversations"));//v2.1
            }
            catch (Exception ex)
            {
                return("Invalid Access Token");
            }
        }
Example #9
0
 public static string GetApplicationToken(string ApiKey, string ApiSecret)
 {
     if (string.IsNullOrEmpty(ApplicationToken))
     {
         var     fb     = new FacebookClient();
         dynamic result = fb.Get("oauth/access_token", new {
             client_id     = ApiKey,
             client_secret = ApiSecret,
             grant_type    = "client_credentials"
         });
         ApplicationToken = result.access_token;
     }
     return(ApplicationToken);
 }
Example #10
0
        public static dynamic getPageTaggedPostDetails(string accessToken)
        {
            FacebookClient fb = new FacebookClient();

            fb.AccessToken = accessToken;
            try
            {
                return(fb.Get($"{FbConstants.FacebookApiVersion}/me/tagged?fields=picture,created_time,message,description,from&limit=99"));//v2.6
            }
            catch (Exception ex)
            {
                return("Invalid Access Token");
            }
        }
Example #11
0
        private void yourname()
        {
            try
            {
                FacebookClient fb     = new FacebookClient(token);
                dynamic        result = fb.Get("/me?name");

                Invoke(new Action(() => label2.Text = result.name));
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.ToString());
            }
        }
Example #12
0
        public f103_Main()
        {
            InitializeComponent();
            this.CenterToScreen();
            FacebookClient fb     = new FacebookClient(globalInfo.access_token);
            dynamic        data   = fb.Get("/me?fields=name");
            var            v_name = ((JsonObject)data)["name"].ToString();

            globalInfo.name = v_name;
            this.Text       = globalInfo.name + " đang sử dụng iPost";
            request v_req = new request();

            globalInfo.cookie_collection = v_req.cookie_init();
        }
Example #13
0
        public static DebugFB GetDebugInfo(string access_token, ApplicationRecord appRecord)
        {
            string  apptoken = GetApplicationToken(appRecord.fbAppKey, appRecord.fbAppSecret);
            var     fb       = new FacebookClient();
            dynamic result   = fb.Get("debug_token", new
            {
                access_token = apptoken,
                input_token  = access_token
            });

            DebugFB debugFB = new DebugFB(result);

            return(debugFB);
        }
        public static string[] voiceGetFrndList(string AccessToken)
        {
            int            i;
            FacebookClient fb         = new FacebookClient(AccessToken);
            dynamic        FriendList = fb.Get("/me/friends");
            int            frndcount  = (int)FriendList.data.Count;

            for (i = 0; i < frndcount; i++)
            {
                ListFriend[i] = FriendList.data[i].name;
            }
            ListFriend[i + 1] = "###";
            return(ListFriend);
        }
        private FacebookDetails GetFacebookDetails(FacebookCredentials facebookCredentials)
        {
            FacebookClient facebookClient = new FacebookClient(facebookCredentials.AccessToken);

            dynamic me = facebookClient.Get("me");

            return(new FacebookDetails()
            {
                UserId = me.id,
                EmailAddress = me.email,
                FirstName = me.first_name,
                LastName = me.last_name
            });
        }
        public static string GetFacebookAccessToken(string code, string returnUrl, string fbRedirectUri)
        {
            var     f      = new FacebookClient();
            dynamic result = f.Get("oauth/access_token", new
            {
                client_id     = System.Configuration.ConfigurationManager.AppSettings["Facebook_API_Key"],
                client_secret = System.Configuration.ConfigurationManager.AppSettings["Facebook_API_Secret"],
                redirect_uri  = fbRedirectUri,
                code          = code,
                state         = returnUrl
            });

            return(result.access_token as string);
        }
Example #17
0
        private void GraphApiExample()
        {
            // note: avoid using synchronous methods if possible as it will block the thread until the result is received
            // use async methods instead. see: GraphApiAsyncExample()
            var fb = new FacebookClient(_accessToken);

            try
            {
                dynamic result = fb.Get("/me");
                var name = result.name;

                lnkName.Text = "Hi " + name;
                lnkName.LinkClicked += (o, e) => Process.Start(result.link);

                // available picture types: square (50x50), small (50xvariable height), large (about 200x variable height) (all size in pixels)
                // for more info visit http://developers.facebook.com/docs/reference/api
                picProfilePic.LoadAsync(string.Format("https://graph.facebook.com/{0}/picture?type={1}", result.id, "square"));
            }
            catch (FacebookApiException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void LegacyRestApiTests()
        {
            Test("legacy rest api tests", () =>
            {
                var fb = new FacebookClient();

                var parameters = new Dictionary<string, object>();
                parameters["fields"] = new[] { "name" };
                parameters["uids"] = new[] { 4 };
                parameters["method"] = "users.getInfo";

                return fb.Get(parameters);
            });
        }
        public int getfanCount(ref FacebookStats objfbsts)
        {
            int friendscnt = 0;
            long friendscount = 0;
            try
            {

                FacebookClient fb = new FacebookClient();

                string accessToken = HttpContext.Current.Session["accesstoken"].ToString();

                fb.AccessToken = accessToken;


                var client = new FacebookClient();

                dynamic me = fb.Get("me");


                dynamic friedscount = fb.Get("fql", new { q = "SELECT friend_count FROM user WHERE uid=me()" });

                foreach (var friend in friedscount.data)
                {
                    friendscount = friend.friend_count;
                }

                friendscnt = Convert.ToInt32(friendscount);


            }
            catch (Exception ex)
            {
                //logger.Error(ex.StackTrace);
                //Console.WriteLine(ex.StackTrace);

            }
            return friendscnt;
        }
        private void LoginCallback(string token)
        {
            _AccessToken = token;

            var fb = new FacebookClient(token);
            var json = fb.Get("/me/accounts/").ToString();
            var root = JObject.Parse(json);

            try
            {
                var pageAccessToken =
                    root["data"].Children().FirstOrDefault(x => x["id"].ToString() == _PageId)["access_token"].ToString();

                if (!string.IsNullOrEmpty(pageAccessToken))
                {
                    _PageAccessToken = pageAccessToken;
                    _ViewModel.IsAuthenticated = true;
                    EnableBrowse();
                }
                else
                {
                    ShowErrorDialog("Unable to find the specified Page ID! I can't create any events for this.");
                    DisableBrowse();
                }
            }
            catch (Exception ex)
            {
                Logger.LogInfo(string.Format(ex.Message + Environment.NewLine + ex.StackTrace));
                ShowErrorDialog("You do not have permission to manage pages.");
                DisableBrowse();
            }

            LoginMenu.Header = _ViewModel.IsAuthenticated ? "Logout" : "Login";
        }