Forráskód Böngészése

Merge pull request #20 from lsxliron/master

Foursquare
David Leonard 10 éve
szülő
commit
bb1e01160c

+ 18 - 1
README.md

@@ -49,6 +49,7 @@ Features
     * Facebook API
     * Google+ API
     * Dropbox API
+    * Foursquare API
 
 <hr>
 
@@ -246,12 +247,28 @@ Getting API Keys
 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```.
+    * Copy your ```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='http://www.atlantamusicguide.com/wp-content/uploads/foursquare-logo.png' width="200">
+
+1. Register and account on [Foursquare.com](https://foursquare.com).
+2. Navigate to [Foursquare For Developers](https://developer.foursquare.com).
+3. From the top menu bar select **My Apps** and you will be redirected to the app dashboard.
+4. Hit **Create a New App**:
+    * Give your app a name.
+    * Under **Download / welcome page url**, specify your app main url (e.g ```http://www.localhost:8000```).
+    * Under **Redirect URI**, specify the URL to be redirected after authentication is complete (e.g ```http://locahost:8000/home```) and click **add**.
+    * Scroll all the way to the botttom and hit **Save Changes**.
+5. From the App page you were redirected to, copy your ```App key``` and ```App secret```.
+6. Under ```settings.py``` change to following values:
+    * ```FOURSQUARE_APP_ID = your_client_id```
+    * ```FOURSQUARE_APP_SECRET = your_app_secret```
+<hr>
+
 
 <img src="https://secure.assets.tumblr.com/images/logo_page/img_logotype_34465d_2x.png" width="200">
 

+ 9 - 2
hackathon_starter/hackathon/models.py

@@ -83,7 +83,7 @@ class FacebookProfile(models.Model):
     time_created = models.DateTimeField(auto_now_add=True)
     profile_url = models.CharField(max_length=50)
     access_token = models.CharField(max_length=100)
-    
+
 class GoogleProfile(models.Model):
     user = models.ForeignKey(User)
     google_user_id = models.CharField(max_length=100)
@@ -95,4 +95,11 @@ 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)
+    access_token = models.CharField(max_length=100)
+
+
+class FoursquareProfile(models.Model):
+    user = models.ForeignKey(User)
+    foursquare_id = models.CharField(max_length=100)
+    time_created = models.DateTimeField(auto_now_add=True)
+    access_token = models.CharField(max_length=100)

+ 102 - 0
hackathon_starter/hackathon/scripts/foursquare.py

@@ -0,0 +1,102 @@
+import simplejson as json
+import urllib
+import requests
+
+
+############################
+# FOURSQUARE API CONSTANTS #
+############################
+AUTHORIZE_URL = 'https://foursquare.com/oauth2/authenticate'
+ACCESS_TOKEN_URL = 'https://foursquare.com/oauth2/access_token'
+REDIRECT_URL = 'http://localhost:8000/hackathon'
+
+
+class FoursquareOauthClient(object):
+    '''
+    Pytohn client for Foursquare 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 = {'client_id': self.client_id,
+                        'response_type': 'code',
+                        'redirect_uri': REDIRECT_URL}
+
+        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 = {'client_id': self.client_id,
+                        'client_secret': self.client_secret,
+                        'grant_type': 'authorization_code',
+                        'redirect_uri': REDIRECT_URL,
+                        'code': code}
+
+        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)))
+
+        self.access_token = response.json()['access_token']
+
+
+    def get_user_info(self, api_version='20140806'):
+        '''
+        Obtains user information.
+
+        Parameters:
+            api_version: string
+                - The API version you would use. This parameter is mandatory by Foursquare.
+
+        Returns:
+            content: Dictionary
+                - A dictionary containing user information.
+		'''
+        USER_INFO_API_URL = 'https://api.foursquare.com/v2/users/self'
+
+        authSettings={'v':api_version,
+                      'oauth_token': self.access_token}
+
+        params = urllib.urlencode(authSettings)
+
+        response = requests.get(USER_INFO_API_URL + '?' + params)
+
+        if response.status_code != 200:
+			raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
+
+        return response.json()['response']['user']

+ 5 - 4
hackathon_starter/hackathon/templates/hackathon/api_examples.html

@@ -17,12 +17,13 @@
 		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/yelp/" style="color: #000"><div style="background-color: #f5f5f5" class="panel panel-default"><div class="panel-body"><img src="http://i.imgur.com/pCmuBIY.png" height="40"> Yelp </div></div></a></div>
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/nytimesarticles/" style="color: #fff"><div style="background-color: #454442" class="panel panel-default"><div class="panel-body"><img src="http://i.imgur.com/e3sjmYj.png" height="40"> New York Times</div></div></a></div>
         <div class="col-sm-4"><a href="http://localhost:8000/hackathon/facebook/" style="color: #fff"><div style="background-color: #3b5998" class="panel panel-default"><div class="panel-body"><img src="http://i.imgur.com/jiztYCH.png" height="40"> Facebook Example</div></div></a></div>
-        
+
         <div class="col-sm-4"><a href="http://localhost:8000/hackathon/google/" style="color: #fff"><div style="background-color: #d95234" class="panel panel-default"><div class="panel-body"><img src="http://upcity.com/blog/wp-content/uploads/2013/11/Google-Plus-Logo-650x318.png" height="40">Google User Info Example</div></div></a></div>
-        
-        <div class="col-sm-4"><a href="http://localhost:8000/hackathon/dropbox/" style="color: #fff"><div style="background-color: #0d56a0" class="panel panel-default"><div class="panel-body"><img src="https://lh6.ggpht.com/fR_IJDfD1becp10IEaG2ly07WO4WW0LdZGUaNSrscqpgr9PI53D3Cp0yd2dXOgyux8w=w300" height="40">Dropbox API</div></div></a></div>
 
+        <div class="col-sm-4"><a href="http://localhost:8000/hackathon/dropbox/" style="color: #fff"><div style="background-color: #0d56a0" class="panel panel-default"><div class="panel-body"><img src="https://lh6.ggpht.com/fR_IJDfD1becp10IEaG2ly07WO4WW0LdZGUaNSrscqpgr9PI53D3Cp0yd2dXOgyux8w=w300" height="40">Dropbox API</div></div></a></div>
+		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/foursquare/" style="color: #000"><div style="background-color: #ffffff" class="panel panel-default"><div class="panel-body"><img src="http://www.atlantamusicguide.com/wp-content/uploads/foursquare-logo.png" height="40">&nbspAPI Example</div></div></a></div>
   	</div>
 
+
 </body>
-</html>
+</html>

+ 71 - 0
hackathon_starter/hackathon/templates/hackathon/foursquare.html

@@ -0,0 +1,71 @@
+<!DOCTYPE html>
+<html>
+	<body>
+		{% include 'hackathon/base.html' %}
+	    <style>
+
+	    </style>
+
+	    <div class="container">
+            <h1> Foursqure API Example</h1>
+            <h2> Get 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>
+				    	{{data.id}}
+			    	</td>
+				</tr>
+
+                <tr>
+			    	<th class="header">First Name<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{data.firstName}}
+			    	</td>
+				</tr>
+
+                <tr>
+			    	<th class="header">Last Name ID<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{data.lastName}}
+			    	</td>
+				</tr>
+
+                <tr>
+			    	<th class="header">Gender<i class="icon-sort"></i></th>
+			    	<td>
+				    	{% if data.gender == 'none' %}
+                            Not Specified
+                        {% else %}
+                            {{data.gender}}
+                        {% endif %}
+			    	</td>
+				</tr>
+
+                <tr>
+			    	<th class="header">Email<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{data.contact.email}}
+			    	</td>
+				</tr>
+
+                <tr>
+			    	<th class="header">Num. of Friends<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{data.friends.count}}
+			    	</td>
+				</tr>
+
+                <tr>
+			    	<th class="header">Num. of Check Ins<i class="icon-sort"></i></th>
+			    	<td>
+				    	{{data.checkins.count}}
+			    	</td>
+				</tr>
+            </table>
+
+
+
+        </div>
+    </body>
+</html>

+ 11 - 7
hackathon_starter/hackathon/templates/hackathon/login.html

@@ -6,7 +6,7 @@
         max-width: 550px;
         padding: 15px;
         margin: 0 auto;
-      }    
+      }
     </style>
 
     <body>
@@ -25,7 +25,7 @@
         </form>
       </div>
 
-      <div class="form-signin">          
+      <div class="form-signin">
         <a class="btn btn-block btn-social btn-twitter" href="http://127.0.0.1:8000/hackathon/twitter_login/">
           <i class="fa fa-twitter"></i>
           Sign in with Twitter
@@ -45,19 +45,23 @@
         <a class="btn btn-block btn-social btn-linkedin" href="http://localhost:8000/hackathon/linkedin_login/">
           <i class="fa fa-linkedin"></i>
           Sign in with LinkedIn
-        </a> 
+        </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> 
+        </a>
         <a class="btn btn-block btn-social btn-google" href="http://localhost:8000/hackathon/google_login/">
           <i class="fa fa-google"></i>
           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> 
+        </a>
+        <a class="btn btn-block btn-social btn-foursquare" href="http://localhost:8000/hackathon/foursquare_login/">
+          <i class="fa fa-foursquare"></i>
+          Sign in with Foursquare
+        </a>
       </div>
     </body>
-</html>
+</html>

+ 3 - 1
hackathon_starter/hackathon/urls.py

@@ -35,6 +35,8 @@ urlpatterns = patterns('',
     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'^foursquare_login/$', views.foursquare_login, name='foursquare_login'),
+    url(r'^foursquare/$', views.foursquare, name='foursquare'),
     url(r'^quandlSnp500/$', views.quandlSnp500, name='quandlsnp500'),
     url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
     url(r'^quandlNasdaqdiff/$', views.quandlNasdaqdiff, name='quandlnasdaqdiff'),
@@ -51,4 +53,4 @@ urlpatterns = patterns('',
     url(r'^meetupToken/$', views.meetupToken, name='meetupToken'),
     url(r'^meetupUser/$', views.meetupUser, name='meetupUser'),
     url(r'^yelp/$', views.yelp, name='yelp'),
-)
+)

+ 44 - 1
hackathon_starter/hackathon/views.py

@@ -30,6 +30,7 @@ from scripts.yelp import requestData
 from scripts.facebook import *
 from scripts.googlePlus import *
 from scripts.dropbox import *
+from scripts.foursquare import *
 
 # Python
 import oauth2 as oauth
@@ -38,7 +39,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, DropboxProfile
+from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile, FacebookProfile, TumblrProfile, GoogleProfile, DropboxProfile, FoursquareProfile
 from hackathon.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 
@@ -52,6 +53,7 @@ getLinkedIn = LinkedinOauthClient(settings.LINKEDIN_CLIENT_ID, settings.LINKEDIN
 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)
+getFoursquare = FoursquareOauthClient(settings.FOURSQUARE_APP_ID, settings.FOURSQUARE_APP_SECRET)
 
 def index(request):
     print "index: " + str(request.user)
@@ -224,6 +226,34 @@ def index(request):
                 user = authenticate(username=username+'_dropbox', password='password')
                 login(request, user)
 
+            elif profile_track == 'foursquare':
+                code = request.GET['code']
+                getFoursquare.get_access_token(code)
+                userInfo = getFoursquare.get_user_info()
+                username = userInfo['firstName'] + userInfo['lastName']
+
+                try:
+                    user = User.objects.get(username=username+'_foursquare')
+                except User.DoesNotExist:
+                    new_user = User.objects.create_user(username+'_foursquare', username+'@madewithfoursquare', 'password')
+                    new_user.save()
+
+                    try:
+                        profile = FoursquareProfile.object.get(user=new_user.id)
+                        profile.access_token = getFoursquare.access_token
+
+                    except:
+                        profile = FoursquareProfile()
+                        profile.user = new_user
+                        profile.foursquare_id = userInfo['id']
+                        profile.access_token = getFoursquare.access_token
+                    profile.save()
+
+                user = authenticate(username=username+'_foursquare', password='password')
+                login(request, user)
+
+
+
 
 
     else:
@@ -347,6 +377,13 @@ def dropboxSearchFile(request):
             raise(Exception('Invalid response, response code {c}'.format(c=response.status_code)))
 
         return render(request, 'hackathon/dropboxSearchFile.html', {'data': response.json()})
+#######################
+#    FOURSQUARE API   #
+#######################
+
+def foursquare(request):
+    userInfo = getFoursquare.get_user_info()
+    return render(request, 'hackathon/foursquare.html', {'data' : userInfo})
 
 
 #################
@@ -800,3 +837,9 @@ def dropbox_login(request):
     profile_track = 'dropbox'
     dropbox_url = getDropbox.get_authorize_url()
     return HttpResponseRedirect(dropbox_url)
+
+def foursquare_login(request):
+    global profile_track
+    profile_track = 'foursquare'
+    forsquare_url = getFoursquare.get_authorize_url()
+    return HttpResponseRedirect(forsquare_url)

+ 3 - 0
hackathon_starter/hackathon_starter/settings.py

@@ -153,3 +153,6 @@ GOOGLE_PLUS_APP_SECRET = 'mv1ZcpHqMF6uX7NRTLDC2jXR'
 
 DROPBOX_APP_ID = '8et85bx2ur6b1fb'
 DROPBOX_APP_SECRET = 'xx0virsvtghxlui'
+
+FOURSQUARE_APP_ID = '2V342MA2PZQEKABT450WJQKKRHV0QPFMOUBA1ZHXKWZ5YZ1Y'
+FOURSQUARE_APP_SECRET = 'PC0O1JQWP24EAPPLXNRIJVVBN5D2DW3XD5GJGGSQWIESYN1B'