Permalink
Browse files

added middleware facebook auth

  • Loading branch information...
1 parent 5f74e99 commit db29c62d3fb7891ac0b2a21e1d243854a711cd73 @bradmann committed Apr 27, 2012
View
@@ -0,0 +1 @@
+*.py[cod]
View
@@ -0,0 +1 @@
+*.py[cod]
View
Binary file not shown.
View
@@ -102,6 +102,7 @@
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
+ 'muggedapp.middleware.fbauth.FBAuthMiddleware'
)
ROOT_URLCONF = 'mugged.urls'
View
Binary file not shown.
View
Binary file not shown.
View
Binary file not shown.
View
@@ -0,0 +1 @@
+*.py[cod]
View
Binary file not shown.
View
@@ -0,0 +1 @@
+*.py[cod]
No changes.
View
@@ -0,0 +1,22 @@
+import json
+import requests
+
+def fb_call(call, args=None):
+ url = "https://graph.facebook.com/{0}".format(call)
+ r = requests.get(url, params=args)
+ return json.loads(r.content)
+
+def get_friends(request):
+ access_token = request.session['access_token']
+ friends = fb_call('me/friends', args={'access_token': access_token})
+ friendarr = friends['data']
+ while friends.has_key('paging') and friends['paging'].has_key('next'):
+ next_url = friends['paging']['next']
+ r = requests.get(next_url, params={'access_token': access_token})
+ friends = json.loads(r.content)
+ friendarr.extend(friends['data'])
+ return friendarr
+
+def get_user(request, id):
+ access_token = request.session['access_token']
+ return fb_call(str(id), args={'access_token': access_token})
View
@@ -0,0 +1,38 @@
+import datetime
+import requests
+import re
+
+base_uri = 'http://florida.arrests.org/search.php'
+
+def get_age(birthday):
+ month, day, year = birthday.split('/')
+ birthdate = datetime.datetime(int(year), int(month), int(day))
+ delta = datetime.datetime.now() - birthdate
+ return int(delta.days / 365.25)
+
+def run_search(request, fbuser):
+ first_name = fbuser['first_name']
+ last_name = fbuser['last_name']
+ birthday = fbuser.get('birthday', None)
+ gender = fbuser.get('gender', None)
+ request_params = {'fname': first_name, 'lname': last_name, 'fpartial': 'True'}
+ gender_map = {'male': 'M', 'female': 'F'}
+ request_params['sex'] = gender_map.get(gender, 'M')
+ if birthday and len(birthday.split('/')) == 3:
+ age = get_age(birthday)
+ request_params.update({'minage': age, 'maxage': age})
+ req = requests.get(base_uri, params=request_params)
+ page = req.content
+ paths = re.findall("<img src='(/thumbs/[^']*)'", page)
+ if len(paths) == 0:
+ return None
+ pagenum = 1
+ patharr = paths[:]
+ while len(paths) == 42:
+ request_params['page'] = pagenum
+ req = requests.get(base_uri, params=request_params)
+ page = req.content
+ paths = re.findall("<img src='(/thumbs/[^']*)'", page)
+ patharr.extend(paths)
+ pagenum += 1
+ return patharr
View
@@ -1,42 +0,0 @@
-from django.http import HttpResponse
-from django.conf import settings
-import json
-import hmac
-import hashlib
-import requests
-from base64 import urlsafe_b64decode, urlsafe_b64encode
-
-def fbapi_auth(code):
- params = {'client_id': app.config['FB_APP_ID'],
- 'redirect_uri': get_home(),
- 'client_secret': app.config['FB_APP_SECRET'],
- 'code': code}
-
- result = fbapi_get_string(path=u"/oauth/access_token?", params=params, encode_func=simple_dict_serialisation)
- pairs = result.split("&", 1)
- result_dict = {}
- for pair in pairs:
- (key, value) = pair.split("=")
- result_dict[key] = value
- return (result_dict["access_token"], result_dict["expires"])
-
-def get_token(signed_request):
- sig, payload = signed_request.split('.', 2)
- data = json.loads(urlsafe_b64decode(str(payload) + "="*(4 - len(payload) % 4)))
- if not data['algorithm'].upper() == 'HMAC-SHA256':
- raise ValueError('unknown algorithm {0}'.format(data['algorithm']))
- h = hmac.new(settings.FBAPI_APP_SECRET, digestmod=hashlib.sha256)
- h.update(payload)
- expected_sig = urlsafe_b64encode(h.digest()).replace('=', '')
- if sig != expected_sig:
- raise ValueError('bad signature')
- if data.has_key('oauth_token'):
- return data.get('oauth_token')
-
-def oauth_redirect():
- return HttpResponse("<script>var oauth_url = 'https://www.facebook.com/dialog/oauth/?client_id={0}&redirect_uri=' + encodeURIComponent('https://apps.facebook.com/{1}/') + '&scope={2}';window.top.location = oauth_url;</script>".format(settings.FBAPI_APP_ID, settings.FBAPI_APP_NAMESPACE, ','.join(settings.FBAPI_SCOPE)))
-
-def fb_call(call, args=None):
- url = "https://graph.facebook.com/{0}".format(call)
- r = requests.get(url, params=args)
- return json.loads(r.content)
View
Binary file not shown.
View
Binary file not shown.
@@ -0,0 +1 @@
+*.py[cod]
No changes.
@@ -0,0 +1,36 @@
+from django.http import HttpResponse
+from django.conf import settings
+from base64 import urlsafe_b64decode, urlsafe_b64encode
+import hmac
+import hashlib
+import json
+
+
+class FBAuthMiddleware:
+ def get_token(self, signed_request):
+ sig, payload = signed_request.split('.', 2)
+ data = json.loads(urlsafe_b64decode(str(payload) + "="*(4 - len(payload) % 4)))
+ if not data['algorithm'].upper() == 'HMAC-SHA256':
+ raise ValueError('unknown algorithm {0}'.format(data['algorithm']))
+ h = hmac.new(settings.FBAPI_APP_SECRET, digestmod=hashlib.sha256)
+ h.update(payload)
+ expected_sig = urlsafe_b64encode(h.digest()).replace('=', '')
+ if sig != expected_sig:
+ raise ValueError('bad signature')
+ if data.has_key('oauth_token'):
+ return data.get('oauth_token')
+
+ def oauth_redirect(self):
+ return HttpResponse("<script>var oauth_url = 'https://www.facebook.com/dialog/oauth/?client_id={0}&redirect_uri=' + encodeURIComponent('https://apps.facebook.com/{1}/') + '&scope={2}';window.top.location = oauth_url;</script>".format(settings.FBAPI_APP_ID, settings.FBAPI_APP_NAMESPACE, ','.join(settings.FBAPI_SCOPE)))
+
+ def process_request(self, request):
+ access_token = request.session.get('access_token', None)
+ if not access_token:
+ access_token = self.get_token(request.POST.get('signed_request'))
+ if not access_token:
+ return self.oauth_redirect()
+ else:
+ request.session['access_token'] = access_token
+ return None
+ else:
+ return None
View
Binary file not shown.
View
@@ -1,72 +1,21 @@
from django.http import HttpResponse
from django.http import HttpRequest
+from django.views.decorators.http import require_http_methods
from django.shortcuts import render_to_response
from django.conf import settings
import json
-import hmac
-import hashlib
-import requests
-import re
-import datetime
-from base64 import urlsafe_b64decode, urlsafe_b64encode
-import fbapi
-
-base_uri = 'http://florida.arrests.org/search.php'
+from api import fbapi, mugapi
+@require_http_methods(['POST'])
def index(request):
- if request.method == 'POST':
- access_token = fbapi.get_token(request.POST.get('signed_request'))
- request.session['access_token'] = access_token
- if access_token:
- friends = fbapi.fb_call('me/friends', args={'access_token': access_token})
- friendarr = friends['data']
- while friends.has_key('paging') and friends['paging'].has_key('next'):
- next_url = friends['paging']['next']
- r = requests.get(next_url, params={'access_token': access_token})
- friends = json.loads(r.content)
- friendarr.extend(friends['data'])
- friendstring = json.dumps(friendarr)
- return render_to_response('index.html', {'friends': friendstring, 'friendarr': friendarr})
- else:
- return fbapi.oauth_redirect()
- else:
- return HttpResponse('This page only supports POSTS')
-
-def get_age(birthday):
- month, day, year = birthday.split('/')
- birthdate = datetime.date(year, month, day)
- delta = datetime.datetime.now - birthdate
- return int(delta.days / 365.25)
+ friendarr = fbapi.get_friends(request)
+ friendstring = json.dumps(friendarr)
+ return render_to_response('index.html', {'friends': friendstring, 'friendarr': friendarr})
def mugshot(request, id):
- access_token = request.session.get('access_token')
- fbuser = fbapi.fb_call(str(id), args={'access_token': access_token})
- first_name = fbuser['first_name']
- last_name = fbuser['last_name']
- birthday = fbuser.get('birthday', None)
- gender = fbuser.get('gender', None)
- request_params = {'fname': first_name, 'lname': last_name, 'fpartial': 'True'}
- if gender == 'male':
- request_params['sex'] = 'M'
- elif gender == 'female':
- request_params['sex'] = 'F'
- if birthday and len(birthday.split('/')) == 3:
- age = get_age(birthday)
- request_params['minage'] = age
- request_params['maxage'] = age
- req = requests.get(base_uri, params=request_params)
- page = req.content
- paths = re.findall("<img src='(/thumbs/[^']*)'", page)
- if len(paths) == 0:
+ fbuser = fbapi.get_user(request, id)
+ patharr = mugapi.run_search(request, fbuser)
+ if not patharr:
return HttpResponse('', status=204)
- pagenum = 1
- patharr = paths[:]
- while len(paths) == 42:
- request_params['page'] = pagenum
- req = requests.get(base_uri, params=request_params)
- page = req.content
- paths = re.findall("<img src='(/thumbs/[^']*)'", page)
- patharr.extend(paths)
- pagenum += 1
- return render_to_response('mugshot.html', {'name': fbuser['name'], 'id': str(id), 'patharr': patharr, 'birthday': birthday})
+ return render_to_response('mugshot.html', {'name': fbuser['name'], 'id': str(id), 'patharr': patharr})
View
Binary file not shown.

0 comments on commit db29c62

Please sign in to comment.