Pārlūkot izejas kodu

Fixed merge conlicts

Liron Shimrony 10 gadi atpakaļ
vecāks
revīzija
9863247c33

+ 4 - 3
README.md

@@ -36,7 +36,7 @@ Features
 * Sphinx Documentation
 * Django Nosetests 
 * Basic Authentication with username and password
-* **OAuth 2.0 Authentication** for Github, LinkedIn and Instagram
+* **OAuth 2.0 Authentication** for Github, LinkedIn, Instagram and Facebook
 * **OAuth 1.0a Authentication** for Twitter and Tumblr
 * **API Examples**
     * Yelp API
@@ -50,6 +50,7 @@ Features
     * Quandl Stock API
     * New York Times API
     * LinkedIn API
+    * Facebook API
 
 <hr>
 
@@ -245,8 +246,8 @@ Getting API Keys
     * For Default callback URL field, enter: http://127.0.0.1:8000/hackathon/.
 4. Click Register.
 5. Within settings.py, add the following:
-    * TUMBLR_CONSUMER_KEY = <Tumblr-consumer-key>
-    * TUMBLR_CONSUMER_SECRET = <Tumblr-consumer-secret>
+    * TUMBLR_CONSUMER_KEY = `Tumblr-consumer-key`
+    * TUMBLR_CONSUMER_SECRET = `Tumblr-consumer-secret`
 
 <hr>
 

+ 2 - 2
hackathon_starter/hackathon/admin.py

@@ -1,5 +1,5 @@
 from django.contrib import admin
-from hackathon.models import UserProfile, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile
+from hackathon.models import UserProfile, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, TumblrProfile
 
 # Register your models here.
 class TwitterProfileAdmin(admin.ModelAdmin):
@@ -12,4 +12,4 @@ admin.site.register(TwitterProfile, TwitterProfileAdmin)
 admin.site.register(GithubProfile)
 admin.site.register(MeetupToken)
 admin.site.register(LinkedinProfile)
-
+admin.site.register(TumblrProfile)

+ 10 - 1
hackathon_starter/hackathon/models.py

@@ -27,6 +27,15 @@ class GithubProfile(models.Model):
     def __unicode__(self):
         return unicode(self.user)
 
+class TumblrProfile(models.Model):
+    user = models.ForeignKey(User)
+    tumblr_user = models.CharField(max_length=200)
+    access_token = models.CharField(max_length=200)
+    access_token_secret = models.CharField(max_length=200)
+
+    def __unicode__(self):
+        return unicode(self.user)
+
 class InstagramProfile(models.Model):
     user = models.ForeignKey(User)
     instagram_user = models.CharField(max_length=200)
@@ -80,4 +89,4 @@ class GoogleProfile(models.Model):
     google_user_id = models.CharField(max_length=100)
     time_created = models.DateTimeField(auto_now_add=True)
     access_token = models.CharField(max_length=100)
-    profile_url = models.CharField(max_length=100)
+    profile_url = models.CharField(max_length=100)

+ 1 - 1
hackathon_starter/hackathon/scripts/linkedin.py

@@ -21,7 +21,7 @@ class LinkedinOauthClient(object):
                         'client_secret' : self.client_secret,
                         'redirect_uri' : 'http://127.0.0.1:8000/hackathon/',
                         'state' : 'DCEeFWf45A53sdfKef424',
-                        'scope': 'r_fullprofile'}
+                        'scope': 'r_basicprofile'}
 
         params = urllib.urlencode(auth_setting)
         authURL = AUTHORIZATION_URL + '?' + params

+ 6 - 4
hackathon_starter/hackathon/scripts/tumblr.py

@@ -32,7 +32,8 @@ class TumblrOauthClient(object):
     oauth_verifier = None
     oauth_token = None
     oauth_token_secret = None
-    accessed = False
+    is_authorized = False
+    access_token = None
 
     def __init__(self, consumer_key, consumer_secret):
         self.consumer_key = consumer_key
@@ -59,16 +60,16 @@ class TumblrOauthClient(object):
         '''
         Returns an access token to the user.
         '''
-        self.accessed = True
+        self.is_authorized = True
         token = oauth2.Token(self.oauth_token, self.oauth_token_secret)
         self.oauth_verifier = oauth_verifier
         print self.oauth_verifier
         token.set_verifier(self.oauth_verifier)
         client = oauth2.Client(self.consumer, token)
         resp, content = client.request(access_token_url, "POST")
-        access_token = dict(urlparse.parse_qsl(content))
+        self.access_token = dict(urlparse.parse_qsl(content))
         #set verified token
-        self.token = oauth2.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
+        self.token = oauth2.Token(self.access_token['oauth_token'], self.access_token['oauth_token_secret'])
 
     def getUserInfo(self):
         ''' Returns users information. '''
@@ -81,6 +82,7 @@ class TumblrOauthClient(object):
         #return content in json format
         jsonlist = json.loads(content)
         response = jsonlist['response']
+        self.username = str(response['user']['name'])
         user_info = response['user']
         total_blogs = len(user_info['blogs'])
         #print user_info

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

@@ -6,7 +6,7 @@
 	<div class="row text-center">
 	    <div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/githubUser/">Github Example</a></div>
 	    <div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/steam/">Steam Example</a></div>
-	    <div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/">Tumblr Example</a></div>
+	    <div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/tumblr/">Tumblr Example</a></div>
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/linkedin/">LinkedIn Example</a></div>
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/twilio/">Twilio Example</a></div>
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/instagram/">Instagram Example</a></div>

+ 0 - 109
hackathon_starter/hackathon/templates/hackathon/facebook.html

@@ -1,109 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title>Facebook Login JavaScript Example</title>
-<meta charset="UTF-8">
-</head>
-<body>
-{% include 'hackathon/base.html' %}
-<script>
-  // This is called with the results from from FB.getLoginStatus().
-  function statusChangeCallback(response) {
-    console.log('statusChangeCallback');
-    console.log(response);
-    // The response object is returned with a status field that lets the
-    // app know the current login status of the person.
-    // for FB.getLoginStatus().
-    if (response.status === 'connected') {
-      // Logged into your app and Facebook.
-      testAPI();
-    } else if (response.status === 'not_authorized') {
-      // The person is logged into Facebook, but not your app.
-      document.getElementById('status').innerHTML = 'Please log ' +
-        'into this app.';
-    } else {
-      // The person is not logged into Facebook, so we're not sure if
-      // they are logged into this app or not.
-      document.getElementById('status').innerHTML = 'Please log ' +
-        'into Facebook.';
-    }
-  }
-
-  // This function is called when someone finishes with the Login
-  // Button.  See the onlogin handler attached to it in the sample
-  // code below.
-  function checkLoginState() {
-    FB.getLoginStatus(function(response) {
-      statusChangeCallback(response);
-    });
-  }
-
-  window.fbAsyncInit = function() {
-  FB.init({
-    appId      : {{yourappid}},
-    cookie     : true, 
-                        
-    xfbml      : true,  // parse social plugins on this page
-    version    : 'v2.2' // use version 2.2
-  });
-
-  FB.getLoginStatus(function(response) {
-    statusChangeCallback(response);
-  });
-
-  };
-
-  // Load the SDK asynchronously
-  (function(d, s, id) {
-    var js, fjs = d.getElementsByTagName(s)[0];
-    if (d.getElementById(id)) return;
-    js = d.createElement(s); js.id = id;
-    js.src = "//connect.facebook.net/en_US/sdk.js";
-    fjs.parentNode.insertBefore(js, fjs);
-  }(document, 'script', 'facebook-jssdk'));
-
-  // Here we run a very simple test of the Graph API after login is
-  // successful.  See statusChangeCallback() for when this call is made.
-  function testAPI() {
-    console.log('Welcome!  Fetching your information.... ');
-    FB.api('/me', function(response) {
-      console.log('Successful login for: ' + response.name);
-      document.getElementById('status').innerHTML =
-        'Thanks for logging in, ' + response.name + '!';
-    });
-  }
-  // Here will be a function that'll create a dialog box to post upon your own wall. 
-  function posttoFeed() {
-    FB.ui({
-     method: 'Feed',
-     name: 'Django-Hackathon-Starter',
-     caption: 'starter dialog box',
-     description: 'This is a wall post brought to you by the Hackathon Starter',
-     message: 'It is alive!'
-    },
-    function(response){
-      if (response && response.post_id){
-        alert('post was published');
-      } else {
-        alert('post was not published');
-      }
-    });
-  }
-</script>
-
-<!--
-  Below we include the Login Button social plugin. This button uses
-  the JavaScript SDK to present a graphical Login button that triggers
-  the FB.login() function when clicked.
--->
-
-<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
-</fb:login-button>
-
-<input type="button" onclick="posttoFeed()" value="Post to Feed" />
-
-<div id="status">
-</div>
-
-</body>
-</html>

+ 46 - 32
hackathon_starter/hackathon/views.py

@@ -37,7 +37,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, FacebookProfile, GoogleProfile
+from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, FacebookProfile, TumblrProfile, GoogleProfile
 from hackathon.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 
@@ -53,7 +53,7 @@ getGoogle = GooglePlus(settings.GOOGLE_PLUS_APP_ID, settings.GOOGLE_PLUS_APP_SEC
 
 def index(request):
     print "index: " + str(request.user)
-
+    
     if not request.user.is_active:
         if request.GET.items():
             if profile_track == 'github':
@@ -149,6 +149,27 @@ def index(request):
                     profile.save()
                 user = authenticate(username=username+'_facebook', password='password')
                 login(request, user)
+            elif profile_track == 'tumblr':
+                if not getTumblr.is_authorized:
+                    oauth_verifier = request.GET['oauth_verifier']
+                    getTumblr.access_token_url(oauth_verifier) 
+                    getTumblr.getUserInfo()
+                    try:
+                        user = User.objects.get(username = getTumblr.username + '_tumblr')
+                    except User.DoesNotExist:
+                        username = getTumblr.username + '_tumblr'
+                        new_user = User.objects.create_user(username, username+'@madewithtumblr.com', 'password')
+                        new_user.save()
+                        try:
+                            profile =TumblrProfile.objects.get(user = new_user.id)
+                            profile.access_token = getTumblr.access_token['oauth_token']
+                            profile.access_token_secret = getTumblr.access_token['oauth_token_secret']
+                        except TumblrProfile.DoesNotExist:
+                            profile = TumblrProfile(user=new_user, access_token=getTumblr.access_token['oauth_token'], access_token_secret= getTumblr.access_token['oauth_token_secret'], tumblr_user=getTumblr.username)
+                        profile.save()
+                user = authenticate(username=getTumblr.username+'_tumblr', password='password')
+                login(request, user)   
+
 
             elif profile_track == 'google':
                 code = request.GET['code']
@@ -177,8 +198,6 @@ def index(request):
                 login(request, user)
 
 
-
-                
     else:
         if request.GET.items():
             user = User.objects.get(username = request.user.username)
@@ -220,7 +239,17 @@ def index(request):
                 except LinkedinProfile.DoesNotExist:
                     profile = LinkedinProfile(user = user, access_token = getLinkedIn.access_token, linkedin_user=getLinkedIn.user_id)
                     profile.save()
+            elif profile_track == 'tumblr':
+                if not getTumblr.is_authorized:
+                    oauth_verifier = request.GET['oauth_verifier']
+                    getTumblr.access_token_url(oauth_verifier) 
+                    getTumblr.getUserInfo()
 
+                    try:
+                        tumblrUser = TumblrProfile.objects.get(user=user.id)
+                    except TumblrProfile.DoesNotExist:
+                        profile = TumblrProfile(user=user, access_token=getTumblr.access_token['oauth_token'], access_token_secret= getTumblr.access_token['oauth_token_secret'], tumblr_user=getTumblr.username)
+                        profile.save()
             
 
     context = {'hello': 'world'}
@@ -451,34 +480,19 @@ def githubResume(request):
 
 def tumblr(request):
     ''' Tumblr api calls '''
-    if not getTumblr.accessed:
-        oauth_verifier = request.GET.get('oauth_verifier')
-        getTumblr.access_token_url(oauth_verifier)
-    if request.user not in User.objects.all():
-        try:
-            user_info, total_blog = getTumblr.getUserInfo()
-            username = str(user_info['name'])+ "2"
-            user = User.objects.get(username=username)
-        except User.DoesNotExist:
-            user_info, total_blog = getTumblr.getUserInfo()
-            username = str(user_info['name'])+ "2"
-            new_user = User.objects.create_user(username, username+'@tumblr.com','password')
-            new_user.save()
-            profile =Profile()
-            profile.user = new_user
-            profile.oauth_token = getTumblr.oauth_token
-            profile.oauth_secret = getTumblr.oauth_token_secret
-            profile.save()
-
-        user = authenticate(username=username, password='password')
-        login(request, user)
-
-    #get blogger twitterthecomic's blog information
-    blog = getTumblr.getBlogInfo('twitterthecomic')
-    #get tags that was tagged along starbucks
-    tagged_blog = getTumblr.getTaggedInfo("starbucks")
-    #get blog information tagged with starbucks
-    blogontag = getTumblr.getTaggedBlog("starbucks")
+    if getTumblr.is_authorized:
+        #get blogger twitterthecomic's blog information
+        blog = getTumblr.getBlogInfo('twitterthecomic')
+        #get tags that was tagged along starbucks
+        tagged_blog = getTumblr.getTaggedInfo("starbucks")
+        #get blog information tagged with starbucks
+        blogontag = getTumblr.getTaggedBlog("starbucks")
+    else:
+        blog, tagged_blog, blogontag = '', '',''
+        global profile_track
+        profile_track = 'tumblr'
+        tumblr_url = getTumblr.authorize_url()
+        return HttpResponseRedirect(tumblr_url)
 
     context = {'title': "What's up Starbucks?", 'blogData': blog, 'blogTag': tagged_blog, 'blogontag': blogontag}
     return render(request, 'hackathon/tumblr.html', context)