public void IsSuccessShouldBeTrue()
            {
                var parameters = new Dictionary<string, object>
                                 {
                                     { "code", "dummycode" }
                                 };

                var result = new FacebookOAuthResult(parameters);

                Assert.True(result.IsSuccess);
            }
            public void IsSuccessShouldBeFalse()
            {
                var parameters = new Dictionary<string, object>
                                 {
                                     { "error_reason", "dummy error reason" }
                                 };

                var result = new FacebookOAuthResult(parameters);

                Assert.False(result.IsSuccess);
            }
            public void CodeShouldBeTheOneSpecifiedInDictionary()
            {
                var code = "2.XeyH7lWz33itx1R86_uBeg__.3600.1294930800-100001327642026|t8SsfSR2XI6yhBAkhX95J7p9hJ0";
                var parameters = new Dictionary<string, object>
                                 {
                                     { "code", code }
                                 };

                var result = new FacebookOAuthResult(parameters);

                Assert.Equal(code, result.Code);
            }
Beispiel #4
0
 private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
 {
     FacebookOAuthResult oauthResult;
     if (FacebookOAuthResult.TryParse(e.Url, out oauthResult))
     {
         this.FacebookOAuthResult = oauthResult;
         this.DialogResult = oauthResult.IsSuccess ? DialogResult.OK : DialogResult.No;
     }
     else
     {
         this.FacebookOAuthResult = null;
     }
 }
Beispiel #5
0
        public static FacebookOAuthResult <FacebookFriends> GetUserFriends(string facebookId, string accessToken)
        {
            FacebookOAuthResult <FacebookFriends> result = new FacebookOAuthResult <FacebookFriends>();
            IStopwatch watch = MonitoringTimers.Current.GetNewStopwatch(true);

            result.Data = new FacebookFriends();
            try
            {
                result.Data.Next = facebookId + "/friends?format=json&limit=5000";
                do
                {
                    dynamic         d          = GraphAPI.Get(result.Data.Next, accessToken);
                    FacebookFriends pageResult = ConvertToFacebookSocialGraph(d);

                    if (pageResult.Friends != null && pageResult.Friends.Count > 0)
                    {
                        result.Data.Friends.AddRange(pageResult.Friends);
                        result.Data.Next = pageResult.Next;

                        if (pageResult.Friends.Count < 5000)
                        {
                            result.Data.Next = null;
                        }
                    }
                    else
                    {
                        result.Data.Next = null;
                    }
                }while (!string.IsNullOrEmpty(result.Data.Next));
            }
            catch (FacebookOAuthException)
            {
                result.SetHasExpired();
            }
            catch (Exception e)
            {
                Logger.Current.Error("SocialGraph.GetFriendIds", "Could not update a Facebook user's social graph", e);
                result.HasError = true;
            }
            finally
            {
                //TODO : ajouter un compteur sur le nombre d'amis récupérés
                watch.Stop();
                MonitoringTimers.Current.AddTime(Counters.Facebook_GetUserFriends, watch);
            }

            return(result);
        }
Beispiel #6
0
 private void TakeLoggedInAction(FacebookOAuthResult facebookOAuthResult)
 {
     if (facebookOAuthResult == null)
     {
         MessageBox.Show("Cancelled!");
         return;
     }
     if (facebookOAuthResult.IsSuccess)
     {
         SD_AccesTokenMemoEdit.Text = facebookOAuthResult.AccessToken;
     }
     else
     {
         MessageBox.Show(facebookOAuthResult.ErrorDescription);
     }
 }
        private void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            var url = e.Url;
            FacebookOAuthResult oauthResult;

            if (cl.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication
                OAuthResult  = oauthResult;
                DialogResult = OAuthResult.IsSuccess ? DialogResult.OK : DialogResult.No;
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
                OAuthResult = null;
            }
        }
