Sfoglia il codice sorgente

Added Dropbox login option.
Added Dropbox API example for getting basic user info and searching files in your dropbox.

Liron Shimrony 10 anni fa
parent
commit
586399fbc8

+ 6 - 0
hackathon_starter/hackathon/models.py

@@ -90,3 +90,9 @@ class GoogleProfile(models.Model):
     time_created = models.DateTimeField(auto_now_add=True)
     access_token = models.CharField(max_length=100)
     profile_url = models.CharField(max_length=100)
+
+class DropboxProfile(models.Model):
+    user = models.ForeignKey(User)
+    dropbox_user_id = models.CharField(max_length=100)
+    time_created = models.DateTimeField(auto_now_add=True)
+    access_token = models.CharField(max_length=100)

+ 60 - 0
hackathon_starter/hackathon/scripts/dropbox.py

@@ -0,0 +1,60 @@
+import simplejson as json
+import urllib
+import requests
+import string
+import pdb
+import random
+
+
+AUTHORIZE_URL = 'https://www.dropbox.com/1/oauth2/authorize'
+ACCESS_TOKEN_URL = 'https://api.dropbox.com/1/oauth2/token'
+
+
+class DropboxOauthClient(object):
+
+	access_token = None
+	session_id = None
+	def __init__(self, client_id, client_secret):
+		self.client_id = client_id
+		self.client_secret = client_secret
+
+
+	def get_authorize_url(self):
+		self.get_session_id()
+		authSettings = {'response_type': 'code',
+		                'client_id': self.client_id,
+		                'redirect_uri': 'http://localhost:8000/hackathon',
+		                'state': self.session_id}
+
+		params = urllib.urlencode(authSettings)
+
+		return AUTHORIZE_URL + '?' + params
+
+	def get_session_id(self, length=50):
+		chars = string.uppercase + string.digits + string.lowercase
+		self.session_id = ''.join(random.choice(chars) for _ in range(length))
+
+	def get_access_token(self, code, state):
+		if state != self.session_id:
+			raise(Exception('Danger! Someone is messing up with you connection!'))
+
+		authSettings = {'code': code,
+		                'grant_type': 'authorization_code',
+		                'client_id': self.client_id,
+		                'client_secret': self.client_secret,
+		                'redirect_uri': 'http://localhost:8000/hackathon'}
+
+		response = requests.post(ACCESS_TOKEN_URL, data=authSettings)
+
+		if response.status_code!=200:
+			raise(Exception('Invalid response, response code {c}'.format(c=response.status_code)))
+		self.access_token = response.json()['access_token']
+
+
+	def get_user_info(self):
+		USER_INFO_API = 'https://api.dropbox.com/1/account/info'
+		params = urllib.urlencode({'access_token': self.access_token})
+		response = requests.get(USER_INFO_API + '?' + params)
+		if response.status_code!=200:
+			raise(Exception('Invalid response, response code {c}'.format(c=response.status_code)))
+		return response.json()

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

@@ -19,6 +19,7 @@
 		<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 Get User Info Exmaple</a></div>
         <div class="col-sm-4"><a href="http://localhost:8000/hackathon/google/">Google Get User Info Exmaple</a></div>
+        <div class="col-sm-4"><a href="http://localhost:8000/hackathon/dropbox/">Dropbox API</a></div>
 
   	</div>
 

+ 65 - 0
hackathon_starter/hackathon/templates/hackathon/dropbox.html

@@ -0,0 +1,65 @@
+<!DOCTYPE html>
+<html>
+	<body>
+		{% include 'hackathon/base.html' %}
+	    
+	    <style>
+	    	form{
+	    		width:80%;
+	    		text-align: center;
+	    		left:0px;
+	    		right:0px;
+	    		margin:auto;
+	    		margin-top:2%;
+	    	}
+	    </style>
+	    
+	    <div class="container">
+		    <h1>Dropbox 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.uid}}
+			    	</td>
+				</tr>
+
+				<tr>			    	
+			    	<th class="header">Name<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{userInfo.display_name}}
+			    	</td>
+				</tr>
+
+				<tr>			    	
+			    	<th class="header">Email<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{userInfo.email}}
+			    	</td>
+				</tr>
+
+				<tr>			    	
+			    	<th class="header">Country<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{userInfo.country}}
+			    	</td>
+				</tr>
+			</table>
+			
+			<hr>
+
+			<h2>Search Files Example</h2>
+			
+			<form method="POST" action="/hackathon/dropboxSearchFile/">
+				{% csrf_token %}
+				{% load bootstrap %}
+				<input type="text" name="filename" class="form-control" placeholder="Filename to search" value="" required autofocus>
+				<br>
+				<button class="btn btn-lg btn-primary btn-block" type="submit">Search</button>
+				<input type="hidden" name="submit" value="submit" />
+			</form>
+		</div>
+	</body>
+</html>

+ 45 - 0
hackathon_starter/hackathon/templates/hackathon/dropboxSearchFile.html

@@ -0,0 +1,45 @@
+<!DOCTYPE html>
+<html>
+	<body>
+		{% include 'hackathon/base.html' %}
+
+
+        <div class="container">
+            <h4><a href="{% url 'dropbox' %}">Back to Search</a><h4>
+            <h2>Search Results:</h2>
+            <hr>
+            
+            {% if data %}
+                <table class="table table-bordered table-hover table-striped tablesorter">
+                    <thead>
+                        <tr>
+                            <th class="header"> Type <i class="icon-sort"></i></th>
+                            <th class="header" style="width:60%"> Path <i class="icon-sort"></i></th>
+                            <th class="header"> Size <i class="icon-sort"></i></th>
+                            <th class="header" style="width:24%"> Modified <i class="icon-sort"></i></th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        {% for element in data %}
+                        <tr>
+                            <td>
+                                {% if element.is_dir %}
+                                    <img src="http://icons.iconarchive.com/icons/media-design/hydropro-v2/512/Folder-icon.png" alt="Folder" width="40" />
+                                {% else %}
+                                    <img src="http://www.veryicon.com/icon/png/File%20Type/Slika%201.0%20Location%20Icons/Location%20%20%20FILE.png" alt="File" width="40" />
+                                {% endif %}
+                            </td>
+                            <td> {{ element.path }} </td>
+                            <td> {{ element.size }} </td>
+                            <td> {{ element.modified }} </td>
+                        </tr>
+                        {% endfor %}
+                    </tbody>
+                </table>
+
+            {% else %}
+                <h4> No files were found</h4>
+            {% endif %}
+        </div>
+    </body>
+</html>

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

@@ -54,6 +54,10 @@
           <i class="fa fa-google"></i>
           Sign in with Google+
         </a> 
+        <a class="btn btn-block btn-social btn-dropbox" href="http://localhost:8000/hackathon/dropbox_login/">
+          <i class="fa fa-dropbox"></i>
+          Sign in with Dropbox
+        </a> 
       </div>
     </body>
 </html>

+ 3 - 0
hackathon_starter/hackathon/urls.py

