Browse Source

Added a Facebook API example to get the user basic info.
Added a function to check if a permission exists and a function to request a permission.

Liron Shimrony 10 years ago
parent
commit
a5290a2469

+ 68 - 1
hackathon_starter/hackathon/scripts/facebook.py

@@ -1,7 +1,6 @@
 import requests
 import urllib
 import simplejson as json
-import pdb
 
 ##########################
 # FACEBOOK API CONSTANTS #
@@ -9,6 +8,8 @@ import pdb
 
 AUTHORIZE_URL = 'https://graph.facebook.com/oauth/authorize'
 ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
+API_URL = 'https://graph.facebook.com/v2.3/'
+REQUEST_PERMISSIONS_URL = "https://www.facebook.com/dialog/oauth?"
 
 class FacebookOauthClient(object):
 	'''
@@ -16,6 +17,7 @@ class FacebookOauthClient(object):
 	'''
 
 	access_token = None
+	permission_request_url = None
 
 	def __init__(self, client_id, client_secret):
 		'''
@@ -83,4 +85,69 @@ class FacebookOauthClient(object):
 			raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
 
 		return response.json()
+
+
+	
+
+	def get_user_likes(self):
+		'''
+		Obtains a list of all the user likes. Require a special permission
+		via Facebook.
+
+		Returns:
+			content: dicionay
+				-A dictionary containing user likes.
+		'''
+		#Check if permission exists or ask for it
+		if not self.check_permissions('user_likes'):
+			requestedPermissionUrl = self.request_permissions('user_likes')
+
+		#Get likes
+		response = requests.get(API_URL + 'me/likes?access_token={at}'.format(at=self.access_token))
+		return response.json()['data']
+			
+
+
+	def check_permissions(self, perm):
+		'''
+		Checks if the app has the specified permission.
+
+		Parameters:
+		    perm: String
+		    	- The desired permission (such as user_likes)
+
+		Returns:
+			bool
+				- True if the permission granted or false otherwise.
+		'''
+
+		permDict = {'status': 'granted', 'permission':perm}
+		response = requests.get(API_URL + 'me/permissions?access_token={at}'.format(at=self.access_token))
+		if response.status_code != 200:
+			raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
+
+		currentPermissions = response.json()['data']
+		if permDict in currentPermissions:
+			return True
+		return False
+
+
+	def request_permissions(self, perm):
+		'''
+			Requests a permission from the user.
+
+			Parameters:
+				perm: String
+					- The permission we would like to get.
+
+			Returns: String
+				- The URL to redirect the user in order to get the permission.
+		'''
+		authSettings = {'client_id' : self.client_id, 
+		                'redirect_uri' : 'http://localhost:8000/hackathon/', 
+		                'auth_type' : 'rerequest', 
+		                'scope' : perm,
+		                'access_token' : access_token}
+		params = urllib.urlencode(authSettings)
+		self.permission_request_url = REQUEST_PERMISSIONS_URL + '?' + params
 		

+ 1 - 1
hackathon_starter/hackathon/templates/hackathon/api_examples.html

@@ -17,7 +17,7 @@
 		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/meetupUser/">Meetup</a></div>
 		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/yelp/">Yelp</a></div>
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/nytimesarticles/">New York Times</a></div>
-        <div class="col-sm-4"><a href="http://localhost:8000/hackathon/facebook/">Facebook JDK Exmaple</a></div>
+        <div class="col-sm-4"><a href="http://localhost:8000/hackathon/facebook/">Facebook Get User Info Exmaple</a></div>
 
   	</div>
 

+ 58 - 0
hackathon_starter/hackathon/templates/hackathon/facebookAPIExample.html

@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html>
+	<body>
+		{% include 'hackathon/base.html' %}
+	    <style>
+	    
+	    </style>
+	    
+	    <div class="container">
+		    <h1>Facebook API Usage Example</h1>
+		    <hr>
+		    <h2> Basic User Info</h2>
+		    <table class="table table-bordered table-hover table-striped tablesorter">
+			    <tr>			    	
+			    	<th class="header">User ID<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{userInfo.id}}
+			    	</td>
+				</tr>
+				<tr>
+			    	<th class="header">First Name<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{userInfo.first_name}}
+			    	</td>
+			    </tr>
+				<tr>
+			    	<th class="header">Last Name<i class="icon-sort"></i></th>	
+			    	<td>
+				    	{{userInfo.last_name}}
+			    	</td>
+		    	</tr>
+				<tr>
+			    	<th class="header">Gender<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{userInfo.gender}}
+			    	</td>
+			    </tr>
+				<tr>
+			    	<th class="header">Time Zone<i class="icon-sort"></i></th>
+			    	<td>
+				    	GMT{{userInfo.timezone}}
+			    	</td>
+			    </tr>
+				<tr>
+			    	<th class="header">Profile<i class="icon-sort"></i></th>
+			    	<td>
+				    	<a href="{{element.link}}">{{userInfo.link}}</a>
+			    	</td>
+		    	</tr>
+	    	</table>
+	    	<hr>
+	    	Every Facebook account basic information is available for all apps by default. In order to get more information about a user
+	    	(such as likes, photos, status updates, etc.) you must submit a request to facebook which you will find in the Facebook app page.
+	    	After gaining the desired permissions, you can call <em> check_permissions(self, perm)</em> to check if you gained permission from the user and <em>request_permissions</em> to request the permission from the user.
+	    	</div>
+        </div>
+    </body>
+</html>

+ 1 - 0
hackathon_starter/hackathon/urls.py

@@ -29,6 +29,7 @@ urlpatterns = patterns('',
     url(r'^github_login/$', views.github_login, name='github_login'),
     url(r'^linkedin_login/$', views.linkedin_login, name='linkedin_login'),
     url(r'^facebook_login/$', views.facebook_login, name='facebook_login'),
+    url(r'^facebook/$', views.facebook, name='facebook'),
     url(r'^quandlSnp500/$', views.quandlSnp500, name='quandlsnp500'),
     url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
     url(r'^quandlNasdaqdiff/$', views.quandlNasdaqdiff, name='quandlnasdaqdiff'),

+ 5 - 3
hackathon_starter/hackathon/views.py

@@ -228,9 +228,11 @@ def steamDiscountedGames(request):
 #################
 
 def facebook(request):
-    '''A sample application that will publish a status update after going into the login process using the Javascript SDK '''
-    yourappid = '364831617044713'
-    return render(request, 'hackathon/facebook.html', { 'yourappid' : yourappid })
+    '''
+    This is an example of getting basic user info and display it
+    '''
+    userInfo = getFacebook.get_user_info()
+    return render(request, 'hackathon/facebookAPIExample.html', { 'userInfo' : userInfo})
 
 
 #################