Skip to content

Commit

Permalink
starting to support oauth2 through the server side flow
Browse files Browse the repository at this point in the history
  • Loading branch information
tschellenbach committed Jul 23, 2011
1 parent e34820d commit 493abd3
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 15 deletions.
2 changes: 1 addition & 1 deletion django_facebook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


__license__ = 'BSD'
__version__ = '2.3.2'
__version__ = '3.0.0'
__maintainer__ = 'Thierry Schellenbach'
__email__ = 'thierryschellenbach@gmail.com'
__status__ = 'Production'
Expand Down
21 changes: 16 additions & 5 deletions django_facebook/official_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ def get_objects(self, ids, **args):
def get_connections(self, id, connection_name, **args):
"""Fetchs the connections for given object."""
return self.request(id + "/" + connection_name, args)

def convert_code(self, code, redirect_uri=''):
from django_facebook import settings as facebook_settings
args = dict(client_id=facebook_settings.FACEBOOK_APP_ID)
args['client_secret'] = facebook_settings.FACEBOOK_APP_SECRET
args['code'] = code
args['redirect_uri'] = redirect_uri
return self.request('oauth/access_token', args, json=False)

def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
Expand Down Expand Up @@ -228,7 +236,7 @@ def delete_object(self, id):
"""Deletes the object with the given ID from the graph."""
self.request(id, post_args={"method": "delete"})

def request(self, path, args=None, post_args=None):
def request(self, path, args=None, post_args=None, json=True):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is given,
Expand All @@ -242,8 +250,8 @@ def request(self, path, args=None, post_args=None):
args["access_token"] = self.access_token
post_data = None if post_args is None else urllib.urlencode(post_args)
request_url = "https://graph.facebook.com/" + path + "?" + urllib.urlencode(args)
response = _request_json(request_url, post_data)
if response.get("error"):
response = _request_json(request_url, post_data, json=json)
if getattr(response, 'error', False):
raise GraphAPIError(response["error"]["type"],
response["error"]["message"])
return response
Expand Down Expand Up @@ -306,7 +314,7 @@ def get_user_from_cookie(cookies, app_id, app_secret):
else:
return None

def _request_json(url, post_data=None, timeout=3, attempts=2, test_file=None):
def _request_json(url, post_data=None, timeout=3, attempts=2, test_file=None, json=True):
'''
request the given url and parse it as json
Expand All @@ -329,7 +337,10 @@ def _request_json(url, post_data=None, timeout=3, attempts=2, test_file=None):
try:
response = response_file.read().decode('utf8')
#we only use unicode in the application, no bugs for our i18n friends
parsed_response = simplejson.loads(response)
if json:
parsed_response = simplejson.loads(response)
else:
parsed_response = response
finally:
response_file.close()

Expand Down
8 changes: 6 additions & 2 deletions django_facebook/static/js/facebook.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ facebookClass.prototype = {

connect: function (formElement, requiredPerms) {
//,'publish_stream','offline_access'
alert('hey');
requiredPerms = requiredPerms || ['email','user_about_me','user_birthday','user_website'];
FB.login(function(response) {
formElement.submit();
console.log('hello worl');
console.log(response);
var accessToken = response.authResponse.accessToken;
//formElement.submit();
},
{perms: requiredPerms.join(',')}
{scope: requiredPerms.join(',')}
);
},

Expand Down
2 changes: 1 addition & 1 deletion django_facebook/templates/django_facebook/connect.html
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ <h2>Django Facebook - Test page</h2>
<script>
facebookAppId = '{{ FACEBOOK_APP_ID }}';
function facebookJSLoaded(){
FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true});
FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true, oauth: true});
}
window.fbAsyncInit = facebookJSLoaded;
F = new facebookClass(facebookAppId);
Expand Down
40 changes: 37 additions & 3 deletions django_facebook/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.conf import settings
from django.contrib import messages
from django.http import Http404, HttpResponseRedirect
from django.http import Http404, HttpResponseRedirect, QueryDict
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.translation import ugettext as _
Expand All @@ -13,9 +13,30 @@
from django_facebook.utils import next_redirect
import logging
import sys
import types

logger = logging.getLogger(__name__)

def facebook_login_required(redirect_uri, scope=None):
'''
Redirect uri is the url to redirect to
Scope can either be in the format ['email', 'read_stream'] or 'email,read_stream'
'''
url = 'https://www.facebook.com/dialog/oauth?'
query_dict = QueryDict('', True)
query_dict['client_id'] = facebook_settings.FACEBOOK_APP_ID
query_dict['redirect_uri'] = redirect_uri
if scope:
if isinstance(scope, (basestring)):
query_dict['scope'] = scope
else:
query_dict['scope'] = scope
url += query_dict.urlencode()


return HttpResponseRedirect(url)


@csrf_exempt
def connect(request):
Expand All @@ -24,15 +45,28 @@ def connect(request):
- (if authenticated) connect the user
- login
- register
'''
uri = 'http://' + request.META['HTTP_HOST'] + request.path
if request.GET.get('redirect'):
return facebook_login_required(uri, scope='read_stream')
context = RequestContext(request)

assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id and ensure the context processor is enabled'
facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))

access_token = None
if request.GET.get('code'):
facebook = get_facebook_graph(request)
response_string = facebook.convert_code(request.GET.get('code'), redirect_uri=uri)
data = QueryDict(response_string)
#access token with expires
access_token = data['access_token']
print access_token

if facebook_login:
facebook = get_facebook_graph(request)
facebook = get_facebook_graph(request, access_token=access_token)


if facebook.is_authenticated():
facebook_data = facebook.facebook_profile_data()
#either, login register or connect the user
Expand Down
Binary file modified facebook_example/django_fb_test
Binary file not shown.
1 change: 0 additions & 1 deletion facebook_example/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
# ('Your Name', 'your_email@example.com'),
)


MANAGERS = ADMINS

DATABASES = {
Expand Down
1 change: 1 addition & 0 deletions facebook_example/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
(r'^accounts/', include('registration.backends.default.urls')),
(r'^facebook/', include('django_facebook.urls')),
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ def find_package_data(where='.', package='', exclude=standard_exclude,
license = license_text,
packages=find_packages(),
package_data=package_data,
data_files=[('', ['LICENSE.txt',
'README.rest'])],
# data_files=[('', ['LICENSE.txt',
# 'README.rest'])],
description = DESCRIPTION,
long_description=long_description,
classifiers = CLASSIFIERS
Expand Down

0 comments on commit 493abd3

Please sign in to comment.