Facebook connect with python ¶
A few weeks ago I've discover Facebook Connect. So I decide to try to use it in a new project. It look like an easy way for new user to register in my application.
The first step is to follow the Quick start guide. Then whe need to take care of Facebook in our application. There is already a cool python library to play with Facebook called pyfacebook. So you need to install it.
In my project I aleady use repoze.what for authentification. It just rocks. So i decide to write an IIDentifier plugin for Facebook:
import sha
import facebook
from webob import Request
from zope.interface import implements
from repoze.who.interfaces import IIdentifier
DEFAULT_FIELDS = ['uid', 'name', 'first_name', 'birthday', 'relationship_status',
'proxied_email', 'sex', 'hometown_location',
'pic', 'pic_big', 'pic_small', 'pic_square']
class Params(dict):
def __getattr__(self, attr):
return self.get(attr, '')
def __html__(self):
return repr(self)
class Facebook(object):
implements(IIdentifier)
def __init__(self, api_key, secret_key):
self.api_key = api_key
self.secret_key = secret_key
def identify(self, environ):
req = Request(environ)
# initialize the api object
fbapi = facebook.Facebook(self.api_key, self.secret_key) # init pyfacebook instance
if fbapi.check_session(req):
environ['repoze.who.fb'] = fbapi
user = fbapi.users.getInfo([fbapi.uid], DEFAULT_FIELDS)[0]
# we used the proxied_email and a generated password to retriave
# the user from our DB
user.update(
login=user['proxied_email'],
email=user['proxied_email'],
password=sha.new('%s%s' % (fbapi.uid, self.secret_key)).hexdigest(),
)
# we store the facebook data in environ
environ['repoze.who.fbuser'] = Params(user.items())
return user
def remember(self, environ, identity): pass
def forget(self, environ, identity): pass
At the first time there is no user in our DB. So the user isn't really connected to our interface. The trick is to use a javascript callback to show a registration form to the user with fields pre-filled with Facebook's data.
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head></head>
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript">
</script>
<fb:login-button onlogin="facebook_onlogin();"></fb:login-button>
<script type="text/javascript">
FB.init("YOUR_API_KEY_HERE", "xd_receiver.htm");
var facebook_onlogin() function() {
// here is the trick
window.location.href = '/register/facebook';
}
</script>
</body> </html>
When the form is submitted, you need to create the real user in your application. That's all !