Beispiel #8
0
        private bool DisplayAppropriateMessage(FacebookOAuthResult facebookOAuthResult)
        {
            if (facebookOAuthResult != null)
            {
                if (facebookOAuthResult.IsSuccess)
                {
                    this.fb = new FacebookClient(facebookOAuthResult.AccessToken);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(false);
        }
Beispiel #9
0
        public string GetAccessToken(FacebookOAuthResult oauthResult)
        {
            var     client = new FacebookClient();
            dynamic result = null;


            result = client.Get("/oauth/access_token",
                                new
            {
                client_id     = Settings.FacebookAppKey,
                client_secret = Settings.FacebookAppSecret,
                redirect_uri  = "https://www.facebook.com/connect/login_success.html",
                code          = oauthResult.Code,
            });

            return(result.access_token);
        }
        public async void LoginSucceeded(FacebookOAuthResult oauthResult)
        {
            // Hide the Web browser
            ShowBrowser = false;
            // Grab the access token (necessary for further operations)
            var token = GetAccessToken(oauthResult);

            Token = token;
            // Grab user information
            dynamic user = await GetUser(token);

            // Update the user interface
            UserName    = String.Format("{0} ", user.first_name);
            Email       = String.Format("{0} ", user.email);
            UserPicture = user.picture;
            Id          = user.id;
            IsLogged    = true;
        }
        private void DisplayAppropriateMessage(FacebookOAuthResult facebookOAuthResult)
        {
            if (facebookOAuthResult != null)
            {
                if (facebookOAuthResult.IsSuccess)
                {
                    _accessToken = facebookOAuthResult.AccessToken;
                    var fb = new FacebookClient(facebookOAuthResult.AccessToken);

                    fbAnalyze = new Analyze(fb);
                    fbAnalyze.Show();
                }
                else
                {
                    MessageBox.Show(facebookOAuthResult.ErrorDescription);
                }
            }
        }
        /// <summary>
        /// 成功登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            FacebookOAuthResult oauthResult;

            if (_fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication
                FacebookOAuthResult = oauthResult;
                ButtonStateNext    |= WizardButtonState.Enabled;
                ParentWizardForm.UpdateWizardForm(this);
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
                FacebookOAuthResult = null;
                ButtonStateNext     = WizardButtonState.Visible;
            }
        }
Beispiel #13
0
        private void WebView1_LoadCompleted(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult oauthResult;

            if (!FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
            {
                return;
            }

            if (oauthResult.IsSuccess)
            {
                LoginSucceeded(oauthResult.AccessToken);
            }
            else
            {
                // user cancelled.
            }
        }
Beispiel #14
0
        private static FacebookOAuthResult GetAccessTokenForCode(string code, string appId, string appSecret, string redirectUri)
        {
            var fb = new FacebookClient();

            var parameters = new Dictionary <string, object>();

            parameters["client_id"]     = appId;
            parameters["client_secret"] = appSecret;
            parameters["code"]          = code;
            parameters["redirect_uri"]  = redirectUri;

            var data = (IDictionary <string, object>)fb.Post(RequestAccessTokenUrl, parameters);

            //Parse results to FacebookOAuthResult object
            string responseData             = string.Format("access_token={0}&expires_in={1}", data["access_token"], data["expires"]);
            FacebookOAuthResult oauthResult = fb.ParseOAuthCallbackUrl(new Uri(redirectUri + "#" + responseData, UriKind.Absolute));

            return(oauthResult);
        }
        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            // whenever the browser navigates to a new url, try parsing the url.
            // the url may be the result of OAuth 2.0 authentication.

            FacebookOAuthResult oauthResult;

            if (_fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication
                FacebookOAuthResult = oauthResult;
                DialogResult        = FacebookOAuthResult.IsSuccess ? DialogResult.OK : DialogResult.No;
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
                FacebookOAuthResult = null;
            }
        }
Beispiel #16
0
        public async Task <bool> ProcessFbOathResult(FacebookOAuthResult oauthResult)
        {
            var resultProcess = false;
            var accessToken   = oauthResult.AccessToken;

            App.ViewModel.UserPreference.AccessKey = accessToken;
            var fbS = new FacebookClient(accessToken);

            fbS.GetCompleted += (o, res) =>
            {
                if (res.Error != null)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        gridFBLoggedIn.Visibility =
                            Visibility.Collapsed;
                        FaceBookLoginPage.Visibility =
                            Visibility.Collapsed;
                        LinkButton.Visibility = Visibility.Visible;
                    });

                    return;
                }

                var result = (IDictionary <string, object>)res.GetResultData();
                App.ViewModel.UserPreference.FbUserId = (string)result["id"];
                App.ViewModel.UserPreference.Name     = (string)result["name"];
                App.ViewModel.LoadData(true);
                App.ViewModel.SaveSettings();
                Dispatcher.BeginInvoke(() =>
                {
                    facebookImage.Source =
                        App.ViewModel.UserPreference.UserImage;
                    name.Text = App.ViewModel.UserPreference.Name;
                });
                resultProcess = true;
            };

            await fbS.GetTaskAsync("me");

            return(resultProcess);
        }
        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            FacebookOAuthResult result = null;

            try
            {
                if (e.Url.ToString().Contains("access_token"))
                {
                    result = _client.ParseOAuthCallbackUrl(new Uri(e.Url.ToString()));
                }
                if (result != null && result.IsSuccess)
                {
                    _accessToken = result.AccessToken;
                }
            }
            catch (Exception ex)
            {
                errorMessage.Text = ex.Message;
            }
        }
