Exemple #1
0
        public static async Task<string> LogIn()
        {
            string message = String.Empty;
            try
            {
                FacebookSession session = new FacebookSession();
                FacebookSessionClient client = new FacebookSessionClient(App.fbAppID);
                session = await client.LoginAsync(
                    "user_about_me," +
                    "friends_about_me," +
                    "publish_stream");
                App.isAuthenticated = true;
                App.fbToken = session.AccessToken;
                App.fbUserID = session.FacebookId;

                 FacebookUser user = await Users.DownloadUserInfo(App.fbUserID);

                App.fbProfilePicture = user.Picture.data.url;
                App.fbProfileName = user.Name;
                return "OK";

            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                return message;
            }
        }
        private async Task Authenticate(Action loginSuccessCallback)
        {
            //string message = String.Empty;
            try
            {
                session = await App.FacebookSessionClient.LoginAsync(Permissions);

                // Login success 

                App.AccessToken = session.AccessToken;
                App.FacebookId = session.FacebookId;

                //Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/HomePage.xaml", UriKind.Relative)));
                loginSuccessCallback();
            }
            catch (InvalidOperationException e)
            {
                App.AccessToken = String.Empty;
                
                //message = "Login failed! Exception details: " + e.Message;
                //MessageBox.Show(message);
            }

            
            //Update accesstoken (login-status) in user-config
            var u = MiscHelpers.GetItemFromIsolatedStorage<UserConfigModel>("fbd-userconfig.xml");
            if (u != null)
            {
                u.FacebppkAccessToken = App.AccessToken;
                MiscHelpers.SaveDataToIsolatedStorage("fbd-userconfig.xml", u, typeof(UserConfigModel));
            }


            App.isAuthenticated = false;
        }
Exemple #3
0
        public void TheUserIdShouldNotBeNullIfTheLastIsNotEmpty(string accessToken, string id)
        {
            var userId = FacebookSession.ParseUserIdFromAccessToken(accessToken);

            Assert.NotNull(userId);
            Assert.Equal(id, userId);
        }
Exemple #4
0
        private async Task LoginFacebook()
        {
            Deployment.Current.Dispatcher.BeginInvoke(async() =>
            {
                try
                {
                    session = await facebookSessionClient.LoginAsync("user_about_me,read_stream");

                    string js = "";

                    if (session != null)
                    {
                        accessToken    = session.AccessToken;
                        facebookId     = session.FacebookId;
                        facebookClient = new FacebookClient(accessToken);

                        js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.login',true,true);e.success=true;e.token='';e.cancelled={0};document.dispatchEvent(e);", "false");
                    }
                    else
                    {
                        js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.login',true,true);e.success=false;e.token='';e.cancelled={0};document.dispatchEvent(e);", "true");
                    }
                    InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
                }
                catch (Exception ex)
                {
                    string js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.login',true,true);e.success=false;e.token='';e.cancelled={0};document.dispatchEvent(e);", "true");
                    InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
                }
            });
        }
Exemple #5
0
        public static async Task <string> LogIn()
        {
            string message = String.Empty;

            try
            {
                FacebookSession       session = new FacebookSession();
                FacebookSessionClient client  = new FacebookSessionClient(App.fbAppID);
                session = await client.LoginAsync(
                    "user_about_me," +
                    "friends_about_me," +
                    "publish_stream");

                App.isAuthenticated = true;
                App.fbToken         = session.AccessToken;
                App.fbUserID        = session.FacebookId;

                FacebookUser user = await Users.DownloadUserInfo(App.fbUserID);

                App.fbProfilePicture = user.Picture.data.url;
                App.fbProfileName    = user.Name;

                RenewToken();
                return("OK");
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                return(message);
            }
        }
