Facebook JS SDK for login and python backend api calls with Pyfb.

Sometimes you don’t want to have a redirect from your site to facebook to just perform the login. The solution to this problem is simple. Fortunately facebook provides a login via a popup through the js sdk. The only big problem with this is that you must do api call with javascript right on the client side. This is not the best choice at all. If you don’t take care your application might become very vulnerable.

That’s the reason I’ll you you how to use the js sdk just for login and api calls through python backend code using the library I wrote, Pyfb.

First at all you need to write the index.html where the code to achive the login will be located. It would look like this:

<html>
    <head><title>Facebook Login with JS SDK</title>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>

        function isConnected(response) {
            return response.status == 'connected';
        }

        function getLoginStatus(FB) {

            FB.getLoginStatus(function(response) {

                if (isConnected(response)) {
                    onLogin(response);
                }
                else {
                    FB.login(onLogin);
                }
            });
        }

        function onLogin(response) {

            if (isConnected(response)) {
                location.href = '/facebook_javascript_login_sucess?access_token=' + response.authResponse.accessToken;
            }
        }

        window.fbAsyncInit = function() {

            FB.init({
                appId      : '{{FACEBOOK_APP_ID}}',
                channelUrl : 'http://localhost:8000/media/channel.html',
                status     : true,
                cookie     : true,
                xfbml      : true,
                oauth      : true,
            });

        };

        (function(d){
             var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
             js = d.createElement('script'); js.id = id; js.async = true;
             js.src = "http://connect.facebook.net/en_US/all.js";
             d.getElementsByTagName('head')[0].appendChild(js);
        }(document));

    </script>

        <button onclick="getLoginStatus(FB)">Facebook Javascript Login</button>
    </body>
</html>

As you can see, in the login callback function (onLogin) you are receiving the access token. This token will allow you to make backend calls, so don’t lose it! I’d recommend to save it in session or store it on the database every time a user do the login.

I will be using django for this example but you could use whatever you want for backend. The views.py django file would looks like this:

from pyfb import Pyfb
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response

from settings import FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY

def index(request):
    return render_to_response("index.html", {"FACEBOOK_APP_ID": FACEBOOK_APP_ID})

#Login with the js sdk and backend queries with pyfb
def facebook_javascript_login_sucess(request):

    access_token = request.GET.get("access_token")

    facebook = Pyfb(FACEBOOK_APP_ID)
    facebook.set_access_token(access_token)

    return _render_user(facebook)

def _render_user(facebook):

    me = facebook.get_myself()

    welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!"
    return HttpResponse(welcome % me.name)

Finally just configure the urls.py:

urlpatterns = patterns('',
    (r'^$', 'djangoapp.django_pyfb.views.index'),
    (r'^facebook_javascript_login_sucess/$', 'djangoapp.django_pyfb.views.facebook_javascript_login_sucess'),
)

And don’t forget to have the properly configuration constants on your settings.py:

# Facebook related Settings
FACEBOOK_APP_ID = 'YOUR_APP_ID'
FACEBOOK_SECRET_KEY = 'YOUR_APP_SECRET_CODE'

That’s it! enjoy the facebook graph API!

Advertisements

One thought on “Facebook JS SDK for login and python backend api calls with Pyfb.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s