public static IEnumerable <FacebookPost> GetLastestFacebookPosts(object OAuthValue) { // Get the OAuth information stored in the property FacebookOAuthData facebook = OAuthValue as FacebookOAuthData; // Check whether the OAuth data is valid if (facebook != null && facebook.IsValid) { // Gets an instance of FacebookService based on the OAuth data FacebookService service = facebook.GetService(); // Get information about the authenticated user FacebookUser me = service.Users.GetUser("me").Body; // Gets the most recent posts of the authenticated user (me) FacebookPostsResponse response = service.Posts.GetPosts(new FacebookGetPostsOptions { Identifier = "me", Fields = "id,name,message,story,created_time,picture,link,description,status_type,type,likes", Limit = 25 }); return(response.Body.Data.ToList()); } return(null); }
protected void Page_Load(object sender, EventArgs e) { Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; if (AuthState != null) { string[] stateValue = Session["Skybrud.Social_" + AuthState] as string[]; if (stateValue != null && stateValue.Length == 3) { Callback = stateValue[0]; ContentTypeAlias = stateValue[1]; PropertyAlias = stateValue[2]; } } // Get the prevalue options FacebookOAuthPreValueOptions options = FacebookOAuthPreValueOptions.Get(ContentTypeAlias, PropertyAlias); if (!options.IsValid) { Content.Text = "Hold on now! The options of the underlying prevalue editor isn't valid."; return; } // Configure the OAuth client based on the options of the prevalue options FacebookOAuthClient client = new FacebookOAuthClient { AppId = options.AppId, AppSecret = options.AppSecret, RedirectUri = options.RedirectUri }; // Session expired? if (AuthState != null && Session["Skybrud.Social_" + AuthState] == null) { Content.Text = "<div class=\"error\">Session expired?</div>"; return; } // Check whether an error response was received from Facebook if (AuthError != null) { Content.Text = "<div class=\"error\">Error: " + AuthErrorDescription + "</div>"; return; } // Redirect the user to the Facebook login dialog if (AuthCode == null) { // Generate a new unique/random state string state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["Skybrud.Social_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias }; // Construct the authorization URL string url = client.GetAuthorizationUrl(state, options.Scope); // Redirect the user Response.Redirect(url); return; } // Exchange the authorization code for a user access token string userAccessToken; try { userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to acquire access token</b><br />" + ex.Message + "</div>"; return; } try { // Initialize the Facebook service (no calls are made here) FacebookService service = FacebookService.CreateFromAccessToken(userAccessToken); // Make a call to the Facebook API to get information about the user FacebookUser me = service.Users.GetUser("me").Body; //Get accounts information. Only works with "manage_pages" permission FacebookAccountsResponse response = null; if (options.Scope.Contains("manage_pages")) { response = service.Accounts.GetAccounts(); } // Get debug information about the access token FacebookDebugToken debugToken = null; try { debugToken = service.Debug.DebugToken(userAccessToken).Body; } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to acquire debug token. Are you a developer?</b><br />" + ex.Message + "</div>"; } Content.Text += "<p>Hi <strong>" + me.Name + "</strong></p>"; Content.Text += "<p>Please wait while you're being redirected...</p>"; // Set the callback data FacebookOAuthData data = new FacebookOAuthData { Id = me.Id, Name = me.Name, AccessToken = userAccessToken, ExpiresAt = DateTime.Now.AddDays(60), BusinessPages = new FacebookBusinessPageData[0], SelectedBusinessPage = null }; // Set the the business pages (if available) if (response != null) { data.BusinessPages = response.Body.Data.Select(ac => new FacebookBusinessPageData { Id = ac.Id, Name = ac.Name, AccessToken = ac.AccessToken }).ToArray(); } // Update the OAuth data with information from the debug token if (debugToken != null) { data.ExpiresAt = (debugToken.Data.ExpiresAt ?? DateTime.Now.AddDays(60));//NULL when manage_pages permission is granted data.Scope = ( from scope in debugToken.Data.Scopes select scope.Name ).ToArray(); } // Update the UI and close the popup window Page.ClientScript.RegisterClientScriptBlock(GetType(), "callback", String.Format( "self.opener." + Callback + "({0}); window.close();", data.Serialize()//Save JSON data through callback parameter ), true); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to get user information</b><br />" + ex.Message + "</div>"; } }
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); // Hack to get email // Get the raw string and parse it // we use this to get items manually including the email var response = service.Methods.Raw.Me(); var obj = JsonObject.ParseJson(response); // Make a call to the Facebook API to get information about the user var me = service.Methods.Me(); // Get debug information about the access token //var debug = service.Methods.DebugToken(userAccessToken); // Set the callback data var data = new FacebookOAuthData { Id = me.Id, Name = me.Name ?? me.UserName, AccessToken = userAccessToken, //ExpiresAt = debug.ExpiresAt == null ? default(DateTime) : debug.ExpiresAt.Value, //Scope = debug.Scopes }; // Try to get the email - Some FB accounts have protected passwords var email = obj.GetString("email"); if (!string.IsNullOrEmpty(email)) { data.Email = email; } // First see if this user has registered already - Use email address using (UnitOfWorkManager.NewUnitOfWork()) { // 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 var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(data.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 = data.Email, LoginType = LoginType.Facebook, Password = AppHelpers.RandomString(8), UserName = data.Name, UserAccessToken = userAccessToken }; // Get the image and save it var getImageUrl = string.Format("http://graph.facebook.com/{0}/picture?type=square", me.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)); }
protected void Page_Load(object sender, EventArgs e) { Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; if (AuthState != null) { string[] stateValue = Session["Skybrud.Social_" + AuthState] as string[]; if (stateValue != null && stateValue.Length == 3) { Callback = stateValue[0]; ContentTypeAlias = stateValue[1]; PropertyAlias = stateValue[2]; } } // Get the prevalue options FacebookOAuthPreValueOptions options = FacebookOAuthPreValueOptions.Get(ContentTypeAlias, PropertyAlias); if (!options.IsValid) { Content.Text = "Hold on now! The options of the underlying prevalue editor isn't valid."; return; } // Configure the OAuth client based on the options of the prevalue options FacebookOAuthClient client = new FacebookOAuthClient { AppId = options.AppId, AppSecret = options.AppSecret, RedirectUri = options.RedirectUri }; // Session expired? if (AuthState != null && Session["Skybrud.Social_" + AuthState] == null) { Content.Text = "<div class=\"error\">Session expired?</div>"; return; } // Check whether an error response was received from Facebook if (AuthError != null) { Content.Text = "<div class=\"error\">Error: " + AuthErrorDescription + "</div>"; return; } // Redirect the user to the Facebook login dialog if (AuthCode == null) { // Generate a new unique/random state string state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["Skybrud.Social_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias }; // Construct the authorization URL string url = client.GetAuthorizationUrl(state, "read_stream", "user_status", "user_about_me", "user_photos"); // Redirect the user Response.Redirect(url); return; } // Exchange the authorization code for a user access token string userAccessToken; try { userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to acquire access token</b><br />" + ex.Message + "</div>"; return; } try { // Initialize the Facebook service (no calls are made here) FacebookService service = FacebookService.CreateFromAccessToken(userAccessToken); // Make a call to the Facebook API to get information about the user FacebookUser me = service.Users.GetUser("me").Body; // Get debug information about the access token FacebookDebugToken debug = service.Debug.DebugToken(userAccessToken).Body; Content.Text += "<p>Hi <strong>" + me.Name + "</strong></p>"; Content.Text += "<p>Please wait while you're being redirected...</p>"; // Set the callback data FacebookOAuthData data = new FacebookOAuthData { Id = me.Id, Name = me.Name, AccessToken = userAccessToken, ExpiresAt = debug.Data.ExpiresAt == null ? default(DateTime) : debug.Data.ExpiresAt.Value, Scope = ( from scope in debug.Data.Scopes select scope.Name ).ToArray() }; // Update the UI and close the popup window Page.ClientScript.RegisterClientScriptBlock(GetType(), "callback", String.Format( "self.opener." + Callback + "({0}); window.close();", data.Serialize() ), true); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to get user information</b><br />" + ex.Message + "</div>"; return; } }
public FacebookService Service(FacebookOAuthData authenticationData) { return(FacebookService.CreateFromAccessToken(authenticationData.AccessToken)); }