Exemple #6
0
        public void login(string scope)
        {
            try
            {
                if (FacebookSessionClient != null && FacebookSessionClient.LoginInProgress)
                {
                    this.DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                    return;
                }

                var scopes = ParseScopes(scope);

                Deployment.Current.Dispatcher.BeginInvoke(async() =>
                {
                    session = await FacebookSessionClient.LoginAsync(scopes);
                    if (string.IsNullOrEmpty(session.AccessToken))
                    {
                        this.DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                    }
                    else
                    {
                        RemoveLocalData();
                        Settings.Add("access_token", session.AccessToken);
                        Settings.Add("access_expires", session.Expires);
                        Settings.Save();

                        this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, this.getResponse()));
                    }
                });
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
            }
        }
        /*
         * void _browser_Navigating(object sender, NavigatingEventArgs e) {
         *  //throw new NotImplementedException();
         * }
         *
         * void _browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e) {
         *  fail();
         * }
         *
         * void _browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) {
         *  String uri = e.Uri.ToString();
         *  if (uri.StartsWith("https://www.facebook.com/connect/login_success.html") || uri.StartsWith("http://www.facebook.com/connect/login_success.html")
         || uri.StartsWith("https://m.facebook.com/connect/login_success.html") || uri.StartsWith("http://m.facebook.com/connect/login_success.html")) {
         ||     if (uri.EndsWith("#_=_")) {
         ||         uri = uri.Substring(0, uri.Length - 4);
         ||     }
         ||     String queryString = e.Uri.Query.ToString();
         ||     try {
         ||         IEnumerable<KeyValuePair<string, string>> pairs = UriToolKits.ParseQueryString(queryString);
         ||         string code = KeyValuePairUtils.GetValue(pairs, "code");
         ||         string tokenurl = FacebookClient.Instance.getAccessTokenRequestUrl(code);
         ||         WebClient client = new WebClient();
         ||         client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(AccessTokenDownloadCompleted);
         ||         client.DownloadStringAsync(new Uri(tokenurl));
         ||     } catch (Exception ex) {
         ||         fail();
         ||     }
         ||     }
         || else if (uri.StartsWith("https://m.facebook.com/dialog/oauth/write") || uri.StartsWith("http://m.facebook.com/dialog/oauth/write"))
         || {
         ||     string url = FacebookClient.Instance.getLoginUrl();
         ||     _browser.Source = new Uri(url);
         || }
         ||}
         ||void AccessTokenDownloadCompleted(object sender, DownloadStringCompletedEventArgs e) {
         || if (!e.Cancelled && e.Error == null) {
         ||     try {
         ||         string data = e.Result;
         ||         data = "?" + data;
         ||         IEnumerable<KeyValuePair<string, string>> pairs = UriToolKits.ParseQueryString(data);
         ||         string accessToken = KeyValuePairUtils.GetValue(pairs, "access_token");
         ||         string expires = KeyValuePairUtils.GetValue(pairs, "expires");
         ||         success(accessToken, expires);
         ||     } catch (Exception ex) {
         ||         fail();
         ||     }
         || } else {
         ||     fail();
         || }
         ||}*/
        private async Task Authenticate()
        {
            string message = String.Empty;

            try
            {
                session = await FacebookManager.SessionClient.LoginAsync("basic_info,publish_actions,user_about_me,read_stream");

                string state = session.State;
                if (session.AccessToken.Length > 0)
                {
                    state = session.State;
                    FacebookManager.setToken(session.AccessToken);
                    success(session.AccessToken, session.Expires.ToString());
                }
                //Facebook.FacebookClient client = new Facebook.FacebookClient(session.AccessToken);
                //var result = await client.GetTaskAsync("/me?fields=id,name");
                //state = session.State;
            }
            catch (InvalidOperationException e)
            {
                //message = "Login failed! Exception details: " + e.Message;
                // MessageDialog dialog = new MessageDialog(message);
                //dialog.ShowAsync();
                cancel();
            }
        }
        public void TheUserIdShouldBeNull()
        {
            var accessToken = "a||bc";

            var userId = FacebookSession.ParseUserIdFromAccessToken(accessToken);

            Assert.Null(userId);
        }
        public void ParseCookieValue_GivenValidFbsCookieValue_ThenResultShouldNotBeNull()
        {
            var secret      = "3b4a872617be2ae1932baa1d4d240272";
            var cookieValue = "access_token=124973200873702%7C2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026%7Cvz4H9xjlRZPfg2quCv0XOM5g9_o&expires=1295118000&secret=lddpssZCuPoEtjcDFcWtoA__&session_key=2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026&sig=1d95fa4b3dfa5b26c01c8ac8676d80b8&uid=100001327642026";

            Assert.NotNull(FacebookSession.ParseCookieValue(new DefaultFacebookApplication {
                AppSecret = secret
            }, cookieValue));
        }
Exemple #10
0
        public void TheUserIdShouldBeNull()
        {
            string appId = "123";
            string appSecret = " A12aB";

            var userId = FacebookSession.ParseUserIdFromAccessToken(string.Format("{0}|{1}", appId, appSecret));

            Assert.Null(userId);
        }
        public GivenAnApplicationAccessTokenThen()
        {
            string appId     = "123";
            string appSecret = " A12aB";

            accessToken = string.Format("{0}|{1}", appId, appSecret);

            session = new FacebookSession(accessToken);
        }
        public Uri CreateToken()
        {
            FacebookSession session = new FacebookSession(api_key, secret);
            Uri             token   = session.CreateToken();

            facebookSession = session;
            connected       = false;
            return(token);
        }
Exemple #13
0
        /// <summary>
        /// Permet l'authentification via Facebook
        /// </summary>
        /// <returns></returns>
        private async Task Authentification()
        {
            //La variable FacebookSessionClient affiche automatique un élément de type WebBrowser pour la connection Facebook.
            //On déconnecte la variable de type FacebookSession.
            App.FacebookSessionClient.Logout();
            try
            {
                //On initialise la variable FaceBookSession et on récupère le token généré ainsi que l'id Facebook.
                _session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");

                App.AccessToken = _session.AccessToken;
                _idFacebook     = _session.FacebookId;

                //Permet de savoir si l'utilisateur est déjà connecté à Facebook ou non.
                IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

                const string key = "UtilisateurConnecte";

                if (!settings.Contains(key))
                {
                    settings.Add(key, true);
                }
                else
                {
                    settings[key] = true;
                }

                settings.Save();

                //Permet d'exploiter le graphe pour récupérer les informations concernant l'utilisateur.
                //On utilise un Task pour controler l'asynchronisme et permettre à l'application d'avoir le temps de récupérer les informations avant le changement de page.
                var        fb   = new FacebookClient(App.AccessToken);
                JsonObject data = await GetAsyncEx(fb, "https://graph.facebook.com/me", null);

                Dispatcher.BeginInvoke(() =>
                {
                    //On récupère l'image de l'utilisateur en parcourant le graphe Facebook.
                    var profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", _idFacebook, "square", App.AccessToken);
                    BitmapImage photo     = new BitmapImage(new Uri(profilePictureUrl));
                    App.PhotoUtilisateur  = photo;

                    //On crée un utilisateur qui récupère les informations de l'utilisateur.
                    Utilisateur u        = new Utilisateur();
                    u.id_utilisateur     = _idFacebook;
                    u.prenom_utilisateur = data["first_name"].ToString();
                    u.nom_utilisateur    = data["last_name"].ToString();
                    //La variable globale de l'application récupère les informations de l'utilisateur.
                    App.UtilisateurCourant = u;
                });
                //On redirige vers la page dont le nom est contenu dans la variable _pageAvant.
                Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/" + _pageAvant + ".xaml", UriKind.Relative)));
            }
            catch (InvalidOperationException e)
            {
                MessageBox.Show("Login failed! Exception details: " + e.Message);
            }
        }
Exemple #14
0
        public Uri GetLoginUri()
        {
            FacebookSession session = new FacebookSession(api_key, secret);
            Uri             uri     = session.CreateToken();

            facebookSession = session;
            connected       = false;
            return(uri);
        }
        public GivenAnApplicationAccessTokenOnlyThen()
        {
            string appId     = "123";
            string appSecret = " A12aB";

            accessToken = string.Format("{0}|{1}", appId, appSecret);

            session = new FacebookSession(new JsonObject {
                { "access_token", accessToken }
            });
        }
Exemple #16
0
        /// <summary>
        /// Facebook API Instance
        /// </summary>
        /// <param name="session"></param>
        public Api(FacebookSession session) : base(session)
        {
            AuthToken = string.Empty;

#if !SILVERLIGHT
            InstalledCulture = CultureInfo.InstalledUICulture;
#else
            InstalledCulture = CultureInfo.CurrentUICulture;
#endif

            Session = session;

            Auth          = new Auth(Session);
            Video         = new Video(Session);
            Marketplace   = new Marketplace(Session);
            Admin         = new Admin(Session);
            Photos        = new Photos(Session);
            Users         = new Users(Session);
            Friends       = new Friends(Users, Session);
            Events        = new Events(Session);
            Groups        = new Groups(Session);
            Notifications = new Notifications(Session);
            Profile       = new Profile(Session);
            Fbml          = new Fbml(Session);
            Feed          = new Feed(Session);
            Fql           = new Fql(Session);
            LiveMessage   = new LiveMessage(Session);
            Message       = new Message(Session);
            Batch         = new Batch(Session);
            Pages         = new Pages(Session);
            Application   = new Application(Session);
            Data          = new Data(Session);
            Permissions   = new Permissions(Session);
            Connect       = new Connect(Session);
            Comments      = new Comments(Session);
            Stream        = new Stream(Session);
            Status        = new Status(Session);
            Links         = new Links(Session);
            Notes         = new Notes(Session);
            Intl          = new Intl(Session);

            Batch.Batch             = Batch;
            Permissions.Permissions = Permissions;
            Batch.Permissions       = Permissions;
            Permissions.Batch       = Batch;

            foreach (RestBase restBase in new RestBase[] { Auth, Video, Marketplace, Admin, Photos, Users, Friends, Events,
                                                           Groups, Notifications, Profile, Fbml, Feed, Fql, LiveMessage, Message, Pages, Application, Data, Connect, Comments,
                                                           Stream, Status, Links, Notes })
            {
                restBase.Batch       = Batch;
                restBase.Permissions = Permissions;
            }
        }
Exemple #17
0
 private void clearFBData()
 {
     fbLoggedIn            = false;
     FacebookSessionClient = null;
     FacebookSession       = null;
     AccessToken           = String.Empty;
     FacebookId            = String.Empty;
     friends            = null;
     username           = String.Empty;
     userProfilePicture = null;
 }
Exemple #18
0
        public void ParseCookieValue_GivenValidFbsCookieValue_ThenShouldExtractTheAccessTokenCorrectly()
        {
            var secret              = "3b4a872617be2ae1932baa1d4d240272";
            var cookieValue         = "access_token=124973200873702%7C2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026%7Cvz4H9xjlRZPfg2quCv0XOM5g9_o&expires=1295118000&secret=lddpssZCuPoEtjcDFcWtoA__&session_key=2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026&sig=1d95fa4b3dfa5b26c01c8ac8676d80b8&uid=100001327642026";
            var expectedAccessToken = "124973200873702|2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026|vz4H9xjlRZPfg2quCv0XOM5g9_o";

            var session = FacebookSession.ParseCookieValue(new DefaultFacebookApplication {
                AppSecret = secret
            }, cookieValue);

            Assert.Equal(expectedAccessToken, session.AccessToken);
        }
        private async Task Authenticate()
        {
            string message = String.Empty;

            try
            {
                session = await StaticData.FacebookSessionClient.LoginAsync("user_about_me,read_stream,email");

                StaticData.AccessToken = session.AccessToken;
                StaticData.FacebookId  = session.FacebookId;

                FacebookClient fb   = new FacebookClient(StaticData.AccessToken);
                var            temp = await fb.GetTaskAsync("me");

                string       jsonTemp        = temp.ToString();
                JObject      jObject         = JObject.Parse(jsonTemp);
                FacebookUser newFacebookUser = jObject.ToObject <FacebookUser>();

                StaticData.CurrentUser.Name           = newFacebookUser.name;
                StaticData.CurrentUser.UserName       = newFacebookUser.username;
                StaticData.CurrentUser.Password       = newFacebookUser.id;
                StaticData.CurrentUser.Email          = newFacebookUser.email;
                StaticData.CurrentUser.IsFacebookUser = true;

                StaticMethod.ShowProgress(this, "Registering...", 0, true, true);


                try
                {
                    string tempRegister = await UserAPI.Register(StaticData.CurrentUser);

                    //Save that logged in facebook
                    FacebookLoginSettingHelper newHelper = new FacebookLoginSettingHelper();
                    newHelper.SetLanguage(true);

                    StaticMethod.ShowProgress(this, "Registering...", 0, true, false);
                }
                catch (Exception e)
                {
                    //Username conflict
                    Console.WriteLine(e);
                }

                await Login(StaticData.CurrentUser.UserName, StaticData.CurrentUser.Password);
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                MessageBox.Show(message);
            }
        }
        /// <summary>
        /// Deletes all Facebook authentication cookies found in the current request.
        /// </summary>
        public void DeleteAuthCookie()
        {
            string sessionCookieName = FacebookSession.GetCookieName(Settings.AppId);

            foreach (var cookieName in HttpContext.Request.Cookies.AllKeys)
            {
                if (cookieName == sessionCookieName)
                {
                    var cookie = HttpContext.Request.Cookies[sessionCookieName];
                    cookie.Expires = DateTime.UtcNow.AddDays(-1);
                    cookie.Value   = null;
                    HttpContext.Response.Cookies.Set(cookie);
                }
            }
        }
 private async Task Authenticate()
 {
     string message = String.Empty;
     try
     {
         session = await FacebookQuiz.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
         _accessToken = session.AccessToken;
         _faceBookId = session.FacebookId;
     }
     catch (InvalidOperationException e)
     {
         message = "Login failed! Exception details: " + e.Message;
         MessageBox.Show(message);
     }
 }