Beispiel #18
0
        //
        // GET: /Account/OAuth/

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

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    string redirectUrl = "http://" + Request.Url.Host + "/Account/OAuth/";
                    var    oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

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

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

                    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"));
        }
Beispiel #19
0
        private void DisplayAppropriateMessage(FacebookOAuthResult facebookOAuthResult)
        {
            if (facebookOAuthResult == null)
            {
                // most likely user closed the FacebookLoginDialog, so do nothing
                return;
            }

            if (facebookOAuthResult.IsSuccess)
            {
                // we got the access token
                var infoDialog = new Info(facebookOAuthResult.AccessToken);
                infoDialog.ShowDialog();
            }
            else
            {
                // for some reason we failed to get the access token.
                // most likely the user clicked don't allow
                MessageBox.Show(facebookOAuthResult.ErrorDescription);
            }
        }
Beispiel #20
0
        /// <summary>
        ///  Facebook authentication
        /// </summary>
        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    string url = string.Format(@"https://graph.facebook.com/oauth/access_token?client_id=146563355411375&client_secret=03232f1f920aec6f4e4600105f1dfba4&scope=publish_stream&grant_type=client_credentials&redirect_uri={0}", redirectUrl);

                    var request = (HttpWebRequest)WebRequest.Create(url);

                    var response    = (HttpWebResponse)request.GetResponse();
                    var reader      = new StreamReader(response.GetResponseStream());
                    var token       = reader.ReadToEnd();
                    var accessToken = token.Split('=')[1];

                    var expiresOn = DateTime.MaxValue;

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("drquipe");
                    string  facebookId = me.id;

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

                    FormsAuthentication.SetAuthCookie(facebookId, false);
                }

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


            return(RedirectToAction("Index", "Home"));
        }
        private void DisplayAppropriateMessage(FacebookOAuthResult facebookOAuthResult)
        {
            if (facebookOAuthResult != null)
            {
                if (facebookOAuthResult.IsSuccess)
                {
                    _accessToken = facebookOAuthResult.AccessToken;

                    var     client = new FacebookClient(facebookOAuthResult.AccessToken);
                    dynamic me     = client.Get("/me?fields=email");
                    string  email  = me.email;
                    string  fb_id  = me.id;
                    DBC     Con    = new DBC();
                    if (true == Con.search_by_mail(email, "Users"))
                    {
                        username = Con.get_username_from_DB(email);
                        password = Con.GetPassUserName(username);
                        Login nsession = new Login();
                        nsession.login_run(username, password, this, fb_id);

                        /*
                         * //logout from facebook//
                         * var webBrowser = new WebBrowser();
                         * var fb = new FacebookClient();
                         * var logouUrl = fb.GetLogoutUrl(new { access_token = _accessToken, next = "https://www.facebook.com/connect/login_success.html" });
                         * webBrowser.Navigate(logouUrl);
                         * //end logout//
                         */
                    }
                    else
                    {
                        MessageBox.Show("Error - User is not exict");
                    }
                }
                else
                {
                    MessageBox.Show(facebookOAuthResult.ErrorDescription);
                }
            }
        }
        private void webBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            Debug.WriteLine("webBrowser_Navigated: {0}", e.Uri);

            FacebookOAuthResult oauthResult;

            if (!FacebookOAuthResult.TryParse(e.Uri, out oauthResult) || !oauthResult.IsSuccess)
            {
                return;
            }

            var oauthClient = new FacebookOAuthClient {
                AppId = ApplicationID
            };

            oauthClient.AppSecret = ApplicationSecret;
            var code = oauthResult.Code;

            // アクセストークンを要求(非同期実行)
            oauthClient.ExchangeCodeForAccessTokenCompleted += oauthClient_ExchangeCodeForAccessTokenCompleted;
            oauthClient.ExchangeCodeForAccessTokenAsync(code);
        }
Beispiel #23
0
        private void LoadLastPostFromFB(FacebookOAuthResult facebookOAuthResult)
        {
            if (facebookOAuthResult == null)
            {
                // the user closed the FacebookLoginDialog, so do nothing.
                MessageBox.Show("Cancelled!");
                return;
            }

            // Even though facebookOAuthResult is not null, it could had been an
            // OAuth 2.0 error, so make sure to check IsSuccess property always.
            if (facebookOAuthResult.IsSuccess)
            {
                // since our respone_type in FacebookLoginDialog was token,
                // we got the access_token
                // The user now has successfully granted permission to our app.

                //get last user post
                var client = new FacebookClient();

                client.AccessToken = facebookOAuthResult.AccessToken;
                dynamic me = client.Get("me/?fields=id, posts.limit(1)");

                string   message = me.posts["data"][0]["message"];
                DateTime date    = DateTime.Parse(me.posts["data"][0]["created_time"]);

                string accountId = me.id;

                //MessageBox.Show($"{message}\n\nCreated time: {date}");
                this.txtComment.Text      = $"{message}\r\nSource: Facebook account id={accountId}";
                this.dateTimePicker.Value = date;
            }
            else
            {
                // for some reason we failed to get the access token.
                // most likely the user clicked don't allow.
                MessageBox.Show(facebookOAuthResult.ErrorDescription);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Renew a user's Facebook access_token using the "code" parameter passed by Facebook
        /// </summary>
        public static FacebookOAuthResult <string> ExchangeCodeForAccessToken(string applicationId, string secretKey, string code, out DateTime expires)
        {
            FacebookOAuthResult <string> result = new FacebookOAuthResult <string>();

            expires = DateTime.MinValue;

            string url = string.Format(RenewAccessTokenURL,
                                       applicationId,
                                       secretKey,
                                       code);

            try
            {
                Logger.Current.Debug("ExchangeCodeForAccessToken", "Getting new access_token", url);

                string s = GraphAPI.GetRaw(url);
                if (s.StartsWith("access_token="))
                {
                    string[] split            = s.Split('&');
                    string   accessToken      = split[0].Substring(split[0].IndexOf('=') + 1);
                    double   expiresInSeconds = double.Parse(split[1].Substring(split[1].IndexOf('=') + 1));
                    expires = DateTime.UtcNow.AddSeconds(expiresInSeconds);

                    result.Data = accessToken;
                }
            }
            catch (FacebookOAuthException fbe)
            {
                Logger.Current.Error("ExchangeCodeForAccessToken", "Error getting new access_token", fbe, url);

                result.SetHasExpired();
            }
            catch (Exception e)
            {
                Logger.Current.Error("Authentication.RenewAccessToken", "Could not renew the user's access_token", e);
            }

            return(result);
        }
Beispiel #25
0
        private async void AccessToken(FacebookOAuthResult obj)
        {
            GraphApi api = new GraphApi(obj.AccessToken);
            //Declaro los parametros que me traigo desde facebook id , name , birthday , email , picture
            FacebookUser user = await api.Explorer <FacebookUser>("/me?fields=id,name,birthday,email,picture{url}");

            UsuarioJson User = await con.ConsultaExistenciaUsuario(user.id, user.id);

            if (User.Usuario == null)
            {
                // Si usuario es null entonces me registro
                JsonResponseInsert Result = await con.RegistraNuevoUsuario(user.id, user.id, user.name, user.email);

                //si el registro retorna null es porque no hay conexion
                if (Result.Transaccion != null)
                {
                    if (Result.Transaccion.Operacion.Respuesta != "NO")
                    {
                        // si es distinto a NO se registro bien asi que lo envio a la pagina principal
                        Aplicacion.App.Current.MainPage = new PaginaNavegadora();
                    }
                    else
                    {
                        // si retorna NO es por bd (error o condicionales no cumplidas )
                        // popup error de registro
                    }
                }
                else
                {
                    //Pupup Error de Registro atravez de facebook
                }
            }
            else
            {
                //el usuario ya existe en BD y facebook ya valido password asi que le doy acceso
                Aplicacion.App.Current.MainPage = new PaginaNavegadora();
            }
        }
        /// <summary>
        /// Log in to facebook.
        /// </summary>
        private void LoginToFacebook()
        {
            if (QvFacebookOAuthResult == null || !QvFacebookOAuthResult.IsSuccess)
            {
                // Show the facebook login dialog
                var facebookLoginDialog = new FacebookLoginDialog();
                facebookLoginDialog.ShowDialog();

                QvFacebookOAuthResult = facebookLoginDialog.FacebookOAuthResult;

                if (QvFacebookOAuthResult == null)
                {
                    QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, "Init() - Facebook Login error. The user may have canceled the operation or there could be network errors.");
                    // Tell QlikView that the login has failed
                    throw new Exception("Facebook login error. The user may have canceled the operation or there could be network errors.");
                }
                if (!QvFacebookOAuthResult.IsSuccess)
                {
                    QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, String.Format("Init() - Facebook Login error: {0}", QvFacebookOAuthResult.ErrorDescription));
                    // Tell QlikView that the login has failed
                    throw new Exception(QvFacebookOAuthResult.ErrorDescription);
                }
            }
        }
