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!

Just Another Real Time Chat Built Over Node-js and Socket.io

I recently wrote another real time chat built over Node-js and Socket.io. Here is the link: https://github.com/jmg/node-simple-chat

I was researching so much about node-js lately and it turned out amazing when I have to deal with real time applications. But I think python’s Eventlet could achieve a very good performance too. I really need to reimplement this using eventlet websockets and then do some sort of benchmarks.

Probably the topic for my next post =). Keep reading.

Proxy Server Over NodeJs

I finish writing a HTTP Proxy Server using NodeJs.

NodeJs is a nonblocking event-driven I/O framework for the V8 JavaScript engine (The Chrome JS engine).

Clarifying, nothing is blocking in NodeJs. Everything is handled by events. This feature provides networking applications that can handle a thousands of request and do more stuff at same time!

On my experience, complex and critical applications, like web servers, run so fast on NodeJs.

Let’s take a look at my HTTP Proxy Server Features.

  • A Complete Proxy Server
  • Written over Node JS framework
  • Customizable request handlers
  • Javascript to write server side code!
  • Easy configuration to handle all browsers

Setting up the Server

To Run the server you need to install nodejs first:

Just go to http://nodejs.org/ and download the latest version. Then go to https://github.com/joyent/node/wiki/Installation and follow the instructions to install node.

Then you can checkout the proxy:

svn checkout http://node-proxy-server.googlecode.com/svn/trunk/ node-proxy-server-read-only

Next, open a terminal, navigate to the proxy directory and type:

~$ node proxy.js

Now the server is running on localhost:8000.

It’s time to setup your browser to listen it. Do the follow (On Mozila FireFox):

  • Go to Edit > Preferences on the menu bar
  • In the tab “Advanced” Select “Network” and click on “Settings”
  • Select the option “Manual proxy configuration”
  • In the textbox HTTP Proxy write: localhost and set the port to 8000.
  • Click on Ok and it’s done! You’re Ready to Browse.

Extending the server

You can extend your server adding request handlers in the handlers.js file.

A handler must be an object that contains a ‘pattern’ (string which matches the urls) and an ‘action’ (function that indicates what to do with the request). For example:

var handler = {
    pattern : 'facebook',
    action : function(response) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end("Hello facebook!");  
    }
}

The handler must be in a list of handlers that are exported to the server module:

 exports.handlers = [handler];

That’s all! If you want to write more complex modules, you can read the node js documentation (http://nodejs.org/docs/v0.4.3/api/http.html) or contact me.

Check out the repository

svn checkout http://node-proxy-server.googlecode.com/svn/trunk/ node-proxy-server-read-only

Enjoy the code!