Exemple #22
0
        private async void NewLogin(object sender, EventArgs e)
        {
            pbLoading.Visibility = Visibility.Visible;
            bLoginF.Visibility   = Visibility.Collapsed;
            newLogin             = true;

            try
            {
                FacebookSession fbSession = await App.FacebookSessionClient.LoginAsync("email,publish_stream,friends_about_me");

                var token = Newtonsoft.Json.Linq.JObject.FromObject(new
                {
                    access_token = fbSession.AccessToken
                });

                MobileServiceUser user = await App.MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token);

                var     client = new FacebookClient(fbSession.AccessToken);
                dynamic me     = await client.GetTaskAsync("me");

                var dbUser = await new User
                {
                    Id    = user.UserId,
                    Name  = me.name,
                    Email = me.email
                }.GetOrCreate();

                App.User = new ViewModels.UserViewModel(dbUser);

                Dispatcher.BeginInvoke(() =>
                {
                    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

                    settings.Add("id", user.UserId);
                    settings.Add("token", user.MobileServiceAuthenticationToken);
                    settings.Save();

                    NavigationService.Navigate(new Uri("/DiscoveryPage.xaml", UriKind.Relative));
                });
            }
            catch
            {
                MessageBox.Show("Login failed.", "Failed", MessageBoxButton.OK);

                pbLoading.Visibility = Visibility.Collapsed;
                bLoginF.Visibility   = Visibility.Visible;
            }
        }
Exemple #23
0
        private async Task AuthenticateFacebook()
        {
            try {
                FacebookSessionClient = new FacebookSessionClient(Constants.FacebookAppId);
                FacebookSession       = await FacebookSessionClient.LoginAsync("user_friends");

                AccessToken = FacebookSession.AccessToken;
                FacebookId  = FacebookSession.FacebookId;
                fbLoggedIn  = true;
                Debug.WriteLine("Facebook login succeeded, facebook ID: " + FacebookId);
            } catch (InvalidOperationException e) {
                MessageDialog dialog = new MessageDialog("Login failed! Exception details: " + e.Message);
                dialog.Commands.Add(new UICommand("Ok"));
                dialog.ShowAsync();
            }
        }
Exemple #24
0
        async private void PostButtonAppbar_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (FacebookData.SelectedFriends.Count < 1 ||
                FacebookData.SelectedMeal.Name == String.Empty ||
                FacebookData.IsRestaurantSelected == false)
            {
                MessageDialog errorMessageDialog = new MessageDialog("Please select friends, a place to eat and something you ate before attempting to share!");
                await errorMessageDialog.ShowAsync();

                return;
            }

            FacebookSession session = await App.FacebookSessionClient.LoginAsync("publish_stream");

            if (session == null)
            {
                MessageDialog dialog = new MessageDialog("Error while getting publishing permissions. Please try again.");
                await dialog.ShowAsync();

                return;
            }

            // refresh your access token to contain the publish permissions
            App.AccessToken = session.AccessToken;

            FacebookClient fb = new FacebookClient(App.AccessToken);

            try
            {
                dynamic fbPostTaskResult = await fb.PostTaskAsync(String.Format("/me/{0}:eat", Constants.FacebookAppGraphAction), new { meal = FacebookData.SelectedMeal.MealUri, tags = FacebookData.SelectedFriends[0].id, place = FacebookData.SelectedRestaurant.Id });

                var result = (IDictionary <string, object>)fbPostTaskResult;

                MessageDialog successMessageDialog = new MessageDialog("Posted Open Graph Action, id: " + (string)result["id"]);
                await successMessageDialog.ShowAsync();

                // reset the selections after the post action has successfully concluded
                this.selectFriendsTextBox.Text    = "Select Friends";
                this.selectMealTextBox.Text       = "Select One";
                this.selectRestaurantTextBox.Text = "Select One";
            }
            catch (Exception ex)
            {
                MessageDialog exceptionMessageDialog = new MessageDialog("Exception during post: " + ex.Message);
                exceptionMessageDialog.ShowAsync();
            }
        }
Exemple #25
0
        public void GenerateSessionSignature_GivenValidSecretAndCorrectParametersInRandomOrderWithoutSig_ThenItShouldGenerateCorrectSessionSignature()
        {
            var secret     = "3b4a872617be2ae1932baa1d4d240272";
            var dictionary = new Dictionary <string, object>
            {
                { "expires", "1295118000" },
                { "uid", "100001327642026" },
                { "access_token", "124973200873702|2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026|vz4H9xjlRZPfg2quCv0XOM5g9_o" },
                { "secret", "lddpssZCuPoEtjcDFcWtoA__" },
                { "session_key", "2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026" }
            };
            var expectedSignature = "1d95fa4b3dfa5b26c01c8ac8676d80b8";

            var signature = FacebookSession.GenerateSessionSignature(secret, dictionary);

            Assert.Equal(expectedSignature, signature);
        }
        /// <summary>
        /// Authenticate user with Facebook.
        /// </summary>
        /// <param name="email">Email.</param>
        /// <param name="password">Password.</param>
        /// <returns>Facebook session.</returns>
        public FacebookSession Authenticate()
        {
            var userToken = GetUserAccessToken (_email, _password);
            if(string.IsNullOrEmpty (userToken))
            {
                return null;
            }

            var userId = GetUserId (userToken);
            if(string.IsNullOrEmpty (userId))
            {
                return null;
            }

            var facebookToken = new FacebookSession (userToken, userId);
            return facebookToken;
        }
Exemple #27
0
        public FacebookAccount()
        {
            SessionInfo info = ReadSessionInfo();

            if (info != null)
            {
                facebookSession = new FacebookSession(api_key, info);
                try {
                    /* This basically functions like a ping to ensure the
                     * session is still valid:
                     */
                    facebookSession.HasAppPermission("offline_access");
                    connected = true;
                } catch (FacebookException) {
                    connected = false;
                }
            }
        }
Exemple #28
0
        /*perform the Authentication
         * and request read permissions
         * for the user's profile and other data,
         * and to navigate to the LandingPage when the login has succeeded.
         */

        private async Task Authenticate()
        {
            string message = String.Empty;

            try
            {
                session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");

                App.AccessToken = session.AccessToken;
                App.FacebookId  = session.FacebookId;
                Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/EditProfilePage.xaml?msg=" + App.FacebookId, UriKind.Relative)));
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                MessageBox.Show(message);
            }
        }
        private async System.Threading.Tasks.Task Authenticate()
        {
            while (session == null)
            {
                string message;
                try
                {
                    session = await App.FacebookSessionClient.LoginAsync("email,publish_checkins");
                    message = "You are now logged in";
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                MessageBox.Show(message);
            }
        }
Exemple #30
0
            public static async Task <bool> canAuthenticate()
            {
                try
                {
                    FacebookSessionClient = new FacebookSessionClient(Main.FacebookAppId);
                    session = await FacebookSessionClient.LoginAsync("user_about_me,read_stream");

                    Main.AccessToken = session.AccessToken;
                    Main.FacebookId  = session.FacebookId;
                    return(true);
                }

                catch
                {
                    MessageBox.Show("No se pudo iniciar la sesion, intentalo de nuevo por favor");
                    session = new FacebookSession();
                    return(false);
                }
            }
        private async Task Authenticate(Action loginSuccessCallback)
        {
            //string message = String.Empty;
            try
            {
                session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
                App.AccessToken = session.AccessToken;
                App.FacebookId = session.FacebookId;

                //Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/HomePage.xaml", UriKind.Relative)));
                loginSuccessCallback();
            }
            catch (InvalidOperationException e)
            {
                App.AccessToken = String.Empty;
                //message = "Login failed! Exception details: " + e.Message;
                //MessageBox.Show(message);
            }
        }
        public async System.Threading.Tasks.Task authenticate()
        {
            while (user == null)
            {
                try
                {
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);

                    fbSession = await App.FacebookSessionClient.LoginAsync("publish_stream,friends_about_me");

                    var     fbclient = new FacebookClient(fbSession.AccessToken);
                    dynamic fbUser   = await fbclient.GetTaskAsync("me");
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        public async System.Threading.Tasks.Task authenticate(string companyName, string companyEmail)
        {
            while (user == null)
            {
                try
                {
                    //log in to azure
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);

                    //log in to fb graph to get extra details
                    fbSession = await App.FacebookSessionClient.LoginAsync("publish_stream,friends_about_me");

                    var     fbclient = new FacebookClient(fbSession.AccessToken);
                    dynamic fbUser   = await fbclient.GetTaskAsync("me");

                    //add details to view model
                    UserProfileModel userProfile = new UserProfileModel();
                    userProfile.CompanyGuid   = functions.CreateGuid();
                    userProfile.companyName   = companyName;
                    userProfile.companyEmail  = companyEmail;
                    userProfile.UserGuid      = functions.CreateGuid();
                    userProfile.name          = fbUser.name;
                    userProfile.profilePicUrl = formatProfileImageUrl(fbSession.FacebookId);

                    //save to phone iso storage as json string
                    App.Setting.UserProfile = JsonConvert.SerializeObject(userProfile);
                    App.Setting.CompanyGuid = userProfile.CompanyGuid;

                    //save fb info
                    App.FacebookId          = fbSession.FacebookId;
                    App.FaceBookAccessToken = fbSession.AccessToken;

                    //set logged in to true
                    App.Setting.LoggedIn = true;
                }
                catch (InvalidOperationException)
                {
                }
                catch (Exception)
                {
                }
            }
        }
        private async Task Authenticate()
        {
            string message = String.Empty;

            try
            {
                session = await App.FacebookSessionClient.LoginAsync("email,user_about_me,read_stream");

                App.AccessToken = session.AccessToken;
                App.FacebookId  = session.FacebookId;

                LoadUserInfo();
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                MessageBox.Show(message);
            }
        }
        private async System.Threading.Tasks.Task Authenticate()
        {
            while (session == null)
            {
                string message;
                try
                {
                    session = await App.FacebookSessionClient.LoginAsync("publish_checkins,manage_notifications");

                    message = "You are now logged in";
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                MessageBox.Show(message);
            }
        }
        /// <summary>
        /// Maps a deep link Uri to a navigation within this application
        /// </summary>
        /// <param name="uri">Deep link Uri to map</param>
        /// <returns>Navigation Uri within this app</returns>
        public override Uri MapUri(Uri uri)
        {
            bool response = Task.Run(() => AppAuthenticationHelper.IsFacebookLoginResponse(uri)).Result;

            // if URI is a facebook login response, handle the deep link (once per invocation)
            if (response)
            {
                FacebookSession session = new FacebookSession();

                try
                {
                    session.ParseQueryString(HttpUtility.UrlDecode(uri.ToString()));

                    // Handle success case

                    // do something with the custom state parameter
                    if (session.State != "custom_state_string")
                    {
                        MessageBox.Show("Unexpected state: " + session.State);
                    }
                    else
                    {
                        // save the token and continue (token is retrieved and used when the app is lauched)
                        SessionStorage.Save(session);
                    }
                }
                catch (Facebook.FacebookOAuthException exc)
                {
                    if (!this.facebookLoginHandled)
                    {
                        // Handle error case
                        MessageBox.Show("Not signed in: " + exc.Message);

                        this.facebookLoginHandled = true;
                    }
                }

                return(new Uri("/MainPage.xaml", UriKind.Relative));
            }

            // by default, navigate to the requested uri
            return(uri);
        }
Exemple #37
0
        private async Task Authenticate()
        {
            string message = String.Empty;

            try
            {
                session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
                App.AccessToken = session.AccessToken;
                App.FacebookId = session.FacebookId;

                var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
                var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    Frame.Navigate(typeof(LandingPage));
            });
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
               // MessageBox.Show(message);
            }
        }
Exemple #38
0
 public Me(long uid, FacebookSession session)
     : base(uid, session)
 {
 }
Exemple #39
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            var fbEmailFile = @"../../facebook.email.dontcommit";
            var fbPasswordFile = @"../../facebook.pw.dontcommit";
            var fbAuthInfoFile = @"../../facebook.auth.dontcommit";
            var tndrAuthInfoFile = @"../../tinder.auth.dontcommit";
            var fbEmailAddress = File.ReadAllText (fbEmailFile);
            var fbPassword = File.ReadAllText (fbPasswordFile);
            var recommendationsFolderPath = "nyc_recommendations";
            var nopeFolderPath = "nope";
            var yesFolderPath = "yes";
            var startTime = DateTime.Now;
            var runForTimeSpan = new TimeSpan (4, 0, 0);
            var hitCountDictionaryFile = DateTime.Now.ToString ("MM.dd.yyyy.hh.mm.ss") + "_hitcountdict.dontcommit.txt";

            var recsIntervalRandomizer = new Random ();
            var recsIntervalTimeSpanMininum = new TimeSpan (0, 0, 1, 0);
            var recsIntervalTimeSpanMaximum = new TimeSpan (0, 0, 2, 0);

            var totalRecommendations = 0.0;
            var hitCountDictionary = new Dictionary<string, int> ();
            var disposables = new List<IDisposable> ();

            var jsonSerializer = new NewtonsoftJsonSerializer ();

            var webDriverFactory = new PhantomJSWebDriverFactory ();
            var webDriverForFacebookAuthenticator = webDriverFactory.CreateWebDriver ();
            disposables.Add (webDriverForFacebookAuthenticator);

            Console.Clear ();

            try
            {
                FacebookSession fbSession = null;

                if(File.Exists (fbAuthInfoFile))
                {
                    var fbAuthInfo = File.ReadAllLines (fbAuthInfoFile);
                    if(fbAuthInfo.Any ())
                    {
                        var fbAccessToken = fbAuthInfo[0];
                        var fbId = fbAuthInfo[1];
                        fbSession = new FacebookSession (fbAccessToken, fbId);
                    }
                }
                if(fbSession != null)
                {
                    Console.WriteLine ("Using previous Facebook session authentication.");
                }
                else
                {
                    Console.WriteLine ("Reauthenticating with Facebook...");
                    var fbAuthenticator = new SeleniumFacebookAuthenticator (webDriverForFacebookAuthenticator, fbEmailAddress, fbPassword);
                    fbSession = fbAuthenticator.Authenticate ();
                }
                if(fbSession != null)
                {
                    Console.WriteLine ("Authenticated with Facebook: '{0}'.", fbSession);
                    File.WriteAllLines (fbAuthInfoFile, new string[] { fbSession.AccessToken, fbSession.Id });
                }
                else
                {
                    Console.WriteLine ("Authentication with Facebook failed.");
                    if(File.Exists (fbAuthInfoFile))
                    {
                        File.Delete (fbAuthInfoFile);
                    }
                    goto end;
                }

                string tndrAccessToken = null;
                TndrClient tndrClient = null;

                if(File.Exists (tndrAuthInfoFile))
                {
                    var tndrAuthInfo = File.ReadAllLines (tndrAuthInfoFile);
                    if(tndrAuthInfoFile.Any ())
                    {
                        tndrAccessToken = tndrAuthInfo[0];
                    }
                }
                if(tndrAccessToken != null)
                {
                    Console.WriteLine ("Using previous Tinder session authentication.");
                    tndrClient = new TndrClient (tndrAccessToken);
                    try
                    {
                        var tndrUpdatesResponse = tndrClient.GetUpdates ();
                        if(tndrUpdatesResponse == null || tndrUpdatesResponse.LastActiveDate == null)
                        {
                            tndrAccessToken = null;
                        }
                    }
                    catch
                    {
                        tndrAccessToken = null;
                    }
                }
                if(tndrAccessToken == null)
                {
                    Console.WriteLine ("Reauthenticating with Tinder using current FacebookSession...");
                    var tndrAuthenticationResponse = TndrClient.Authenticate (fbSession);
                    if(tndrAuthenticationResponse != null)
                    {
                        tndrAccessToken = tndrAuthenticationResponse.AccessToken;
                    }
                }
                if(tndrAccessToken != null)
                {
                    Console.WriteLine ("Authenticated with Tinder: '{0}'.", tndrAccessToken);
                    File.WriteAllLines (tndrAuthInfoFile, new string[] { tndrAccessToken });
                    tndrClient = new TndrClient (tndrAccessToken);
                }
                else
                {
                    Console.WriteLine ("Authentication with Tinder failed.");
                    if(File.Exists (tndrAuthInfoFile))
                    {
                        File.Delete (tndrAuthInfoFile);
                    }
                    if(File.Exists (fbAuthInfoFile))
                    {
                        File.Delete (fbAuthInfoFile);
                    }
                    goto end;
                }

                var webClient = new WebClient ();
                disposables.Add (webClient);
                //IWebDriver photoWebDriver = null;
                while((DateTime.Now - startTime) < runForTimeSpan)
                {
                    var tndrUpdatesResponse = tndrClient.GetUpdates ();
                    if(tndrUpdatesResponse.Matches != null)
                    {
                        Console.WriteLine ("Tinder matches: {0}.", tndrUpdatesResponse.Matches.Count ());
                    }

                    var tndrReccomendationsResponse = tndrClient.GetRecommendations ();
                    if(tndrReccomendationsResponse.StatusCode != 200)
                    {
                        Console.WriteLine ("No Tinder recommendations available or requesting too fast.");
                    }
                    else
                    {
                        if(tndrReccomendationsResponse.Recommendations.Any (r => r.TinderId.StartsWith ("tinder_rate_limited_id")))
                        {
                            Console.WriteLine ("Tinder Rate Limit Reached");
                            goto end;
                        }

                        totalRecommendations += tndrReccomendationsResponse.Recommendations.Count ();
                        Console.WriteLine ("Tinder recommendations: {0}.", tndrReccomendationsResponse.Recommendations.Count ());

                        if(tndrReccomendationsResponse.Recommendations.Any ())
                        {
                            //try
                            //{
                            //	var urlTest = photoWebDriver.Url;
                            //}
                            //catch
                            //{
                            //	photoWebDriver = new FirefoxDriver ();
                            //	webDrivers.Add (photoWebDriver);
                            //}

                            foreach(var tndrRecommendation in tndrReccomendationsResponse.Recommendations)
                            {
                                if(hitCountDictionary.ContainsKey (tndrRecommendation.TinderId))
                                {
                                    hitCountDictionary[tndrRecommendation.TinderId]++;
                                }
                                else
                                {
                                    hitCountDictionary[tndrRecommendation.TinderId] = 1;
                                }

                                //photoWebDriver.Url = tndrRecommendation.Photos.First ().Url;
                                //photoWebDriver.Navigate ();
                                //photoWebDriver.FindElement (By.TagName ("body")).SendKeys (Keys.Command + "t");

                                var recommendationFolderPath = Path.Combine (recommendationsFolderPath, tndrRecommendation.TinderId);
                                var nopeRecommendationFolderPath = Path.Combine (nopeFolderPath, tndrRecommendation.TinderId);
                                var yesRecommendationFolderPath = Path.Combine (yesFolderPath, tndrRecommendation.TinderId);

                                if(!Directory.Exists (recommendationFolderPath) && !Directory.Exists (nopeRecommendationFolderPath) && !Directory.Exists (yesRecommendationFolderPath))
                                {
                                    Console.WriteLine ("\tNEW=> Name: {0, -20} Age: {1, -10} Recommended {2} time(s).", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, hitCountDictionary[tndrRecommendation.TinderId]);

                                    Directory.CreateDirectory (recommendationFolderPath);
                                    Directory.CreateDirectory (Path.Combine (recommendationFolderPath, "photos"));
                                    var recommendationFile = Path.Combine (recommendationFolderPath, string.Format ("{0}_{1}_{2}.txt", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, tndrRecommendation.TinderId));
                                    File.WriteAllText (recommendationFile, jsonSerializer.Serialize (tndrRecommendation, indented: true));

                                    foreach(var photo in tndrRecommendation.Photos)
                                    {
                                        //Console.WriteLine ("\t\tPhoto: {0}", photo.Url);

                                        var photoUri = new Uri (photo.Url);
                                        var photoFileName = Path.GetFileName (photoUri.AbsoluteUri);
                                        var photoLocalFilePath = Path.Combine (recommendationFolderPath, "photos", photoFileName);
                                        {
                                            try
                                            {
                                                webClient.DownloadFile (photoUri.ToString (), photoLocalFilePath);
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Console.WriteLine ("\tOLD=> Name: {0, -20} Age: {1, -10} Recommended {2} time(s).", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, hitCountDictionary[tndrRecommendation.TinderId]);
                                }
                            }

                            try
                            {
                                var jsonHitCountDictionary = jsonSerializer.Serialize (hitCountDictionary.OrderByDescending (h => h.Value), true);
                                File.WriteAllText (Path.Combine (recommendationsFolderPath, hitCountDictionaryFile), jsonHitCountDictionary);
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            Console.WriteLine ("No recommendations provided.");
                        }
                    }

                    var average = hitCountDictionary.Average (x => x.Value);
                    Console.WriteLine ("Top 20 Hits:");
                    foreach(var hitCountEntry in hitCountDictionary.OrderByDescending (h => h.Value).Take (20))
                    {
                        Console.WriteLine ("\tId: {0}\tTotal Hits: {1} ({2:P2})\tLiked You: {3:P2}", hitCountEntry.Key, hitCountEntry.Value, (hitCountEntry.Value / totalRecommendations), (1 - (average / hitCountEntry.Value)));
                    }

                    Console.WriteLine ("Time left {0}...", runForTimeSpan - (DateTime.Now - startTime));
                    TimeSpan timeLapsed;
                    var sleepForMs = recsIntervalRandomizer.Next (Convert.ToInt32 (recsIntervalTimeSpanMininum.TotalMilliseconds), Convert.ToInt32 (recsIntervalTimeSpanMaximum.TotalMilliseconds));
                    var sleepForTimeSpan = TimeSpan.FromMilliseconds (sleepForMs);
                    var sleepStart = DateTime.Now;
                    while((timeLapsed = DateTime.Now - sleepStart) < sleepForTimeSpan)
                    {
                        Console.WriteLine ("Sleeping for {0} {1}", (sleepForTimeSpan - timeLapsed), GenerateProgressBar (timeLapsed.TotalMilliseconds, sleepForTimeSpan.TotalMilliseconds));

                        if(Console.KeyAvailable)
                        {
                            if(Console.ReadKey (true).Key == ConsoleKey.Escape)
                            {
                                Console.WriteLine ("\nExiting Tndr tester...");
                                goto end;
                            }
                        }

                        Console.CursorTop = Console.CursorTop - 1;
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine (ex);
            }
            finally
            {
                foreach(var webDriver in disposables)
                {
                    webDriver.Dispose ();
                }
            }
            end:
            Console.WriteLine ("Ran for {0}.", (DateTime.Now - startTime));
            Console.WriteLine ("Press enter to quit.");
            Console.ReadLine ();
        }
Exemple #40
0
 public Friend(long UId, FacebookSession session)
 {
     this.UId = UId;
     this.Session = session;
 }
        internal async Task<FacebookSession> LoginAsync(string permissions, bool force)
        {
            if (this.LoginInProgress)
            {
                throw new InvalidOperationException("Login in progress.");
            }

            this.LoginInProgress = true;
            try
            {
                var session = FacebookSessionCacheProvider.Current.GetSessionData();
                if (session == null)
                {
                    // Authenticate
                    var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None);

                    FacebookClient client = new FacebookClient(authResult.AccessToken);
                    var parameters = new Dictionary<string, object>();
                    parameters["fields"] = "id";

                    var result = await client.GetTaskAsync("me", parameters);
                    var dict = (IDictionary<string, object>)result;

                    session = new FacebookSession
                    {
                        AccessToken = authResult.AccessToken,
                        Expires = authResult.Expires,
                        FacebookId = (string)dict["id"],
                    };
                  
                }
                else
                {
                    // Check if we are requesting new permissions
                    bool newPermissions = false;
                    if (!string.IsNullOrEmpty(permissions))
                    {
                        var p = permissions.Split(',');
                        newPermissions = session.CurrentPermissions.Join(p, s1 => s1, s2 => s2, (s1, s2) => s1).Count() != p.Length;
                    }

                    // Prompt OAuth dialog if force renew is true or
                    // if new permissions are requested or 
                    // if the access token is expired.
                    if (force || newPermissions || session.Expires <= DateTime.UtcNow)
                    {
                        var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None);
                        if (authResult != null)
                        {
                            session.AccessToken = authResult.AccessToken;
                            session.Expires = authResult.Expires;
                        }
                    }
                }

                // Set the current known permissions
                if (!string.IsNullOrEmpty(permissions))
                {
                    var p = permissions.Split(',');
                    session.CurrentPermissions = session.CurrentPermissions.Union(p).ToList();
                }

                // Save session data
                FacebookSessionCacheProvider.Current.SaveSessionData(session);
                this.CurrentSession = session;
            }
            finally
            {
                this.LoginInProgress = false;
            }

            return this.CurrentSession;
        }
 public void Logout()
 {
     try
     {
         FacebookSessionCacheProvider.Current.DeleteSessionData();
     }
     finally
     {
         this.CurrentSession = null;
     }
 }
        public void login(string scope)
        {
            try
            {
                if (FacebookSessionClient != null && FacebookSessionClient.LoginInProgress)
                {
                    this.DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(async () =>
                {
                    session = await FacebookSessionClient.LoginAsync(scope);
                    if (string.IsNullOrEmpty(session.AccessToken))
                        this.DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                    else
                    {
                        RemoveLocalData();
                        Settings.Add("fb_access_token", session.AccessToken);
                        Settings.Add("fb_access_expires", session.Expires);
                        Settings.Save();

                        this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, this.getResponse()));
                    }
                });
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
            }
        }
 private async Task PerformLogin()
 {
     session = await FacebookSessionClient.LoginAsync();
 }