Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Expanding Facebook Scope from a Force.com Social Application
<apex:page controller="FriendsController">
<script src="https://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script>
// Get required permissions from the controller
var permissions = '{!permissions}';
var permlist = permissions.split(',');
var reqperms = '';
FB.init({appId: '{!appId}', xfbml: true, cookie: true});
// We are logged in, but we need getLoginStatus() to get the FB JS
// lib to pick up the access token
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// Check we have the permissions we want
FB.api('/me/permissions', function (response) {
for (var i = 0; i < permlist.length; i++) {
if (! response.data[0][permlist[i]]) {
if (reqperms !== '') {
reqperms += ',';
}
reqperms += permlist[i];
}
}
if (reqperms.length > 0) {
// We need some permissions - ask for them
FB.login(function(response) {
if (!response) {
alert('Error getting permission!');
} else {
location.reload(true);
}
}, {scope: reqperms});
}
});
} else if (response.status === 'not_authorized') {
// The user is logged in to Facebook,
// but has not authenticated the app
// We handle this in the controller
} else {
// The user isn't logged in to Facebook.
// We handle this in the controller
}
});
// Pop up a dialog to send a message to another user
var sendMessage = function(id) {
FB.ui({
method: 'send',
to: id,
name: 'Authentication Provider Test Portal',
link: 'https://authtest-developer-edition.na14.force.com/',
description: 'Come to the cool test portal today!'
});
};
</script>
<apex:pageMessages/>
<apex:pageBlock >
<apex:outputText >Controller says '{!data}'.</apex:outputText>
</apex:pageBlock>
<apex:pageBlock title="Facebook Friends in this Portal">
<apex:pageBlockTable value="{!friendsInPortal}" var="friend">
<apex:column width="70">
<apex:outputLink target="_new" value="https://www.facebook.com/{!friend.id}">
<img src="https://graph.facebook.com/{!friend.id}/picture?type=square"/>
</apex:outputLink>
</apex:column>
<apex:column headerValue="Name" style="vertical-align: middle;">
<!-- Link to each friend's Facebook page -->
<apex:outputLink target="_new" value="https://www.facebook.com/{!friend.id}">
{!friend.name}
</apex:outputLink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock title="All Facebook Friends">
<apex:pageBlockTable value="{!friends}" var="friend">
<apex:column width="70">
<apex:outputLink target="_new" value="https://www.facebook.com/{!friend.id}">
<img src="https://graph.facebook.com/{!friend.id}/picture?type=square"/>
</apex:outputLink>
</apex:column>
<apex:column width="140" headerValue="Name" style="vertical-align: middle;">
<!-- Link to each friend's Facebook page -->
<apex:outputLink target="_new" value="https://www.facebook.com/{!friend.id}">
{!friend.name}
</apex:outputLink>
</apex:column>
<apex:column style="vertical-align: middle;">
<!-- Link to each friend's Facebook page -->
<a href="#" onclick="sendMessage('{!friend.id}'); return false;">
Invite {!friend.first_name}
</a>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
public class FriendsController {
public List<FacebookUser> friends { get; set; }
public List<FacebookUser> friendsInPortal { get; set; }
public String data { get; set; }
public FriendsController() {
// Replace the ID in this call with the ID of your auth provider
String access_token = Auth.AuthToken.getAccessToken('0SOd0000000abcd', 'Facebook');
try {
// Get friends ID, name, first name via Graph API
Map<String,String> params = new Map<string,string>{'fields' => 'id,name,first_name'};
FacebookUsers friendsList = new FacebookUsers(access_token, 'me/friends', params);
friends = friendsList.data;
// Figure out which friends are in the portal
Map<String,FacebookUser> friendMap = new Map<String,FacebookUser>();
for (FacebookUser fbu : friends) {
friendMap.put(fbu.id, fbu);
}
List<User> users = [SELECT Facebook_ID__c FROM User WHERE Facebook_ID__c IN :friendMap.keySet()];
friendsInPortal = new List<FacebookUser>();
for (User u : users) {
friendsInPortal.add(friendMap.get(u.Facebook_ID__c));
}
// Get the authenticated user's profile and see if we can see the fields
// for which we requested permission
FacebookUser me = new FacebookUser(access_token, 'me');
data = 'Religion: ' + ((me.religion != null) ? me.religion : 'null');
data += ' / ';
data += 'Hometown: ' + ((me.hometown != null) ? me.hometown.name : 'null');
} catch (FacebookException fbe) {
// This can happen if the user revokes permissions for the app
// while they are in the portal...
data = '';
friends = new List<FacebookUser>();
friendsInPortal = new List<FacebookUser>();
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,
'Error accessing Facebook. Please logout of the portal and log back in.');
ApexPages.addMessage(myMsg);
}
}
public String getAppId() {
// Replace this with your auth provider's consumer key
return '123456789012345';
}
public String getPermissions() {
// FB permissions for the religion and hometown profile data
return 'user_religion_politics,user_hometown';
}
}
global class PortalHandler implements Auth.RegistrationHandler{
global User createUser(Id portalId, Auth.UserData data){
Account a = [SELECT Id FROM account WHERE name='sForce'];
Contact c = new Contact();
c.accountId = a.Id;
c.email = data.email;
c.firstName = data.firstName;
c.lastName = data.lastName;
insert(c);
User u = new User();
Profile p = [SELECT Id FROM profile WHERE name='High Volume Customer Portal'];
// Use incoming email for username, since we're creating a portal user
u.username = data.email;
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
u.Facebook_ID__c = data.identifier;
u.alias = (data.username != null) ? data.username : data.identifier;
if (u.alias.length() > 8) {
u.alias = u.alias.substring(0, 8);
}
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = 'UTF-8';
u.timeZoneSidKey = 'America/Los_Angeles';
u.profileId = p.Id;
u.contactId = c.Id;
System.debug('Returning new user record for '+data.username);
return u;
}
global void updateUser(Id userId, Id portalId, Auth.UserData data){
User u = new User(id=userId);
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
u.Facebook_ID__c = data.identifier;
System.debug('Updating user record for '+data.username);
update(u);
}
}
@sanjeevmehta
Copy link

sanjeevmehta commented Dec 4, 2012

Is it possible to use String access_token = Auth.AuthToken.getAccessToken('0SOd0000000abcd', 'Facebook'); in the Portal Handler.cls under createUser method?

I tried to access token in the AuthRegistration Handler class and it is returning null value (and as a result OAuth Exception).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment