Browse Source

Merge pull request #16 from lsxliron/master

Added Dropbox login option.
David Leonard 10 years ago
parent
commit
ccd1ba1219

+ 31 - 14
README.md

@@ -34,7 +34,7 @@ Features
 --------
 --------
 * User Registration
 * User Registration
 * Sphinx Documentation
 * Sphinx Documentation
-* Django Nosetests 
+* Django Nosetests
 * Basic Authentication with username and password
 * Basic Authentication with username and password
 * **OAuth 2.0 Authentication** for Github, LinkedIn, Instagram and Facebook
 * **OAuth 2.0 Authentication** for Github, LinkedIn, Instagram and Facebook
 * **OAuth 1.0a Authentication** for Twitter and Tumblr
 * **OAuth 1.0a Authentication** for Twitter and Tumblr
@@ -45,13 +45,14 @@ Features
     * Tumblr API
     * Tumblr API
     * Twitter API
     * Twitter API
     * Twilio API
     * Twilio API
-    * Meetup API 
+    * Meetup API
     * Steam API
     * Steam API
     * Quandl Stock API
     * Quandl Stock API
     * New York Times API
     * New York Times API
     * LinkedIn API
     * LinkedIn API
     * Facebook API
     * Facebook API
     * Google+ API
     * Google+ API
+    * Dropbox API
 
 
 <hr>
 <hr>
 
 
@@ -69,14 +70,14 @@ To get up and running, simply do the following:
 
 
     $ git clone https://github.com/DrkSephy/django-hackathon-starter.git
     $ git clone https://github.com/DrkSephy/django-hackathon-starter.git
     $ cd django-hackathon-starter
     $ cd django-hackathon-starter
-    
+
     # Install the requirements
     # Install the requirements
     $ pip install -r requirements.txt
     $ pip install -r requirements.txt
-    
+
     # Install bower
     # Install bower
     $ npm install -g bower
     $ npm install -g bower
     $ bower install
     $ bower install
-    
+
     # Perform database migrations
     # Perform database migrations
     $ python manage.py makemigrations
     $ python manage.py makemigrations
     $ python manage.py migrate
     $ python manage.py migrate
