Created
October 24, 2013 03:31
-
-
Save chriskief/7130864 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
import urllib2 | |
import urlparse | |
import json | |
from django.conf import settings | |
from django.core.urlresolvers import reverse | |
def get_user_data(request): | |
data = {} | |
# if we don't have a token yet, get one now | |
if 'facebook_access_token' not in request.session: | |
# URL to where we will redirect to | |
redirect_url = urllib.quote_plus(settings.SITE_URL + reverse('register_facebook')) | |
# set the token URL | |
url = 'https://graph.facebook.com/oauth/access_token?' \ | |
+ 'client_id=' + settings.FACEBOOK_APP_ID \ | |
+ '&redirect_uri=' + redirect_url \ | |
+ '&client_secret=' + settings.FACEBOOK_API_SECRET \ | |
+ '&code=' + request.GET['code'] | |
# grab the token from FB | |
response = urllib2.urlopen(url).read() | |
# parse the response | |
# {'access_token': ['AAAGVChRC0ygBAF3...'], 'expires': ['5183529']} | |
params = urlparse.parse_qs(response) | |
# save the token | |
request.session['facebook_access_token'] = params['access_token'][0] | |
request.session['facebook_access_expires'] = params['expires'][0] | |
# set the graph URL using the token we just fetched | |
graph_url = 'https://graph.facebook.com/me?' \ | |
+ 'access_token=' + request.session['facebook_access_token'] | |
# get the user's data from facebook | |
response = urllib2.urlopen(graph_url).read() | |
user = json.loads(response) | |
# get their photo | |
# is_silhouette is true if the user has not uploaded a profile picture | |
graph_url = 'https://graph.facebook.com/me/picture?' \ | |
+ 'type=large' \ | |
+ '&redirect=false' \ | |
+ '&access_token=' + request.session['facebook_access_token'] | |
response = urllib2.urlopen(graph_url).read() | |
picture = json.loads(response) | |
# get the user's info | |
data['user_id'] = user['id'] | |
data['username'] = user['username'] | |
data['email'] = user['email'] | |
data['full_name'] = user['first_name'] + ' ' + user['last_name'] | |
data['first_name'] = user['first_name'] | |
data['last_name'] = user['last_name'] | |
data['timezone'] = user['timezone'] | |
# ensure the user has uploaded a picture | |
if not picture['data']['is_silhouette']: | |
data['picture'] = picture['data']['url'] | |
else: | |
data['picture'] = '' | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment