public override void LoadView()
		{
			base.LoadView();
			
			_AuthClient = new FacebookOAuthClient() {
				AppId = AppId,
				AppSecret = AppSecret,
			};
			
			var loginParms = new Dictionary<string, object>();
			loginParms["response_type"] = "code";
			
			if(string.IsNullOrWhiteSpace(ExtendedPermissions) == false) {
				loginParms["scope"] = ExtendedPermissions;	
			}
			
			
			
		}
Пример #2
0
        /// <summary>
        /// Gets the canvas login url
        /// </summary>
        /// <param name="returnUrlPath">
        /// The return Url Path.
        /// </param>
        /// <param name="cancelUrlPath">
        /// The cancel Url Path.
        /// </param>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="loginParameters">
        /// The parameters.
        /// </param>
        /// <returns>
        /// Returns the login url.
        /// </returns>
        public Uri GetLoginUrl(string returnUrlPath, string cancelUrlPath, string state, IDictionary<string, object> loginParameters)
        {
            Contract.Ensures(Contract.Result<Uri>() != null);

            var oauth = new FacebookOAuthClient
            {
                AppId = _settings.AppId
            };

            var oauthJsonState = PrepareCanvasLoginUrlOAuthState(returnUrlPath, cancelUrlPath, state, loginParameters);

            var oauthState = FacebookUtils.Base64UrlEncode(Encoding.UTF8.GetBytes(oauthJsonState.ToString()));
            var mergedLoginParameters = FacebookUtils.Merge(loginParameters, null);
            mergedLoginParameters["state"] = oauthState;

            var appPath = _httpRequest.ApplicationPath;
            if (appPath != "/")
            {
                appPath = string.Concat(appPath, "/");
            }

            string redirectRoot = RedirectPath;

            var uriBuilder = new UriBuilder(CurrentCanvasUrl)
            {
                Path = string.Concat(appPath, redirectRoot),
                Query = string.Empty
            };

            oauth.RedirectUri = uriBuilder.Uri;

            var loginUrl = oauth.GetLoginUrl(mergedLoginParameters);
            return loginUrl;
        }
        private void c_webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            c_CurrentUrl.Text = e.Uri.AbsoluteUri;
            // 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 (FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication.
                if (oauthResult.IsSuccess)
                {
                    var oauthClient = new FacebookOAuthClient {
                        AppId = AppId, AppSecret = AppSecret
                    };

                    // we got the code here
                    var code = oauthResult.Code;
                    oauthClient.ExchangeCodeForAccessTokenCompleted +=
                        (o, args) =>
                    {
                        // make sure to check that no error has occurred.
                        if (args.Error != null)
                        {
                            // make sure to access ui stuffs on the correct thread.
                            Dispatcher.BeginInvoke(
                                () =>
                            {
                                MessageBox.Show(args.Error.Message);
                                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                            });
                        }
                        else
                        {
                            var result      = (IDictionary <string, object>)args.GetResultData();
                            var accessToken = (string)result["access_token"];

                            // make sure to access ui stuffs on the correct thread.
                            Dispatcher.BeginInvoke(() => NavigationService.Navigate(
                                                       new Uri(string.Format("/FacebookInfoPage.xaml?access_token={0}&n={1}&p={2}",
                                                                             accessToken,
                                                                             note,
                                                                             url
                                                                             ),
                                                               UriKind.Relative)));
                        }
                    };

                    oauthClient.ExchangeCodeForAccessTokenAsync(code);
                }
                else
                {
                    // the user clicked don't allow or some other error occurred.
                    MessageBox.Show(oauthResult.ErrorDescription);
                }
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
            }
        }
Пример #4
0
 internal FacebookEventsRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }
Пример #5
0
        public virtual ActionResult FacebookLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback         = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias    = Request.QueryString["propertyAlias"];

            if (AuthState != null)
            {
                var stateValue = Session[$"MvcForum_{AuthState}"] as string[];
                if (stateValue != null && stateValue.Length == 3)
                {
                    Callback         = stateValue[0];
                    ContentTypeAlias = stateValue[1];
                    PropertyAlias    = stateValue[2];
                }
            }

            // Get the prevalue options
            if (string.IsNullOrWhiteSpace(ForumConfiguration.Instance.FacebookAppId) ||
                string.IsNullOrWhiteSpace(ForumConfiguration.Instance.FacebookAppSecret))
            {
                resultMessage.Message     = "You need to add the Facebook app credentials";
                resultMessage.MessageType = GenericMessages.danger;
            }
            else
            {
                // Settings valid move on
                // Configure the OAuth client based on the options of the prevalue options
                var client = new FacebookOAuthClient
                {
                    AppId       = ForumConfiguration.Instance.FacebookAppId,
                    AppSecret   = ForumConfiguration.Instance.FacebookAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session[$"MvcForum_{AuthState}"] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Check whether an error response was received from Facebook
                if (AuthError != null)
                {
                    Session.Remove($"MvcForum_{AuthState}");
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.danger;
                }

                // Redirect the user to the Facebook login dialog
                if (AuthCode == null)
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session[$"MvcForum_{state}"] = new[] { Callback, ContentTypeAlias, PropertyAlias };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends"

                    // Redirect the user
                    return(Redirect(url));
                }

                // Exchange the authorization code for a user access token
                var userAccessToken = string.Empty;
                try
                {
                    userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to acquire access token<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                }

                try
                {
                    if (string.IsNullOrWhiteSpace(resultMessage.Message))
                    {
                        // Initialize the Facebook service (no calls are made here)
                        var service = FacebookService.CreateFromAccessToken(userAccessToken);

                        // Declare the options for the call to the API
                        var options = new FacebookGetUserOptions
                        {
                            Identifier = "me",
                            Fields     = new[] { "id", "name", "email", "first_name", "last_name", "gender" }
                        };

                        var user = service.Users.GetUser(options);

                        // Try to get the email - Some FB accounts have protected passwords
                        var email = user.Body.Email;
                        if (string.IsNullOrWhiteSpace(email))
                        {
                            resultMessage.Message =
                                LocalizationService.GetResourceString("Members.UnableToGetEmailAddress");
                            resultMessage.MessageType = GenericMessages.danger;
                            ShowMessage(resultMessage);
                            return(RedirectToAction("LogOn", "Members"));
                        }

                        // First see if this user has registered already - Use email address
                        var userExists = MembershipService.GetUserByEmail(email);

                        if (userExists != null)
                        {
                            try
                            {
                                // Users already exists, so log them in
                                FormsAuthentication.SetAuthCookie(userExists.UserName, true);
                                resultMessage.Message =
                                    LocalizationService.GetResourceString("Members.NowLoggedIn");
                                resultMessage.MessageType = GenericMessages.success;
                                ShowMessage(resultMessage);
                                return(RedirectToAction("Index", "Home"));
                            }
                            catch (Exception ex)
                            {
                                LoggingService.Error(ex);
                            }
                        }
                        else
                        {
                            // Not registered already so register them
                            var viewModel = new MemberAddViewModel
                            {
                                Email           = email,
                                LoginType       = LoginType.Facebook,
                                Password        = StringUtils.RandomString(8),
                                UserName        = user.Body.Name,
                                UserAccessToken = userAccessToken
                            };

                            // Get the image and save it
                            var getImageUrl = $"http://graph.facebook.com/{user.Body.Id}/picture?type=square";
                            viewModel.SocialProfileImageUrl = getImageUrl;

                            // Large size photo https://graph.facebook.com/{facebookId}/picture?type=large
                            // Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal
                            // Small size photo https://graph.facebook.com/{facebookId}/picture?type=small
                            // Square photo https://graph.facebook.com/{facebookId}/picture?type=square

                            // Store the viewModel in TempData - Which we'll use in the register logic
                            TempData[Constants.MemberRegisterViewModel] = viewModel;

                            return(RedirectToAction("SocialLoginValidator", "Members"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = $"Unable to get user information<br/>{ex.Message}";
                    resultMessage.MessageType = GenericMessages.danger;
                    LoggingService.Error(ex);
                }
            }

            ShowMessage(resultMessage);
            return(RedirectToAction("LogOn", "Members"));
        }
Пример #6
0
        public ActionResult Callback()
        {
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };
            FacebookOAuthResult oAuthResult;

            if (oauthClient.TryParseResult(Request.Url, out oAuthResult))
            {
                if (oAuthResult.IsSuccess)
                {
                    if (!string.IsNullOrWhiteSpace(oAuthResult.Code))
                    {
                        string returnUrl  = "";
                        string domainName = null;
                        string planName   = null;
                        string affiliate  = null;
                        var    state      = new CallbackState();
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(oAuthResult.State))
                            {
                                state = (CallbackState)JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(OAuthFacebook.Base64UrlDecode(oAuthResult.State)), typeof(CallbackState));
                                // TODO: at the moment only check if there is token. Hack Bug
                                // we do this because for logins we are saving token in a separate domain
                                if (!string.IsNullOrEmpty(state.csrf_token) && !ValidateFacebookCsrfToken(state.csrf_token))
                                {
                                    // someone tried to hack the site.
                                    return(RedirectToAction("Index", "Error"));
                                }

                                if (!string.IsNullOrEmpty(state.return_url))
                                {
                                    returnUrl = state.return_url;
                                }

                                if (!string.IsNullOrEmpty(state.domain_name))
                                {
                                    domainName = state.domain_name;
                                }

                                if (!string.IsNullOrEmpty(state.plan_name))
                                {
                                    planName = state.plan_name;
                                }

                                if (!string.IsNullOrEmpty(state.affiliate))
                                {
                                    affiliate = state.affiliate;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Syslog.Write(ex);
                            // catch incase user puts his own state,
                            // Base64UrlDecode might throw exception if the value is not properly encoded.
                            return(RedirectToAction("Index", "Error"));
                        }

                        try
                        {
                            var token         = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code);
                            var token_key     = (string)token["access_token"];
                            var token_expires = token.ContainsKey("expires") ? token["expires"].ToString() : "";
                            if (state.isRegistration && !string.IsNullOrEmpty(domainName))
                            {
                                var errorMessage = ProcessSuccesfulFacebookRegistrationCallback(token, domainName, planName, affiliate);

                                if (!string.IsNullOrEmpty(errorMessage))
                                {
                                    return(Redirect(ErrorHelper.CreateErrorPage(errorMessage, "/register/" + planName)));
                                }
                            }

                            if (state.isLogin || state.isLink)
                            {
                                var returnUri       = new Uri(returnUrl);
                                var queryParameters = HttpUtility.ParseQueryString(returnUri.Query);
                                queryParameters.Add("token", token_key);
                                queryParameters.Add("expires", token_expires);
                                returnUrl = string.Format("{0}://{1}{2}{3}", returnUri.Scheme, returnUri.Host, returnUri.LocalPath, queryParameters.ToQueryString(true));
                            }

                            if (state.requestPageTokens && !string.IsNullOrEmpty(state.domain_name))
                            {
                                // obtain any other account tokens
                                var facebook = new FacebookService(token_key);
                                var accounts = facebook.Account.GetAccountTokens("me");
                                if (accounts != null && accounts.data != null)
                                {
                                    var domain =
                                        repository.GetSubDomains().SingleOrDefault(x => x.name == state.domain_name);
                                    if (domain != null)
                                    {
                                        foreach (var entry in accounts.data)
                                        {
                                            if (entry.name != null)
                                            {
                                                var ftoken = new facebook_token
                                                {
                                                    pageid      = entry.id,
                                                    subdomainid = domain.id,
                                                    accesstoken = entry.access_token,
                                                    name        = entry.name,
                                                    category    = entry.category,
                                                    flags       = (int)FacebookTokenSettings.NONE
                                                };
                                                repository.AddUpdateFacebookToken(ftoken);
                                            }
                                        }
                                    }
                                }
                            }

                            // save any changes
                            repository.Save();

                            // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it
                            if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.Contains(GeneralConstants.SUBDOMAIN_HOST))
                            {
                                return(Redirect(returnUrl));
                            }
                        }
                        catch (FacebookApiException ex)
                        {
                            // catch incase the user entered dummy code or the code expired.
                            Syslog.Write(ex);
                        }
                    }
                }
                else
                {
                    switch (oAuthResult.ErrorReason)
                    {
                    // permission request denied
                    case "user_denied":
                        return(RedirectToAction("NoAuth", "Error"));

                    default:
                        Syslog.Write(string.Format("Unhandled Facebook OAUTH {0} - {1}", oAuthResult.ErrorReason, oAuthResult.ErrorDescription));
                        break;
                    }
                }
            }
            return(RedirectToAction("Index", "Error"));
        }
Пример #7
0
 internal FacebookFeedRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }
Пример #8
0
 internal FacebookMethodsRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }
Пример #9
0
 public FacebookApplication()
 {
     Client = new FacebookOAuthClient();
 }
 internal FacebookApplicationsRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }
Пример #11
0
        public ActionResult FacebookCallback()
        {
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };

            FacebookOAuthResult oAuthResult;

            if (oauthClient.TryParseResult(Request.Url, out oAuthResult))
            {
                if (oAuthResult.IsSuccess)
                {
                    if (!string.IsNullOrWhiteSpace(oAuthResult.Code))
                    {
                        string returnUrl = null;
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(oAuthResult.State))
                            {
                                dynamic state = JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State)));
                                if (!state.ContainsKey("csrf_token") || !ValidateFacebookCsrfToken(state.csrf_token))
                                {
                                    // someone tried to hack the site.
                                    return(RedirectToAction("Index", "Home"));
                                }

                                if (state.ContainsKey("return_url") && !string.IsNullOrWhiteSpace(state.return_url))
                                {
                                    returnUrl = Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State));
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // catch incase user puts his own state,
                            // Base64UrlDecode might throw exception if the value is not properly encoded.
                            return(RedirectToAction("Index", "Home"));
                        }

                        try
                        {
                            var result = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code);

                            ProcessSuccesfulFacebookCallback(result);

                            // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it
                            if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                            {
                                return(Redirect(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "Facebook"));
                            }
                        }
                        catch (FacebookApiException)
                        {
                            // catch incase the user entered dummy code or the code expired.
                        }
                    }

                    return(Redirect("~/"));
                }

                return(View("FacebookCallbackError", oAuthResult));
            }

            return(Redirect("~/"));
        }
        public ActionResult FacebookLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback         = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias    = Request.QueryString["propertyAlias"];

            if (AuthState != null)
            {
                var stateValue = Session["Dialogue_" + AuthState] as string[];
                if (stateValue != null && stateValue.Length == 3)
                {
                    Callback         = stateValue[0];
                    ContentTypeAlias = stateValue[1];
                    PropertyAlias    = stateValue[2];
                }
            }

            // Get the prevalue options
            if (string.IsNullOrEmpty(Dialogue.Settings().FacebookAppId) || string.IsNullOrEmpty(Dialogue.Settings().FacebookAppSecret))
            {
                resultMessage.Message     = "You need to add the Facebook app credentials";
                resultMessage.MessageType = GenericMessages.Danger;
            }
            else
            {
                // Settings valid move on
                // Configure the OAuth client based on the options of the prevalue options
                var client = new FacebookOAuthClient
                {
                    AppId       = Dialogue.Settings().FacebookAppId,
                    AppSecret   = Dialogue.Settings().FacebookAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session["Dialogue_" + AuthState] == null)
                {
                    resultMessage.Message     = "Session Expired";
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Check whether an error response was received from Facebook
                if (AuthError != null)
                {
                    resultMessage.Message     = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Redirect the user to the Facebook login dialog
                if (AuthCode == null)
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["Dialogue_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends"

                    // Redirect the user
                    return(Redirect(url));
                }

                // Exchange the authorization code for a user access token
                var userAccessToken = string.Empty;
                try
                {
                    userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = string.Format("Unable to acquire access token<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message))
                    {
                        // Initialize the Facebook service (no calls are made here)
                        var service = FacebookService.CreateFromAccessToken(userAccessToken);

                        var fbOptions = new FacebookGetUserOptions("me");
                        fbOptions.Fields.Add(new FacebookField("email"));
                        fbOptions.Fields.Add(new FacebookField("name"));
                        var user = service.Users.GetUser(fbOptions);

                        // Try to get the email - Some FB accounts have protected passwords
                        var email = user.Body.Email;
                        // TODO - Ignore if no email - Have to check PropMemberFacebookAccessToken has a value
                        // TODO - and the me.UserName is there to match existing logged in accounts


                        // First see if this user has registered already - Use email address
                        using (UnitOfWorkManager.NewUnitOfWork())
                        {
                            var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(email);

                            if (userExists != null)
                            {
                                // Update access token
                                userExists.Properties[AppConstants.PropMemberFacebookAccessToken].Value = userAccessToken;
                                AppHelpers.UmbServices().MemberService.Save(userExists);

                                // Users already exists, so log them in
                                FormsAuthentication.SetAuthCookie(userExists.Username, true);
                                resultMessage.Message     = Lang("Members.NowLoggedIn");
                                resultMessage.MessageType = GenericMessages.Success;
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new RegisterViewModel
                                {
                                    Email           = email,
                                    LoginType       = LoginType.Facebook,
                                    Password        = AppHelpers.RandomString(8),
                                    UserName        = user.Body.Name,
                                    UserAccessToken = userAccessToken
                                };

                                // Get the image and save it
                                var getImageUrl = string.Format("http://graph.facebook.com/{0}/picture?type=square", user.Body.Id);
                                viewModel.SocialProfileImageUrl = getImageUrl;

                                //Large size photo https://graph.facebook.com/{facebookId}/picture?type=large
                                //Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal
                                //Small size photo https://graph.facebook.com/{facebookId}/picture?type=small
                                //Square photo https://graph.facebook.com/{facebookId}/picture?type=square

                                return(RedirectToAction("MemberRegisterLogic", "DialogueLoginRegisterSurface", viewModel));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message     = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.Danger;
                }
            }

            ShowMessage(resultMessage);
            return(RedirectToUmbracoPage(Dialogue.Settings().ForumId));
        }
 internal FacebookPhotosRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }
Пример #14
0
 internal FacebookDebugRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }
 internal FacebookAlbumsRawEndpoint(FacebookOAuthClient client)
 {
     Client = client;
 }