@@ -32,6 +32,9 @@ urlpatterns = patterns('',
     url(r'^facebook/$', views.facebook, name='facebook'),
     url(r'^google_login/$', views.google_login, name='google_login'),
     url(r'^google/$', views.googlePlus, name='googlePlus'),
+    url(r'^dropbox_login/$', views.dropbox_login, name='dropbox_login'),
+    url(r'^dropbox/$', views.dropbox, name='dropbox'),
+    url(r'^dropboxSearchFile/$', views.dropboxSearchFile, name='dropboxSearchFile'),
     url(r'^quandlSnp500/$', views.quandlSnp500, name='quandlsnp500'),
     url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
     url(r'^quandlNasdaqdiff/$', views.quandlNasdaqdiff, name='quandlnasdaqdiff'),

+ 75 - 20
hackathon_starter/hackathon/views.py

@@ -12,10 +12,10 @@ 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.steam import gamespulling, steamidpulling
 from scripts.github import *
 from scripts.tumblr import TumblrOauthClient
 from scripts.twilioapi import *
@@ -29,6 +29,7 @@ from scripts.linkedin import LinkedinOauthClient
 from scripts.yelp import requestData
 from scripts.facebook import *
 from scripts.googlePlus import *
+from scripts.dropbox import *
 
 # Python
 import oauth2 as oauth
@@ -37,7 +38,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, TumblrProfile, GoogleProfile
+from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, FacebookProfile, TumblrProfile, GoogleProfile, DropboxProfile
 from hackathon.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 
@@ -50,10 +51,11 @@ getGithub = GithubOauthClient('2a11ce63ea7952d21f02', '7e20f82a34698fb33fc837186
 getLinkedIn = LinkedinOauthClient(settings.LINKEDIN_CLIENT_ID, settings.LINKEDIN_CLIENT_SECRET)
 getFacebook = FacebookOauthClient(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
 getGoogle = GooglePlus(settings.GOOGLE_PLUS_APP_ID, settings.GOOGLE_PLUS_APP_SECRET)
+getDropbox = DropboxOauthClient(settings.DROPBOX_APP_ID, settings.DROPBOX_APP_SECRET)
 
 def index(request):
     print "index: " + str(request.user)
-    
+
     if not request.user.is_active:
         if request.GET.items():
             if profile_track == 'github':
@@ -79,7 +81,7 @@ def index(request):
                 login(request, user)
             elif profile_track == 'twitter':
                 oauth_verifier = request.GET['oauth_verifier']
-                getTwitter.get_access_token_url(oauth_verifier) 
+                getTwitter.get_access_token_url(oauth_verifier)
 
                 try:
                     user = User.objects.get(username = getTwitter.username + '_twitter')#(username=getTwitter.username)
@@ -95,7 +97,7 @@ def index(request):
                 code = request.GET['code']
                 getInstagram.get_access_token(code)
 
-                try: 
+                try:
                     user = User.objects.get(username=getInstagram.user_data['username']+'_instagram')
                 except User.DoesNotExist:
                     username = getInstagram.user_data['username']+'_instagram'
@@ -124,13 +126,13 @@ 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:
@@ -152,7 +154,7 @@ def index(request):
             elif profile_track == 'tumblr':
                 if not getTumblr.is_authorized:
                     oauth_verifier = request.GET['oauth_verifier']
-                    getTumblr.access_token_url(oauth_verifier) 
+                    getTumblr.access_token_url(oauth_verifier)
                     getTumblr.getUserInfo()
                     try:
                         user = User.objects.get(username = getTumblr.username + '_tumblr')
@@ -168,7 +170,7 @@ def index(request):
                             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)   
+                login(request, user)
 
 
             elif profile_track == 'google':
@@ -197,6 +199,32 @@ def index(request):
                 user = authenticate(username=username+'_google', password='password')
                 login(request, user)
 
+            elif profile_track == 'dropbox':
+                code = request.GET['code']
+                state = request.GET['state']
+                getDropbox.get_access_token(code, state)
+                userInfo = getDropbox.get_user_info()
+                username = userInfo['name_details']['given_name'] + userInfo['name_details']['surname']
+
+                try:
+                    user = User.objects.get(username=username+'_dropbox')
+                except User.DoesNotExist:
+                    new_user = User.objects.create_user(username+'_dropbox', username+'@madewithdropbox', 'password')
+                    new_user.save()
+
+                    try:
+                        profile = DropboxProfile.objects.get(user=new_user.id)
+                        profile.access_token = getDropbox.access_token
+                    except:
+                        profile = DropboxProfile()
+                        profile.user = new_user
+                        profile.access_token = getDropbox.access_token
+                        profile.dropbox_user_id = userInfo['uid']
+                    profile.save()
+                user = authenticate(username=username+'_dropbox', password='password')
+                login(request, user)
+
+
 
     else:
         if request.GET.items():
@@ -224,7 +252,7 @@ def index(request):
                 code = request.GET['code']
                 getInstagram.get_access_token(code)
 
-                try: 
+                try:
                     instagramUser = InstagramProfile.objects.get(user= user.id)
                 except InstagramProfile.DoesNotExist:
                     profile = InstagramProfile(user = user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
@@ -242,7 +270,7 @@ def index(request):
             elif profile_track == 'tumblr':
                 if not getTumblr.is_authorized:
                     oauth_verifier = request.GET['oauth_verifier']
-                    getTumblr.access_token_url(oauth_verifier) 
+                    getTumblr.access_token_url(oauth_verifier)
                     getTumblr.getUserInfo()
 
                     try:
@@ -250,7 +278,7 @@ def index(request):
                     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'}
     return render(request, 'hackathon/index.html', context)
@@ -292,13 +320,34 @@ def facebook(request):
     return render(request, 'hackathon/facebookAPIExample.html', { 'userInfo' : userInfo})
 
 #################
-#  GOOGLE API  #
+#  GOOGLE API   #
 #################
 def googlePlus(request):
 
     userInfo = getGoogle.get_user_info()
     return render(request, 'hackathon/googlePlus.html', {'userInfo' : userInfo})
 
+#################
+#  DROPBOX API  #
+#################
+def dropbox(request):
+    userInfo = getDropbox.get_user_info()
+    return render(request, 'hackathon/dropbox.html', {'userInfo' : userInfo})
+
+def dropboxSearchFile(request):
+    if request.method == 'POST':
+        SEARCH_FILE_URL = 'https://api.dropbox.com/1/search/auto/'
+        requestParams = {'query': request.POST['filename'],
+                         'file_limit': '1000',
+                         'include_deleted': True,
+                         'access_token': getDropbox.access_token}
+        response = requests.post(SEARCH_FILE_URL, data=requestParams)
+
+        if response.status_code!=200:
+            raise(Exception('Invalid response, response code {c}'.format(c=response.status_code)))
+
+        return render(request, 'hackathon/dropboxSearchFile.html', {'data': response.json()})
+
 
 #################
 #    YELP API   #
@@ -338,7 +387,7 @@ def meetupToken(request):
         MeetupToken.objects.all()[0] = meetupToken
     return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetupUser/')
 
-def meetupUser(request): 
+def meetupUser(request):
     if not MeetupToken.objects.all().exists():
         return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetup')
     access_token = MeetupToken.objects.all()[0]
@@ -458,7 +507,7 @@ def githubTopRepositories(request):
 
 def githubResume(request):
     '''A sample application which pulls various Github data to form a Resume of sorts'''
-    
+
     allData = {}
     userData = getUserData('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
     repositories = getUserRepositories('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
@@ -518,7 +567,7 @@ def instagram(request):
         profile_track = 'instagram'
         instagram_url =getInstagram.get_authorize_url()
         return HttpResponseRedirect(instagram_url)
-    
+
     context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': instagram_tag}
     return render(request, 'hackathon/instagram.html', context)
 
@@ -608,7 +657,7 @@ def linkedin(request):
     if getLinkedIn.is_authorized:
         content = getLinkedIn.getUserInfo()
     else:
-        global profile_track 
+        global profile_track
         profile_track = 'linkedin'
         linkedin_url = getLinkedIn.get_authorize_url()
         return HttpResponseRedirect(linkedin_url)
@@ -673,7 +722,7 @@ def register(request):
     else:
         user_form = UserForm()
 
-    
+
     return render(request,
             'hackathon/register.html',
             {'user_form': user_form, 'registered': registered} )
@@ -718,7 +767,7 @@ def tumblr_login(request):
 def twitter_login(request):
     global profile_track
     profile_track = 'twitter'
-    twitter_url = getTwitter.get_authorize_url()     
+    twitter_url = getTwitter.get_authorize_url()
     return HttpResponseRedirect(twitter_url)
 
 def github_login(request):
@@ -745,3 +794,9 @@ def google_login(request):
     profile_track = 'google'
     google_url = getGoogle.get_authorize_url()
     return HttpResponseRedirect(google_url)
+
+def dropbox_login(request):
+    global profile_track
+    profile_track = 'dropbox'
+    dropbox_url = getDropbox.get_authorize_url()
+    return HttpResponseRedirect(dropbox_url)

+ 3 - 0
hackathon_starter/hackathon_starter/settings.py

@@ -150,3 +150,6 @@ FACEBOOK_APP_SECRET = '9a81d5797b87885ef608463086a5c4ac'
 
 GOOGLE_PLUS_APP_ID = '52433353167-5hvsos5pvd2i2dt62trivbqvfk4qc2pv.apps.googleusercontent.com'
 GOOGLE_PLUS_APP_SECRET = 'mv1ZcpHqMF6uX7NRTLDC2jXR'
+
+DROPBOX_APP_ID = '8et85bx2ur6b1fb'
+DROPBOX_APP_SECRET = 'xx0virsvtghxlui'