Skip to content

Instantly share code, notes, and snippets.

@kzar
Forked from droot/fb_helpers.py
Created October 14, 2010 13:34
Show Gist options
  • Save kzar/626167 to your computer and use it in GitHub Desktop.
Save kzar/626167 to your computer and use it in GitHub Desktop.
Stuff that's missing from the Facebook python SDK
import base64
import hashlib
import hmac
import simplejson as json
def base64_url_decode(inp):
padding_factor = (4 - len(inp) % 4) % 4
inp += "="*padding_factor
return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/'))))
def parse_signed_request(signed_request, secret):
if not signed_request or not secret:
return None
l = signed_request.split('.', 2)
encoded_sig = l[0]
payload = l[1]
sig = base64_url_decode(encoded_sig)
data = json.loads(base64_url_decode(payload))
if data.get('algorithm').upper() != 'HMAC-SHA256':
log.error('Unknown algorithm')
return None
else:
expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()
if sig != expected_sig:
return None
else:
log.debug('valid signed request received..')
return data
def oauth_token(signed_request, secret):
"""Grab the Facebook auth token, return it or None."""
data = parse_signed_request(signed_request, secret)
if data and isinstance(data, dict) and data.has_key('oauth_token'):
return data['oauth_token']
def oauth_URL(**args):
"""Crafts a oauth link that you can send users to if you want to
get an auth_token or obtain more permissions.
E.G. oauth_URL(scope="offline_access,friends_birthday")
"""
return "https://graph.facebook.com/oauth/authorize?" + urllib.urlencode(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment