Child pages
  • Log in with Facebook
Skip to end of metadata
Go to start of metadata

Facebook integration

Apstrata allows you to easily interact and integrate with Facebook's APIs by providing you with a native server-side scripting object: the apsdb.social.facebook object. Using the method exposed by this facebook object, you can implement authentication scenarios using your end user's Facebook credentials and invoke any Facebook graph API. Apstrata also provides you with utility scripts that you can deploy to your Apstrata application back-end, which will even facilitate more the integration of your application with Facebook.

Back to the map       Next station: post to wall

Example : sign in you users with Facebook

Asking a user to sign-in to an application using his Facebook - or other social network - credentials is a very common scenario. This is why we assume in this example that you decide to implement it as a feature of the cool mobile game app that you are currently developing.

Before we start digging into the code, let us just remember the Facebook OAuth authentication process:

  • Step 1: ask for authorization. A request is sent to Facebook along with a Facebook application id and secret, the authorization scope that is requested by the application (e.g. read the user's email address) and a callback URL. Facebook validates the requests and, if valid, returns an authorization URL to which the end user should be redirected.
  • Step 2: end user authenticates and approves. The end user enters his Facebook credentials and grant the application access to what was defined in the authorization scope. Once this step is successfully achieved, Facebook redirects the request initiator to the provided callback URL, passing a temporary code along with the callback. 
  • Step 3: get definitive token from Facebook. The code has to be sent again to Facebook in order to obtain a definitive authentication token.

So let us now see how steps 1 and 3 above are easily implemented using Apstrata server-side scripts.

 

Step 1

Step 1: requestFacebookAuthURL
 <script>
	<scriptACL>
		<execute>anonymous</execute> <!-- anyone can call this script -->
		<read>nobody</read>
		<write>nobody</write>
	</scriptACL>
	<code>
		<![CDATA[
			
			try {
				// import the "common" script that contains shared methods and Facebook app id and secret
            	var common = apsdb.require("common");            
            	// Ask Facebook for an authorization URL
            	var response = apsdb.social.facebook.getRequestToken(common.facebookAppKey, common.facebookAppSecret, common.getCallbackUrl(apsdb), common.facebookScope, common.facebookStatus);                    
            	// Return the authorization URL 
				// (you can also redirect by replacing the below with apsdb.httpRedirect(response.result.authorizationUrl)
            	return response.result.authorizationUrl;
			}catch(exception) {
				JSON.stringify(exception);
			}
		]]>
	</code>
</script>

Step 3

Step 3: getFacebookAuthToken
 <script>
	<scriptACL>
		<execute>facebookadmin</execute> <!-- only this user (you need to create it in your user directory) can invoke this script -->
		<read>nobody</read>
		<write>nobody</write>
	</scriptACL>
	<code>
		<![CDATA[
		
		    try { 
		       
                // import the "common" script that contains shared methods and Facebook app id and secret
                var common = apsdb.require("common");                
                // retrieve the OAuth verifier sent by Facebook from the request, if any
                var code = request.parameters["code"];                
                // Retrieve the Apstrata authentication from the request to reuse it when building the callback URL
                var apstrataToken = request.parameters["apsdb.authToken"];                
                // build the callback URL expected by Facebook when asking for the definitive auth token
                var callbackUrl = common.getCallbackUrl(apsdb, apstrataToken);                    
                // Obtain a definitive access token from Facebook
                var response = apsdb.social.facebook.getAccessToken(common.facebookAppKey, common.facebookAppSecret, callbackUrl, code);	                    
                // Return the Facebook access token to the caller (only for the example)
                if (response.status.metadata =="success") {
                    return {
                        "status": "success",
                        "message": "congratulations, you successfully signed in with Facebook",
                        "facebookAuthToken": response.result.accessToken
                    }
                }else {
                    return response;
                }
            }catch(exception) {
                return JSON.stringify(exception);
            }
		]]>
	</code>
</script>

Common properties and functions

 Click here to see the common properties and functions script
<script>
	<scriptACL>
		<execute>nobody</execute>
		<read>nobody</read>
		<write>nobody</write>
	</scriptACL>
	<code>
		<![CDATA[
			
		// Your Apstrata application key (id)
		var apsrataAppKey = "EXAMPLE_O79301F690"		
		// The application id of the facebook application
		var facebookAppKey = "EXAMPLE_501463657349742";			
		// The application secret of the facebook application
        var facebookAppSecret = "EXAMPLE_g6642a9840862315fe1df883ff78463d";
        // The scope used by the facebook application	
        var facebookScope = "email";        
        // The status to use, as security means for the facebook  application
        var facebookStatus = "ads&=f";        
        // The namespace of the facebook application, as defined in the application settings
        var appNameSpace = "EXAMPLE_apstratatutorial";
        
        // Build a callback URL to your Apstrata app that will be called by Facebook to 
        // communicate the OAuth verifier, then to obtain the Facebook definitive auth token
        // The token parameter of the function is an Apstrata authentication token. When 
        // provided, it is used in the callback URL, otherwise, a new one is generated
        function getCallbackUrl(apsdb, token) {
            
            return "https://varick.apstrata.com/apsdb/rest/"
                                + apsrataAppKey
                                + "/RunScript?apsdb.scriptName=" + encodeURIComponent("getFacebookAuthToken")
                                + "&apsws.time=123456789"
                                + "&apsws.id=facebookadmin"
                                + "&apsdb.authToken=" + generateApstrataAuthToken(apsdb, token)
                                + "&apsws.responseType=json";
        }
        
        // Generate an Apstrata authentication token to be used in the callback URL that is sent
		// to Facebook along with your authorization request. We generate a token for a specific
		// user that we created on that occasion, called "facebookadmin"
		function generateApstrataAuthToken(apsdb, token) {
		 
		    // If we already have a token, just reuse it
		    // Note that we do not make sure here that the token is still valid
		    if (token) {
		        return token;
		    }		    
		    // Otherwise, ask Apstrata to generate a new authentication token
		    // for our facebookadmin user. Set the expiration time of this token
		    // to 240 seconds
		    var tokenRequest = {
	            "apsws.id": "facebookadmin",
	            "apsdb.tokenExpires": "240",
	            "apsdb.tokenLifetime": "360",
	            "apsdb.bindReferrer": "false",
	            "apsdb.runAs": "facebookadmin"
	        };			        
	        var res = apsdb.callApi("GenerateToken", tokenRequest, null);
	        if (res.metadata.status == "failure") {
	            throw JSON.stringify(res.metadata);
	        }	        
	        return res.result["apsdb.authToken"];
		}			
		]]>
	</code>
</script>
 
Try it!

Dig deeper

Related tutorials