Browse Source

Added facebook login.
still need to add some API examples.

Liron Shimrony 10 năm trước cách đây
mục cha
commit
342649654e

+ 9 - 1
hackathon_starter/hackathon/models.py

@@ -66,4 +66,12 @@ class MeetupToken(models.Model):
     access_token = models.CharField(max_length=200)
 
     def __unicode__(self):
-        return unicode(self.access_token)
+        return unicode(self.access_token)
+
+class FacebookProfile(models.Model):
+    user = models.ForeignKey(User)
+    fb_user_id = models.CharField(max_length=100)
+    time_created = models.DateTimeField(auto_now_add=True)
+    profile_url = models.CharField(max_length=50)
+    access_token = models.CharField(max_length=100)
+    

+ 85 - 0
hackathon_starter/hackathon/scripts/facebook.py

@@ -0,0 +1,85 @@
+import requests
+import urllib
+import simplejson as json
+import pdb
+
+##########################
+# FACEBOOK API CONSTANTS #
+##########################
+
+AUTHORIZE_URL = 'https://graph.facebook.com/oauth/authorize'
+ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
+
+class FacebookOauthClient(object):
+	'''
+	Python client for Facebook API
+	'''
+
+	access_token = None
+
+	def __init__(self, client_id, client_secret):
+		'''
+		Parameters:
+			client_id: String
+				- The client id from the registering app on Facebook
+			client_secret: String
+				- The client secret from the registering app on Facebook
+		'''
+		self.client_id = client_id
+		self.client_secret = client_secret
+
+
+
+	def get_authorize_url(self):
+		'''
+		Obtains authorize url link with given client_id.
+
+        Returns:
+            authURL: String
+                - The authorization url.
+
+		'''
+		authSettings = {'redirect_uri': "http://localhost:8000/hackathon/",
+		                'client_id': self.client_id}
+		params = urllib.urlencode(authSettings)
+		return AUTHORIZE_URL + '?' + params
+
+
+
+	def get_access_token(self, code):
+		'''
+		Obtains access token.
+
+        Parameters:
+            code: String
+                - The code is retrieved from the authorization url parameter
+                  to obtain access_token.
+		'''
+		authSettings = {'code': code,
+		                'redirect_uri': "http://localhost:8000/hackathon/",
+		                'client_secret': self.client_secret,
+		                'client_id': self.client_id}
+		params = urllib.urlencode(authSettings)
+		response = requests.get(ACCESS_TOKEN_URL + '?' + params)
+
+		if response.status_code != 200:
+			raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
+
+		response_array = str(response.text).split('&')
+		self.access_token = str(response_array[0][13:])
+		
+
+
+	def get_user_info(self):
+		'''
+        Obtains user information.
+
+        Returns:
+            content: Dictionary
+                - A dictionary containing user information.
+		'''
+		response = requests.get("https://graph.facebook.com/me?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)))
+
+		return response.json()

+ 4 - 0
hackathon_starter/hackathon/templates/hackathon/login.html

@@ -46,6 +46,10 @@
           <i class="fa fa-linkedin"></i>
           Sign in with LinkedIn
         </a> 
+        <a class="btn btn-block btn-social btn-facebook" href="http://localhost:8000/hackathon/facebook_login/">
+          <i class="fa fa-facebook"></i>
+          Sign in with Facebook
+        </a> 
       </div>
     </body>
 </html>

+ 1 - 1
hackathon_starter/hackathon/urls.py

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

+ 43 - 1
hackathon_starter/hackathon/views.py

@@ -11,6 +11,9 @@ from django.contrib.auth.decorators import login_required
 from django.views.decorators.csrf import csrf_exempt
 from django.http import JsonResponse
 
+import requests
+import pdb
+
 # Scripts
 from scripts.steam import gamespulling, steamidpulling 
 from scripts.github import *
@@ -24,6 +27,7 @@ from scripts.nytimes import *
 from scripts.meetup import *
 from scripts.linkedin import LinkedinOauthClient
 from scripts.yelp import requestData
+from scripts.facebook import *
 
 # Python
 import oauth2 as oauth
@@ -32,7 +36,7 @@ from rest_framework.renderers import JSONRenderer
 from rest_framework.parsers import JSONParser
 
 # Models
-from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile
+from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, FacebookProfile
 from hackathon.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 
@@ -43,6 +47,7 @@ getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTA
 getTwitter = TwitterOauthClient(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)
 getGithub = GithubOauthClient('2a11ce63ea7952d21f02', '7e20f82a34698fb33fc837186e96b12aaca2618d')
 getLinkedIn = LinkedinOauthClient(settings.LINKEDIN_CLIENT_ID, settings.LINKEDIN_CLIENT_SECRET)
+getFacebook = FacebookOauthClient(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
 
 def index(request):
     print "index: " + str(request.user)
@@ -117,6 +122,35 @@ def index(request):
                     profile.save()
                 user = authenticate(username=getLinkedIn.user_id+'_linkedin', password='password')
                 login(request, user)
+            
+            elif profile_track == 'facebook':
+                code = request.GET['code']
+                getFacebook.get_access_token(code)
+                userInfo = getFacebook.get_user_info()
+                username = userInfo['first_name'] + userInfo['last_name']
+                
+                try:
+                    user = User.objects.get(username=username+'_facebook')
+                except User.DoesNotExist:
+                    new_user = User.objects.create_user(username+'_facebook', username+'@madewithfacbook', 'password')
+                    new_user.save()
+
+                    try:
+                        profile = FacebookProfile.objects.get(user=new_user.id)
+                        profile.access_token = getFacebook.access_token
+                    except:
+                        profile = FacebookProfile()
+                        profile.user = new_user
+                        profile.fb_user_id = userInfo['id']
+                        profile.profile_url = userInfo['link']
+                        profile.access_token = getFacebook.access_token
+                    profile.save()
+                user = authenticate(username=username+'_facebook', password='password')
+                login(request, user)
+
+
+
+                
     else:
         if request.GET.items():
             user = User.objects.get(username = request.user.username)
@@ -159,6 +193,8 @@ def index(request):
                     profile = LinkedinProfile(user = user, access_token = getLinkedIn.access_token, linkedin_user=getLinkedIn.user_id)
                     profile.save()
 
+            
+
     context = {'hello': 'world'}
     return render(request, 'hackathon/index.html', context)
 
@@ -644,3 +680,9 @@ def linkedin_login(request):
     profile_track = 'linkedin'
     linkedin_url = getLinkedIn.get_authorize_url()
     return HttpResponseRedirect(linkedin_url)
+
+def facebook_login(request):
+    global profile_track
+    profile_track = 'facebook'
+    facebook_url = getFacebook.get_authorize_url()
+    return HttpResponseRedirect(facebook_url)

+ 3 - 0
hackathon_starter/hackathon_starter/settings.py

@@ -144,3 +144,6 @@ POPAPIKEY = 'be4cd251d8a4f1a3362689088bdb0255:0:71947444'
 TOPAPIKEY = 'c9655598e1fd4ff591f6d46f2321260e:17:71947444'
 
 QUANDLAPIKEY = 'fANs6ykrCdAxas7zpMz7'
+
+FACEBOOK_APP_ID = '928765007154940'
+FACEBOOK_APP_SECRET = 'b8ebaba232a18a1bf57c67a6be1e5652'