Beispiel #27
0
        public static FacebookOAuthResult <dynamic> GetUserProfileFieldSync(string facebookId, string fields, string accessToken)
        {
            FacebookOAuthResult <dynamic> result = new FacebookOAuthResult <dynamic>();

            IStopwatch watch = MonitoringTimers.Current.GetNewStopwatch(true);

            try
            {
                dynamic d = GraphAPI.Get(
                    string.Format("{0}?fields={1}",
                                  facebookId,
                                  fields), accessToken);

                result.Data = d;
            }
            catch (FacebookOAuthException)
            {
                result.SetHasExpired();
            }
            catch (Exception e)
            {
                Logger.Current.Error("Profile.GetUserProfileFieldSync", "Could not retrieve Facebook user's profile field", e, fields);
            }
            finally
            {
                watch.Stop();
                var counter = Counters.Facebook_GetUserProfile;
                if (fields.Contains("likes"))
                {
                    counter = Counters.Facebook_GetUserLikesAndProfile;
                }
                MonitoringTimers.Current.AddTime(counter, watch);
            }

            return(result);
        }
Beispiel #28
0
        // For Facebook
        private void DisplayAppropriateMessage(FacebookOAuthResult facebookOAuthResult)
        {
            // If OAuth Doesnt return Null
            if (facebookOAuthResult != null)
            {
                // If OAuth Authentication was successful
                if (facebookOAuthResult.IsSuccess)
                {
                    // Instatiates the AccessToken Variable and creates a FB Client Object
                    _accessToken = facebookOAuthResult.AccessToken;
                    var fb = new FacebookClient(facebookOAuthResult.AccessToken);



                    _accessToken = new AccessTokenCheck(_accessToken).getExtendedToken;
                    File.WriteAllText(@"AccessTokenStorage\accessToken.txt", _accessToken);
                }
                else
                {
                    // If OAuth fails, a message box will return a short error description.
                    MessageBox.Show(facebookOAuthResult.ErrorDescription);
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Awaits permission of facebook user and will issue authenication cookie if successful.
        /// </summary>
        /// <param name="code">Facebook authorization code</param>
        /// <param name="state">Redirect url</param>
        private void ProcessOAuth(string code, string state)
        {
            FacebookOAuthResult oAuthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oAuthResult) && oAuthResult.IsSuccess)
            {
                try
                {
                    // create client to read response
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current)
                    {
                        RedirectUri = new Uri(GetOAuthRedirectUrl())
                    };
                    oAuthClient.AppId     = PageInstance.Site.FacebookAppId;
                    oAuthClient.AppSecret = PageInstance.Site.FacebookAppSecret;
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me");
                    string         facebookId = "FACEBOOK_" + me.id.ToString();

                    // query for matching id in the user table
                    UserService userService = new UserService();
                    var         user        = userService.GetByUserName(facebookId);

                    // if not user was found see if we can find a match in the person table
                    if (user == null)
                    {
                        try
                        {
                            // determine if we can find a match and if so add an user login record

                            // get properties from Facebook dynamic object
                            string lastName  = me.last_name.ToString();
                            string firstName = me.first_name.ToString();
                            string email     = me.email.ToString();

                            var personService = new PersonService();
                            var person        = personService.Queryable().FirstOrDefault(u => u.LastName == lastName && (u.GivenName == firstName || u.NickName == firstName) && u.Email == email);

                            if (person != null)
                            {
                                // since we have the data enter the birthday from Facebook to the db if we don't have it yet
                                DateTime birthdate = Convert.ToDateTime(me.birthday.ToString());

                                if (person.BirthDay == null)
                                {
                                    person.BirthDate = birthdate;
                                    personService.Save(person, person.Id);
                                }
                            }
                            else
                            {
                                person           = new Person();
                                person.GivenName = me.first_name.ToString();
                                person.LastName  = me.last_name.ToString();
                                person.Email     = me.email.ToString();

                                if (me.gender.ToString() == "male")
                                {
                                    person.Gender = Gender.Male;
                                }
                                if (me.gender.ToString() == "female")
                                {
                                    person.Gender = Gender.Female;
                                }

                                person.BirthDate = Convert.ToDateTime(me.birthday.ToString());

                                personService.Add(person, null);
                                personService.Save(person, null);
                            }

                            user = userService.Create(person, AuthenticationType.Facebook, facebookId, "fb", true, person.Id);
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                            // TODO: probably should report something...
                        }

                        // TODO: Show label indicating inability to find user corresponding to facebook id
                    }

                    // update user record noting the login datetime
                    user.LastLoginDate    = DateTime.Now;
                    user.LastActivityDate = DateTime.Now;
                    userService.Save(user, user.PersonId);

                    FormsAuthentication.SetAuthCookie(user.UserName, false);
                    Session["UserIsAuthenticated"] = true;

                    if (state != null)
                    {
                        Response.Redirect(state);
                    }
                }
                catch (FacebookOAuthException oae)
                {
                    string msg = oae.Message;
                    // TODO: Add error handeling
                    // Error validating verification code. (usually from wrong return url very picky with formatting)
                    // Error validating client secret.
                    // Error validating application.
                }
            }
        }
            public void AccessTokenShouldBeNull()
            {
                var result = new FacebookOAuthResult(new Dictionary<string, object>());

                Assert.Null(result.AccessToken);
            }
            public void ErrorDescriptionShouldBeNull()
            {
                var result = new FacebookOAuthResult(new Dictionary<string, object>());

                Assert.Null(result.ErrorDescription);
            }
Beispiel #32
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params)
        {
            var builder = new UriBuilder(context.Request.GetUrlRewriter()) {Query = "p=" + context.Request["p"]};
            var oauth = new FacebookOAuthClient
            {
                AppId = KeyStorage.Get("facebookAppID"),
                AppSecret = KeyStorage.Get("facebookAppSecret"),
                RedirectUri = builder.Uri
            };
            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result))
            {
                if (result.IsSuccess)
                {
                    var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code);
                    var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"]));
                    using (var response = request.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            var graph = FacebookGraph.Deserialize(responseStream);
                            var profile = ProfileFromFacebook(graph);
                            return profile;
                        }
                    }
                }
                return LoginProfile.FromError(new Exception(result.ErrorReason));
            }
            //Maybe we didn't query
            var extendedPermissions = new[] { "email", "user_about_me" };
            var parameters = new Dictionary<string, object>
                                 {
                                     { "display", "popup" }
                                 };

            if (extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }
            var loginUrl = oauth.GetLoginUrl(parameters);
            context.Response.Redirect(loginUrl.ToString());
            return LoginProfile.FromError(new Exception("Failed to login with facebook"));




            //var client = new FacebookClient
            //                 {
            //                     ClientIdentifier = KeyStorage.Get("facebookAppID"),
            //                     ClientSecret = KeyStorage.Get("facebookAppSecret"),
            //                 };
            //try
            //{
            //    IAuthorizationState authorization = client.ProcessUserAuthorization(new HttpRequestInfo(context.Request));
            //    if (authorization == null)
            //    {
            //        // Kick off authorization request
            //        var scope = new List<string>()
            //                    {
            //                        "email,user_about_me",
            //                    };
            //        client.RequestUserAuthorization(scope, null, null);
            //    }
            //    else
            //    {
            //        var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
            //        using (var response = request.GetResponse())
            //        {
            //            if (response != null)
            //                using (var responseStream = response.GetResponseStream())
            //                {
            //                    var graph = FacebookGraph.Deserialize(responseStream);
            //                    var profile = ProfileFromFacebook(graph);
            //                    return profile;
            //                }
            //        }
            //    }
            //}
            //catch (ProtocolException e)
            //{
            //    if (e.InnerException is WebException)
            //    {
            //        //Read stream
            //        var responce =
            //            new StreamReader((e.InnerException as WebException).Response.GetResponseStream()).ReadToEnd();
            //    }
            //    throw;
            //}

        }
        protected Uri GetUrl(HttpContextBase context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Request == null)
            {
                throw new Exception("context.Request is null");
            }

            // TODO: need unit tests for this method, might as well need to refactor this method.
            UriBuilder redirectUriBuilder;

            if (!context.Request.QueryString.AllKeys.Contains("state"))
            {
                // todo: better to redirect to the default canvas page.
                return(new Uri("http://www.facebook.com"));
            }

            // if state is present.
            var state = Encoding.UTF8.GetString(FacebookWebUtils.Base64UrlDecode(context.Request.QueryString["state"]));
            var json  = (IDictionary <string, object>)JsonSerializer.Current.DeserializeObject(state);

            // make it one letter character so more info can fit in.
            // r -> return_url_path (full uri)
            // c -> cancel_url_path (full uri)
            // s -> user_state
            FacebookOAuthResult oauthResult;

            if (!FacebookOAuthResult.TryParse(context.Request.Url, out oauthResult))
            {
                // todo: better to redirect to the default canvas page.
                return(new Uri("http://www.facebook.com"));
            }

            if (oauthResult.IsSuccess)
            {
                var returnUrl = json["r"].ToString();

                redirectUriBuilder = new UriBuilder(returnUrl);

                if (returnUrl.Contains("?"))
                {
                    // incase return url path contains querystrings.
                    var returnUrlParts = returnUrl.Split('?');
                    if (returnUrlParts.Length == 2 && !string.IsNullOrEmpty(returnUrlParts[1]))
                    {
                        var queryStrings = FacebookUtils.ParseUrlQueryString(returnUrlParts[1]);

                        if (queryStrings.ContainsKey("error_reason"))
                        {
                            // remove oauth stuffs.
                            if (queryStrings.ContainsKey("error_reason"))
                            {
                                queryStrings.Remove("error_reason");
                            }

                            if (queryStrings.ContainsKey("error"))
                            {
                                queryStrings.Remove("error");
                            }

                            if (queryStrings.ContainsKey("error_description"))
                            {
                                queryStrings.Remove("error_description");
                            }

                            redirectUriBuilder.Query = FacebookUtils.ToJsonQueryString(queryStrings);
                        }
                    }
                }
            }
            else
            {
                if (!json.ContainsKey("c"))
                {
                    // there is no cancel url path
                    redirectUriBuilder = new UriBuilder("http://facebook.com");
                }
                else
                {
                    var cancelUrl = json["c"].ToString();

                    IDictionary <string, object> cancelUrlQueryStrings = new Dictionary <string, object>
                    {
                        { "error_reason", context.Request.QueryString["error_reason"] },
                        { "error", context.Request.QueryString["error"] },
                        { "error_description", context.Request.QueryString["error_description"] }
                    };

                    if (cancelUrl.Contains("?"))
                    {
                        // incase cancel url path contains querystrings.
                        var cancelUrlParts = cancelUrl.Split('?');
                        if (cancelUrlParts.Length == 2 && !string.IsNullOrEmpty(cancelUrlParts[1]))
                        {
                            var queryStrings = FacebookUtils.ParseUrlQueryString(cancelUrlParts[1]);
                            cancelUrlQueryStrings = FacebookUtils.Merge(cancelUrlQueryStrings, queryStrings);
                        }
                    }

                    redirectUriBuilder = new UriBuilder(cancelUrl)
                    {
                        Query = FacebookUtils.ToJsonQueryString(cancelUrlQueryStrings)
                    };
                }
            }

            return(redirectUriBuilder.Uri);
        }
            public void CodeShouldBeNull()
            {
                var result = new FacebookOAuthResult(new Dictionary<string, object>());

                Assert.Null(result.Code);
            }
Beispiel #35
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);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);

                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

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

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

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

                    var user = Membership.GetUser(facebookId.ToString());

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

                    string      format   = "d";
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    DateTime    birthday = new DateTime();
                    try
                    {
                        birthday = DateTime.ParseExact(me.birthday, format, provider);
                    }
                    catch
                    {
                    }

                    if (user == null)
                    {
                        var u = Membership.CreateUser(facebookId.ToString(), Guid.NewGuid().ToString());
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Create((Guid)u.ProviderUserKey,
                                                 facebookId.ToString(),
                                                 (string)me.name,
                                                 Transfer.GetPictureUrl(facebookId.ToString()),
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }
                    else
                    {
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Update((Guid)user.ProviderUserKey,
                                                 (string)me.name,
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }

                    // 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"));
        }
            public void CodeShouldBeNull()
            {
                var result = new FacebookOAuthResult(new Dictionary <string, object>());

                Assert.Null(result.Code);
            }
            public void ErrorDescriptionShouldBeNull()
            {
                var result = new FacebookOAuthResult(new Dictionary <string, object>());

                Assert.Null(result.ErrorDescription);
            }
            public void AccessTokenShouldBeNull()
            {
                var result = new FacebookOAuthResult(new Dictionary <string, object>());

                Assert.Null(result.AccessToken);
            }
            public void CodeShouldBeTheOneSpecifiedInDictionary()
            {
                var parameters = new Dictionary<string, object>
                                {
                                    { "code", "code" },
                                    { "access_token", "accesstoken" }
                                };

                var result = new FacebookOAuthResult(parameters);

                Assert.Equal("code", result.Code);
            }