@@ -84,11 +85,11 @@ To get up and running, simply do the following:
 
 
 **NOTE**: We highly recommend creating a [Virtual Environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/). Python Virtual Environments allow developers to work in isolated sandboxes and to create separation between python packages installed via [pip](https://pypi.python.org/pypi/pip).
 **NOTE**: We highly recommend creating a [Virtual Environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/). Python Virtual Environments allow developers to work in isolated sandboxes and to create separation between python packages installed via [pip](https://pypi.python.org/pypi/pip).
 
 
-**NOTE**: To get you up and running quickly, we have provided dummy API keys for use. We highly recommend setting up your own keys and replacing them within `settings.py`. 
+**NOTE**: To get you up and running quickly, we have provided dummy API keys for use. We highly recommend setting up your own keys and replacing them within `settings.py`.
 
 
 
 
 <hr>
 <hr>
-    
+
 Getting API Keys
 Getting API Keys
 ----------------
 ----------------
 
 
@@ -113,7 +114,7 @@ Getting API Keys
     * For `redirect url` field, enter: `http://127.0.0.1:8000/hackathon/`
     * For `redirect url` field, enter: `http://127.0.0.1:8000/hackathon/`
 3. Within `settings.py`, add the following:
 3. Within `settings.py`, add the following:
     * `MEETUP_CONSUMER_KEY` = `Meetup key`
     * `MEETUP_CONSUMER_KEY` = `Meetup key`
-    * `MEETUP_CONSUMER_SECRET` = `Meetup secret key` 
+    * `MEETUP_CONSUMER_SECRET` = `Meetup secret key`
 
 
 <hr>
 <hr>
 
 
@@ -121,7 +122,7 @@ Getting API Keys
 
 
 1. Register an account on [Twilio.com](https://www.twilio.com/)
 1. Register an account on [Twilio.com](https://www.twilio.com/)
 2. Get your [Twilio Number](https://www.twilio.com/user/account/phone-numbers/incoming)
 2. Get your [Twilio Number](https://www.twilio.com/user/account/phone-numbers/incoming)
-3. [Setup the numbers](https://www.twilio.com/user/account/phone-numbers/incoming) you want to be able to send messages to 
+3. [Setup the numbers](https://www.twilio.com/user/account/phone-numbers/incoming) you want to be able to send messages to
 4. Grab your `account_sid` and `auth_token` [here](https://www.twilio.com/user/account/voice-messaging)
 4. Grab your `account_sid` and `auth_token` [here](https://www.twilio.com/user/account/voice-messaging)
 5. Within `scripts/twilioapi.py`:
 5. Within `scripts/twilioapi.py`:
     * Replace `account_sid` with your own Twilio `account_sid`
     * Replace `account_sid` with your own Twilio `account_sid`
@@ -236,6 +237,24 @@ Getting API Keys
 
 
 <hr>
 <hr>
 
 
+<img src="https://cf.dropboxstatic.com/static/images/brand/logotype-vflFbF9pY.png" width="200">
+
+1. Register an account on [Dropbox.com](http://www.dropbox.com).
+2. Navigate to [Dropbox Developers](https://www.dropbox.com/developers).
+3. From the side menu, select **App Console** and click on **Create app**.
+4. Configure the app permissions. This example uses the following configuration:
+    * App type- Dropbox API app
+    * My app needs access to files already on Dropbox.
+    * My app needs access to a user's full Dropbox.
+    * **Note:** This kind of configuration will require you to submit your app for approval.
+5. Give your app a name and click the **Create app button**.
+6. You will be redirected to the app console:
+    * Under **Redirect URIs** specify the URL to be redirected after authentication is complete (e.g ```http://locahost:8000/home```) and click **add**.
+    * Copy you ```App key``` and ```App secret```.
+7. Under ```settings.py``` change the following values:
+    * ```DROPBOX_APP_ID = your_app_id```
+    * ```DROPBOX_APP_SECRET = your_app_secret```
+<hr>
 
 
 
 
 <img src="https://secure.assets.tumblr.com/images/logo_page/img_logotype_34465d_2x.png" width="200">
 <img src="https://secure.assets.tumblr.com/images/logo_page/img_logotype_34465d_2x.png" width="200">
@@ -279,8 +298,8 @@ Getting API Keys
 <img src="http://planetcassandra.org/blogs/Upload/Postddfdbb6f-16ed-4e1c-8e29-ff2cf0cb43a1/quandl.png" width="200">
 <img src="http://planetcassandra.org/blogs/Upload/Postddfdbb6f-16ed-4e1c-8e29-ff2cf0cb43a1/quandl.png" width="200">
 
 
 1. Register an account on [Quandl](https://www.quandl.com/)
 1. Register an account on [Quandl](https://www.quandl.com/)
-2. After logging in, click on **Me** and then **Account settings** to find the API key 
-3. Within your `settings.py`add `QUANDLAPIKEY` = `Key` 
+2. After logging in, click on **Me** and then **Account settings** to find the API key
+3. Within your `settings.py`add `QUANDLAPIKEY` = `Key`
 
 
 <hr>
 <hr>
 
 
@@ -318,7 +337,7 @@ Project Structure
 Contributing
 Contributing
 ------------
 ------------
 
 
-We welcome contributions of all kinds. If you would like to know what work is needed to be done, check the [issue tracker](https://github.com/DrkSephy/django-hackathon-starter/issues). Before sending a pull request, please open an issue. This project follows the [pep-0008](https://www.python.org/dev/peps/pep-0008/) style guide. 
+We welcome contributions of all kinds. If you would like to know what work is needed to be done, check the [issue tracker](https://github.com/DrkSephy/django-hackathon-starter/issues). Before sending a pull request, please open an issue. This project follows the [pep-0008](https://www.python.org/dev/peps/pep-0008/) style guide.
 
 
 
 
 LICENSE
 LICENSE
@@ -345,5 +364,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 SOFTWARE.
-
-

+ 6 - 0
hackathon_starter/hackathon/models.py

@@ -90,3 +90,9 @@ class GoogleProfile(models.Model):
     time_created = models.DateTimeField(auto_now_add=True)
     time_created = models.DateTimeField(auto_now_add=True)
     access_token = models.CharField(max_length=100)
     access_token = models.CharField(max_length=100)
     profile_url = 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://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/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/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>
   	</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>
           <i class="fa fa-google"></i>
           Sign in with Google+
           Sign in with Google+
         </a> 
         </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>
       </div>
     </body>
     </body>
 </html>
 </html>

+ 3 - 0
hackathon_starter/hackathon/urls.py

@@ -32,6 +32,9 @@ urlpatterns = patterns('',
     url(r'^facebook/$', views.facebook, name='facebook'),
     url(r'^facebook/$', views.facebook, name='facebook'),
     url(r'^google_login/$', views.google_login, name='google_login'),
     url(r'^google_login/$', views.google_login, name='google_login'),
     url(r'^google/$', views.googlePlus, name='googlePlus'),
     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'^quandlSnp500/$', views.quandlSnp500, name='quandlsnp500'),
     url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
     url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
     url(r'^quandlNasdaqdiff/$', views.quandlNasdaqdiff, name='quandlnasdaqdiff'),
     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
 from django.http import JsonResponse
 
 
 import requests
 import requests
-
+import pdb
 
 
 # Scripts
 # Scripts
-from scripts.steam import gamespulling, steamidpulling 
+from scripts.steam import gamespulling, steamidpulling
 from scripts.github import *
 from scripts.github import *
 from scripts.tumblr import TumblrOauthClient
 from scripts.tumblr import TumblrOauthClient
 from scripts.twilioapi import *
 from scripts.twilioapi import *
@@ -29,6 +29,7 @@ from scripts.linkedin import LinkedinOauthClient
 from scripts.yelp import requestData
 from scripts.yelp import requestData
 from scripts.facebook import *
 from scripts.facebook import *
 from scripts.googlePlus import *
 from scripts.googlePlus import *
+from scripts.dropbox import *
 
 
 # Python
 # Python
 import oauth2 as oauth
 import oauth2 as oauth
@@ -37,7 +38,7 @@ from rest_framework.renderers import JSONRenderer
 from rest_framework.parsers import JSONParser
 from rest_framework.parsers import JSONParser
 
 
 # Models
 # 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.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 from hackathon.forms import UserForm
 
 
@@ -50,10 +51,11 @@ getGithub = GithubOauthClient('2a11ce63ea7952d21f02', '7e20f82a34698fb33fc837186
 getLinkedIn = LinkedinOauthClient(settings.LINKEDIN_CLIENT_ID, settings.LINKEDIN_CLIENT_SECRET)
 getLinkedIn = LinkedinOauthClient(settings.LINKEDIN_CLIENT_ID, settings.LINKEDIN_CLIENT_SECRET)
 getFacebook = FacebookOauthClient(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
 getFacebook = FacebookOauthClient(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
 getGoogle = GooglePlus(settings.GOOGLE_PLUS_APP_ID, settings.GOOGLE_PLUS_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):
 def index(request):
     print "index: " + str(request.user)
     print "index: " + str(request.user)
-    
+
     if not request.user.is_active:
     if not request.user.is_active:
         if request.GET.items():
         if request.GET.items():
             if profile_track == 'github':
             if profile_track == 'github':
@@ -79,7 +81,7 @@ def index(request):
                 login(request, user)
                 login(request, user)
             elif profile_track == 'twitter':
             elif profile_track == 'twitter':
                 oauth_verifier = request.GET['oauth_verifier']
                 oauth_verifier = request.GET['oauth_verifier']
-                getTwitter.get_access_token_url(oauth_verifier) 
+                getTwitter.get_access_token_url(oauth_verifier)
 
 
                 try:
                 try:
                     user = User.objects.get(username = getTwitter.username + '_twitter')#(username=getTwitter.username)
                     user = User.objects.get(username = getTwitter.username + '_twitter')#(username=getTwitter.username)
@@ -95,7 +97,7 @@ def index(request):
                 code = request.GET['code']
                 code = request.GET['code']
                 getInstagram.get_access_token(code)
                 getInstagram.get_access_token(code)
 
 
-                try: 
+                try:
                     user = User.objects.get(username=getInstagram.user_data['username']+'_instagram')
                     user = User.objects.get(username=getInstagram.user_data['username']+'_instagram')
                 except User.DoesNotExist:
                 except User.DoesNotExist:
                     username = getInstagram.user_data['username']+'_instagram'
                     username = getInstagram.user_data['username']+'_instagram'
@@ -124,13 +126,13 @@ def index(request):
                     profile.save()
                     profile.save()
                 user = authenticate(username=getLinkedIn.user_id+'_linkedin', password='password')
                 user = authenticate(username=getLinkedIn.user_id+'_linkedin', password='password')
                 login(request, user)
                 login(request, user)
-            
+
             elif profile_track == 'facebook':
             elif profile_track == 'facebook':
                 code = request.GET['code']
                 code = request.GET['code']
                 getFacebook.get_access_token(code)
                 getFacebook.get_access_token(code)
                 userInfo = getFacebook.get_user_info()
                 userInfo = getFacebook.get_user_info()
                 username = userInfo['first_name'] + userInfo['last_name']
                 username = userInfo['first_name'] + userInfo['last_name']
-                
+
                 try:
                 try:
                     user = User.objects.get(username=username+'_facebook')
                     user = User.objects.get(username=username+'_facebook')
                 except User.DoesNotExist:
                 except User.DoesNotExist:
@@ -152,7 +154,7 @@ def index(request):
             elif profile_track == 'tumblr':
             elif profile_track == 'tumblr':
                 if not getTumblr.is_authorized:
                 if not getTumblr.is_authorized:
                     oauth_verifier = request.GET['oauth_verifier']
                     oauth_verifier = request.GET['oauth_verifier']
-                    getTumblr.access_token_url(oauth_verifier) 
+                    getTumblr.access_token_url(oauth_verifier)
                     getTumblr.getUserInfo()
                     getTumblr.getUserInfo()
                     try:
                     try:
                         user = User.objects.get(username = getTumblr.username + '_tumblr')
                         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 = 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()
                         profile.save()
                 user = authenticate(username=getTumblr.username+'_tumblr', password='password')
                 user = authenticate(username=getTumblr.username+'_tumblr', password='password')
-                login(request, user)   
+                login(request, user)
 
 
 
 
             elif profile_track == 'google':
             elif profile_track == 'google':
@@ -197,6 +199,32 @@ def index(request):
                 user = authenticate(username=username+'_google', password='password')
                 user = authenticate(username=username+'_google', password='password')
                 login(request, user)
                 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:
     else:
         if request.GET.items():
         if request.GET.items():
@@ -224,7 +252,7 @@ def index(request):
                 code = request.GET['code']
                 code = request.GET['code']
                 getInstagram.get_access_token(code)
                 getInstagram.get_access_token(code)
 
 
-                try: 
+                try:
                     instagramUser = InstagramProfile.objects.get(user= user.id)
                     instagramUser = InstagramProfile.objects.get(user= user.id)
                 except InstagramProfile.DoesNotExist:
                 except InstagramProfile.DoesNotExist:
                     profile = InstagramProfile(user = user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
                     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':
             elif profile_track == 'tumblr':
                 if not getTumblr.is_authorized:
                 if not getTumblr.is_authorized:
                     oauth_verifier = request.GET['oauth_verifier']
                     oauth_verifier = request.GET['oauth_verifier']
-                    getTumblr.access_token_url(oauth_verifier) 
+                    getTumblr.access_token_url(oauth_verifier)
                     getTumblr.getUserInfo()
                     getTumblr.getUserInfo()
 
 
                     try:
                     try:
@@ -250,7 +278,7 @@ def index(request):
                     except TumblrProfile.DoesNotExist:
                     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 = 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()
                         profile.save()
-            
+
 
 
     context = {'hello': 'world'}
     context = {'hello': 'world'}
     return render(request, 'hackathon/index.html', context)
     return render(request, 'hackathon/index.html', context)
@@ -292,13 +320,34 @@ def facebook(request):
     return render(request, 'hackathon/facebookAPIExample.html', { 'userInfo' : userInfo})
     return render(request, 'hackathon/facebookAPIExample.html', { 'userInfo' : userInfo})
 
 
 #################
 #################
-#  GOOGLE API  #
+#  GOOGLE API   #
 #################
 #################
 def googlePlus(request):
 def googlePlus(request):
 
 
     userInfo = getGoogle.get_user_info()
     userInfo = getGoogle.get_user_info()
     return render(request, 'hackathon/googlePlus.html', {'userInfo' : userInfo})
     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   #
 #    YELP API   #
@@ -338,7 +387,7 @@ def meetupToken(request):
         MeetupToken.objects.all()[0] = meetupToken
         MeetupToken.objects.all()[0] = meetupToken
     return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetupUser/')
     return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetupUser/')
 
 
-def meetupUser(request): 
+def meetupUser(request):
     if not MeetupToken.objects.all().exists():
     if not MeetupToken.objects.all().exists():
         return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetup')
         return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetup')
     access_token = MeetupToken.objects.all()[0]
     access_token = MeetupToken.objects.all()[0]
@@ -458,7 +507,7 @@ def githubTopRepositories(request):
 
 
 def githubResume(request):
 def githubResume(request):
     '''A sample application which pulls various Github data to form a Resume of sorts'''
     '''A sample application which pulls various Github data to form a Resume of sorts'''
-    
+
     allData = {}
     allData = {}
     userData = getUserData('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
     userData = getUserData('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
     repositories = getUserRepositories('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'
         profile_track = 'instagram'
         instagram_url =getInstagram.get_authorize_url()
         instagram_url =getInstagram.get_authorize_url()
         return HttpResponseRedirect(instagram_url)
         return HttpResponseRedirect(instagram_url)
-    
+
     context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': instagram_tag}
     context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': instagram_tag}
     return render(request, 'hackathon/instagram.html', context)
     return render(request, 'hackathon/instagram.html', context)
 
 
@@ -608,7 +657,7 @@ def linkedin(request):
     if getLinkedIn.is_authorized:
     if getLinkedIn.is_authorized:
         content = getLinkedIn.getUserInfo()
         content = getLinkedIn.getUserInfo()
     else:
     else:
-        global profile_track 
+        global profile_track
         profile_track = 'linkedin'
         profile_track = 'linkedin'
         linkedin_url = getLinkedIn.get_authorize_url()
         linkedin_url = getLinkedIn.get_authorize_url()
         return HttpResponseRedirect(linkedin_url)
         return HttpResponseRedirect(linkedin_url)
@@ -673,7 +722,7 @@ def register(request):
     else:
     else:
         user_form = UserForm()
         user_form = UserForm()
 
 
-    
+
     return render(request,
     return render(request,
             'hackathon/register.html',
             'hackathon/register.html',
             {'user_form': user_form, 'registered': registered} )
             {'user_form': user_form, 'registered': registered} )
@@ -718,7 +767,7 @@ def tumblr_login(request):
 def twitter_login(request):
 def twitter_login(request):
     global profile_track
     global profile_track
     profile_track = 'twitter'
     profile_track = 'twitter'
-    twitter_url = getTwitter.get_authorize_url()     
+    twitter_url = getTwitter.get_authorize_url()
     return HttpResponseRedirect(twitter_url)
     return HttpResponseRedirect(twitter_url)
 
 
 def github_login(request):
 def github_login(request):
@@ -745,3 +794,9 @@ def google_login(request):
     profile_track = 'google'
     profile_track = 'google'
     google_url = getGoogle.get_authorize_url()
     google_url = getGoogle.get_authorize_url()
     return HttpResponseRedirect(google_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_ID = '52433353167-5hvsos5pvd2i2dt62trivbqvfk4qc2pv.apps.googleusercontent.com'
 GOOGLE_PLUS_APP_SECRET = 'mv1ZcpHqMF6uX7NRTLDC2jXR'
 GOOGLE_PLUS_APP_SECRET = 'mv1ZcpHqMF6uX7NRTLDC2jXR'
+
+DROPBOX_APP_ID = '8et85bx2ur6b1fb'
+DROPBOX_APP_SECRET = 'xx0virsvtghxlui'