Created
October 12, 2011 15:19
-
-
Save un33k/1281494 to your computer and use it in GitHub Desktop.
code required to connect to Facebook in python / django
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 | |
from django.http import HttpResponseRedirect | |
from django.conf import settings | |
from django.contrib.auth import login as auth_login | |
from django.contrib.auth import authenticate | |
from django.core.urlresolvers import reverse | |
# Step 1. when facebook login is clicked, this function is hit | |
# Things to know: we have an app_id and app_secret from facebook for out app / site | |
# We have the main domain name of our site registered with facebook as facebook only | |
# accepts callback urls that are from the registered domain name | |
def login(request): | |
""" First step of process, redirects user to facebook, which redirects to authentication_callback. """ | |
args = { | |
'client_id': settings.FACEBOOK_APP_ID, | |
'scope': settings.FACEBOOK_SCOPE, | |
'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), | |
} | |
return HttpResponseRedirect('https://www.facebook.com/dialog/oauth?' + urllib.urlencode(args)) | |
# Step 2. facebook comes back and calls this fuction with a code | |
def authentication_callback(request): | |
""" Second step of the login process. | |
It reads in a code from Facebook, then redirects back to the home page. """ | |
# todo: make sure the code exist before accessing it, user haskey() or try: | |
code = request.GET.get('code') | |
args = { | |
'client_id': settings.FACEBOOK_APP_ID, | |
'client_secret': settings.FACEBOOK_APP_SECRET, | |
'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), | |
'code': code, | |
} | |
# Get a legit access token | |
target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() | |
# no json return, so just parse and take the value | |
response = cgi.parse_qs(target) | |
access_token = response['access_token'][-1] | |
# Read the user's profile information | |
fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) | |
# json format, deal with it as such | |
fb_profile = json.load(fb_profile) | |
# now you have the user info, do something with it, login user, force a user setup, or whatever you like | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment