diff --git a/README.md b/README.md index 6d48a0b..676100d 100644 --- a/README.md +++ b/README.md @@ -9,15 +9,11 @@ Even if you are not using this for a hackathon, Django Hackathon Starter is sure

Basic Authentication / OAuth Signin

-![Login](https://github.com/DrkSephy/drksephy.github.io/blob/master/img/login.png) +![Login](http://i.imgur.com/sEIHsIS.png)

API Examples

-![API Examples](https://github.com/DrkSephy/drksephy.github.io/blob/master/img/api_examples.png) - -

Twitter Example

- -![Twitter Tweets](http://i.imgur.com/tHZrgoK.png) +![API Examples](http://i.imgur.com/zFqKcVa.png) Table of Contents ----------------- @@ -34,10 +30,20 @@ Features -------- * User Registration * Sphinx Documentation -* Django Nosetests +* Django Nosetests +* Integration with Django Rest Framework * Basic Authentication with username and password -* **OAuth 2.0 Authentication** for Github, LinkedIn and Instagram -* **OAuth 1.0a Authentication** for Twitter and Tumblr +* **OAuth 2.0 Authentication** + * Github + * LinkedIn + * Instagram + * Facebook + * Google+ + * Dropbox + * Foursquare +* **OAuth 1.0a Authentication** + * Twitter + * Tumblr * **API Examples** * Yelp API * Github API @@ -45,11 +51,15 @@ Features * Tumblr API * Twitter API * Twilio API - * Meetup API + * Meetup API * Steam API * Quandl Stock API * New York Times API * LinkedIn API + * Facebook API + * Google+ API + * Dropbox API + * Foursquare API
@@ -67,14 +77,14 @@ To get up and running, simply do the following: $ git clone https://github.com/DrkSephy/django-hackathon-starter.git $ cd django-hackathon-starter - + # Install the requirements $ pip install -r requirements.txt - + # Install bower $ npm install -g bower $ bower install - + # Perform database migrations $ python manage.py makemigrations $ python manage.py migrate @@ -82,11 +92,8 @@ 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**: 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`. - -
- + Getting API Keys ---------------- @@ -111,7 +118,7 @@ Getting API Keys * For `redirect url` field, enter: `http://127.0.0.1:8000/hackathon/` 3. Within `settings.py`, add the following: * `MEETUP_CONSUMER_KEY` = `Meetup key` - * `MEETUP_CONSUMER_SECRET` = `Meetup secret key` + * `MEETUP_CONSUMER_SECRET` = `Meetup secret key`
@@ -119,7 +126,7 @@ Getting API Keys 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) -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) 5. Within `scripts/twilioapi.py`: * Replace `account_sid` with your own Twilio `account_sid` @@ -172,7 +179,6 @@ Getting API Keys * `INSTAGRAM_CLIENT_ID` = `Instagram-client-id` * `INSTAGRAM_CLIENT_SECRET` = `Instagram-client-secret` -
@@ -193,17 +199,99 @@ Getting API Keys 1. Register an account on [Facebook.com](http://www.facebook.com.com/) -2. Visit [Facebook Developer Network page](https://developers.facebook.com/) -3. After logging in, Click on **My Apps** and then on **Add a New App+** - * Choose Website as the platform and add the **name** for your project - * Click on **Create New Facebook APP ID** and choose the **Category** of your application +2. Visit [Facebook Developers page](https://developers.facebook.com/) +3. After logging in, Click on **My Apps** and then on **Add a New App** + * Choose W**ebsite** as the platform and add the **name** for your project + * Give your app a name. + * Choose the category your app falls into. * Click **Create App ID** -4. After the captcha, scroll down past the quick start and add `http://localhost:8000/` -5. Within your `views.py` add the **App ID** in `yourappid` underneath the view for your facebook application. + * Skip the quickstart process and you will be redirected to the app dashboard. +4. Copy the **app ID** and the **app secret**. +5. From the left menu choose the **Settings** option. +6. Click on **Add Platform** and choose **Website** once again. +7. Under **site URL**, specift the URL to be redirected after authentication is complete. +8. Click save. +9. In ```settings.py``` change the following values: + * ```FACEBOOK_APP_ID = your_app_id``` + * ```FACEBOOK_APP_SECRET = your_app_secret``` + + +
+ + +1. Register an account on [Google.com](https://accounts.google.com/signup). +2. Navigate to [Google Developer Console](https://console.developers.google.com/project). +3. Click on **Create Project**, give your app a name and click **Create** (this might take a few sceonds). +4. You will be redirected to the project dashboard. From the left menu choose **APIs & auth** and then choose **APIs**. +5. Choose the API you would like to use (the built in example uses **Google+ API**). +6. Click on **Enable API**. +7. From the side menu, under **APIs & auth** select **consent screen**. + * Fill your app name under **Product Name**. + * Hit **save** button on the bottom. +8. From the side menu, under **APIs & auth** select credentials: + * Click on **Create new Client ID**. + * Under **Authorized JavaScript origins** specify you app base address (e.g ```http://localhost:8000```). + * Under **Authorized redirect URIs** specify the URL to be redirected after authentication is complete. + * Hit **Create Client ID** button (this might also take a few seconds). +9. Copy your new generated ```client_id``` and ```client_secret```: +10. Under ```settings.py``` change the following values: + * ```GOOGLE_PLUS_APP_ID = your_client_id``` + * ```GOOGLE_PLUS_APP_SECRET = your_client_secret```
+ + +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 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``` +
+ + + +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``` +
+ + + + +1. Register an account on Tumblr.com. +2. Visit Tumblr applications page. +3. Click on Register Application. + * Enter your application information. + * 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` + +
+ + 1. Register an account on [Steam](https://store.steampowered.com/join/) @@ -227,11 +315,11 @@ Getting API Keys
- + 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`
@@ -241,37 +329,40 @@ Project Structure | Name | Description | | ---------------------------------- |:-----------------------------------------------------------:| -| **hackathon_starter/hackathon_starter**/settings.py | Django settings module containing database and API keys/tokens.| -| **hackathon_starter/hackathon**/admin.py | Registered models for Django's admin page.| -| **hackathon_starter/hackathon**/models.py | Django models and profiles for user login.| -| **hackathon_starter/hackathon**/tests.py | Integration tests.| -| **hackathon_starter/hackathon**/urls.py | Django Hackathon Starter URL dispatcher.| -| **hackathon_starter/hackathon**/views.py | Django views file.| -| **hackathon_starter/hackathon**/serializers.py | Allows JSON representation for Django Model fields.| -| **hackathon_starter/hackathon**/forms.py | Basic form fields.| -| **hackathon_starter/hackathon/static/** | Front-end JavaScript / CSS files.| -| **hackathon_starter/hackathon/unittests** | Unit tests.| -| **hackathon_starter/hackathon/scripts/** | API Example scripts.| -| **hackathon_starter/hackathon/scripts/**github.py | Script for interacting with Github API. | -| **hackathon_starter/hackathon/scripts/**instagram.py| Script for interacting with Instagram API.| -| **hackathon_starter/hackathon/scripts/**linkedin.py | Script for interacting with LinkedIn API. | -| **hackathon_starter/hackathon/scripts/**meetup.py | Script for interacting with Meetup API. | -| **hackathon_starter/hackathon/scripts/**nytimes.py | Script for interacting with New York Times API. | -| **hackathon_starter/hackathon/scripts/**quandl.py | Script for interacting with Quandl API. | -| **hackathon_starter/hackathon/scripts/**scraper.py | Basic web scraper for getting sales from Steam. | -| **hackathon_starter/hackathon/scripts/**steam.py | Script for interacting with Steam API. | -| **hackathon_starter/hackathon/scripts/**tumblr.py | Script for interacting with Tumblr API. | -| **hackathon_starter/hackathon/scripts/**twilioapi.py | Script for interacting with Twilio API. | -| **hackathon_starter/hackathon/scripts/**twitter.py | Script for interacting with Twitter API. | -| **hackathon_starter/hackathon/scripts/**yelp.py | Script for interacting with Yelp API. | -| **hackathon_starter/hackathon/templates/**hackathon/ | Templates for API examples. | -| **hackathon_starter/hackathon/templates/**hackathon/base.html | Base template, contains navbar. | -| **hackathon_starter/hackathon/templates/**hackathon/api_examples.html | Template for API Examples page. | +| **hackathon_starter**/settings.py | Django settings module containing database and API keys/tokens| +| **hackathon**/admin.py | Registered models for Django's admin page| +| **hackathon**/models.py | Django models and profiles for user login| +| **hackathon**/tests.py | Integration tests| +| **hackathon**/urls.py | Django Hackathon Starter URL dispatcher| +| **hackathon**/views.py | Django views file| +| **hackathon**/serializers.py | Allows JSON representation for Django Model fields| +| **hackathon**/forms.py | Basic form fields| +| **hackathon/static/** | Front-end JavaScript / CSS files| +| **hackathon/unittests** | Unit tests| +| **hackathon/scripts/** | API Example scripts| +| **hackathon/scripts/**github.py | Script for interacting with Github API | +| **hackathon/scripts/**instagram.py| Script for interacting with Instagram API| +| **hackathon/scripts/**linkedin.py | Script for interacting with LinkedIn API | +| **hackathon/scripts/**meetup.py | Script for interacting with Meetup API | +| **hackathon/scripts/**nytimes.py | Script for interacting with New York Times API | +| **hackathon/scripts/**quandl.py | Script for interacting with Quandl API | +| **hackathon/scripts/**scraper.py | Basic web scraper for getting sales from Steam | +| **hackathon/scripts/**facebook.py | Script for interacting with Facebook API | +| **hackathon/scripts/**dropbox.py | Script for interacting with Dropbox API | +| **hackathon/scripts/**foursquare.py | Script for interacting with Foursquare API | +| **hackathon/scripts/**googlePlus.py | Script for interacting with Google+ API | +| **hackathon/scripts/**steam.py | Script for interacting with Steam API | +| **hackathon/scripts/**tumblr.py | Script for interacting with Tumblr API | +| **hackathon/scripts/**twilioapi.py | Script for interacting with Twilio API | +| **hackathon/scripts/**twitter.py | Script for interacting with Twitter API | +| **hackathon/scripts/**yelp.py | Script for interacting with Yelp API | +| **hackathon/templates/**hackathon/ | Templates for API examples | +| **hackathon/templates/**hackathon/base.html | Base template, contains navbar | 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 @@ -298,5 +389,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, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - diff --git a/hackathon_starter/hackathon/admin.py b/hackathon_starter/hackathon/admin.py index fce2802..c2c0a74 100644 --- a/hackathon_starter/hackathon/admin.py +++ b/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 @@ class TwitterProfileAdmin(admin.ModelAdmin): admin.site.register(GithubProfile) admin.site.register(MeetupToken) admin.site.register(LinkedinProfile) - +admin.site.register(TumblrProfile) diff --git a/hackathon_starter/hackathon/models.py b/hackathon_starter/hackathon/models.py index d9e098f..a5252d6 100644 --- a/hackathon_starter/hackathon/models.py +++ b/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) @@ -66,4 +75,31 @@ class MeetupToken(models.Model): access_token = models.CharField(max_length=200) def __unicode__(self): - return unicode(self.access_token) \ No newline at end of file + 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) + +class GoogleProfile(models.Model): + user = models.ForeignKey(User) + 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) + +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) + + +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) diff --git a/hackathon_starter/hackathon/scripts/dropbox.py b/hackathon_starter/hackathon/scripts/dropbox.py new file mode 100644 index 0000000..712e5f3 --- /dev/null +++ b/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() diff --git a/hackathon_starter/hackathon/scripts/facebook.py b/hackathon_starter/hackathon/scripts/facebook.py new file mode 100644 index 0000000..64018fd --- /dev/null +++ b/hackathon_starter/hackathon/scripts/facebook.py @@ -0,0 +1,153 @@ +import requests +import urllib +import simplejson as json + +########################## +# FACEBOOK API CONSTANTS # +########################## + +AUTHORIZE_URL = 'https://graph.facebook.com/oauth/authorize' +ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token' +API_URL = 'https://graph.facebook.com/v2.3/' +REQUEST_PERMISSIONS_URL = "https://www.facebook.com/dialog/oauth?" + +class FacebookOauthClient(object): + ''' + Python client for Facebook API + ''' + + access_token = None + permission_request_url = 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() + + + + + def get_user_likes(self): + ''' + Obtains a list of all the user likes. Require a special permission + via Facebook. + + Returns: + content: dictionary + -A dictionary containing user likes. + ''' + #Check if permission exists or ask for it + if not self.check_permissions('user_likes'): + requestedPermissionUrl = self.request_permissions('user_likes') + + #Get likes + response = requests.get(API_URL + 'me/likes?access_token={at}'.format(at=self.access_token)) + return response.json()['data'] + + + + def check_permissions(self, perm): + ''' + Checks if the app has the specified permission. + + Parameters: + perm: String + - The desired permission (such as user_likes) + + Returns: + bool + - True if the permission granted or false otherwise. + ''' + + permDict = {'status': 'granted', 'permission':perm} + response = requests.get(API_URL + 'me/permissions?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))) + + currentPermissions = response.json()['data'] + if permDict in currentPermissions: + return True + return False + + + def request_permissions(self, perm): + ''' + Requests a permission from the user. + + Parameters: + perm: String + - The permission we would like to get. + + Returns: String + - The URL to redirect the user in order to get the permission. + ''' + authSettings = {'client_id' : self.client_id, + 'redirect_uri' : 'http://localhost:8000/hackathon/', + 'auth_type' : 'rerequest', + 'scope' : perm, + 'access_token' : access_token} + params = urllib.urlencode(authSettings) + self.permission_request_url = REQUEST_PERMISSIONS_URL + '?' + params + \ No newline at end of file diff --git a/hackathon_starter/hackathon/scripts/foursquare.py b/hackathon_starter/hackathon/scripts/foursquare.py new file mode 100644 index 0000000..a436b08 --- /dev/null +++ b/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'] diff --git a/hackathon_starter/hackathon/scripts/googlePlus.py b/hackathon_starter/hackathon/scripts/googlePlus.py new file mode 100644 index 0000000..573dfb6 --- /dev/null +++ b/hackathon_starter/hackathon/scripts/googlePlus.py @@ -0,0 +1,109 @@ +import requests +import urllib +import simplejson as json +import random +import string + + +AUTHORISE_URL = 'https://accounts.google.com/o/oauth2/auth' +ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token' +REDIRECT_URL = 'http://localhost:8000/hackathon/' +PROFILE_API = 'https://www.googleapis.com/auth/plus.login' + +class GooglePlus: + + access_token = None + session_id = None + + def __init__(self, client_id, client_secret): + ''' + Parameters: + client_id: string + - The client ID from the registering app on Google. + + client_secret: string + -The client secret from the registering app on Google. + ''' + self.client_id = client_id + self.client_secret = client_secret + + + def get_session_id(self, length=50): + ''' + Generates a random session ID. As a part from the authentication process + we need to verify that the response we get from the server contains the + same session ID as we sent. + + Parameters: + length: integer + - The length of the session ID. + ''' + chars = string.uppercase + string.digits + string.lowercase + self.session_id = ''.join(random.choice(chars) for _ in range(length)) + + + def get_authorize_url(self): + ''' + Obtains authorize url link with the given client_id. + + Returns: + authURL: string + - The authorization URL. + ''' + + self.get_session_id() + authSettings = {'state': self.session_id, + 'redirect_uri':REDIRECT_URL, + 'response_type':'code', + 'client_id':self.client_id, + 'scope': PROFILE_API} + + params = urllib.urlencode(authSettings) + return AUTHORISE_URL + '?' + params + + + def get_access_token(self, code, state): + ''' + Obtains access token. + + Parameters: + code: string + - The code is retrived from the authorization URL parameter + to obtain access token. + state: string + - The unique session ID. + ''' + + #Checking that the sessino ID from the response match the session ID we sent + if state != self.session_id: + raise(Exception('Danger! Someone is messing up with you connection!')) + + authSettings = {'client_secret': self.client_secret, + 'code':code, + 'grant_type':'authorization_code', + 'client_id': self.client_id, + '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): + ''' + Obtain user information. + + Returns: + content: dictionary + - A dictionary contains user information. + ''' + USER_INFO_API = 'https://www.googleapis.com/oauth2/v2/userinfo' + 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() \ No newline at end of file diff --git a/hackathon_starter/hackathon/scripts/linkedin.py b/hackathon_starter/hackathon/scripts/linkedin.py index 6667478..5a4d444 100644 --- a/hackathon_starter/hackathon/scripts/linkedin.py +++ b/hackathon_starter/hackathon/scripts/linkedin.py @@ -21,7 +21,7 @@ def get_authorize_url(self): '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 diff --git a/hackathon_starter/hackathon/scripts/tumblr.py b/hackathon_starter/hackathon/scripts/tumblr.py index 3d0c188..dec46d6 100644 --- a/hackathon_starter/hackathon/scripts/tumblr.py +++ b/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 @@ def access_token_url(self, oauth_verifier=''): ''' 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 @@ def getUserInfo(self): #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 diff --git a/hackathon_starter/hackathon/templates/hackathon/api_examples.html b/hackathon_starter/hackathon/templates/hackathon/api_examples.html index dd9dc76..3ddc3e1 100644 --- a/hackathon_starter/hackathon/templates/hackathon/api_examples.html +++ b/hackathon_starter/hackathon/templates/hackathon/api_examples.html @@ -4,22 +4,26 @@
-
Github Example
-
Steam Example
-
Tumblr Example
-
LinkedIn Example
-
Twilio Example
-
Instagram Example
-
Instagram Media by Location Example
-
Twitter Example
-
Twitter Tweet Example
-
Quandl Example
-
Meetup
-
Yelp
-
New York Times
-
Facebook JDK Exmaple
+
GitHub Example
+
Steam Example
+
Tumblr Example
+
LinkedIn Example
+
Twilio Example
+
Instagram Example
+
Instagram Media by location
+
Twitter Example
+
Quandl Example
+
Meet Up
+
Yelp
+
New York Times
+
Facebook Example
+
Google User Info Example
+ +
Dropbox API
+
 API Example
+ - \ No newline at end of file + diff --git a/hackathon_starter/hackathon/templates/hackathon/base.html b/hackathon_starter/hackathon/templates/hackathon/base.html index 35f7db0..ac32729 100644 --- a/hackathon_starter/hackathon/templates/hackathon/base.html +++ b/hackathon_starter/hackathon/templates/hackathon/base.html @@ -24,7 +24,7 @@ - Django Hackathon Starter + Django Hackathon Starter diff --git a/hackathon_starter/hackathon/templates/hackathon/dropbox.html b/hackathon_starter/hackathon/templates/hackathon/dropbox.html new file mode 100644 index 0000000..7a30127 --- /dev/null +++ b/hackathon_starter/hackathon/templates/hackathon/dropbox.html @@ -0,0 +1,65 @@ + + + + {% include 'hackathon/base.html' %} + + + +
+

Dropbox API Usage Example

+
+

Basic User Info

+ + + + + + + + + + + + + + + + + + + + +
User ID + {{userInfo.uid}} +
Name + {{userInfo.display_name}} +
Email + {{userInfo.email}} +
Country + {{userInfo.country}} +
+ +
+ +

Search Files Example

+ +
+ {% csrf_token %} + {% load bootstrap %} + +
+ + +
+
+ + \ No newline at end of file diff --git a/hackathon_starter/hackathon/templates/hackathon/dropboxSearchFile.html b/hackathon_starter/hackathon/templates/hackathon/dropboxSearchFile.html new file mode 100644 index 0000000..5ebf223 --- /dev/null +++ b/hackathon_starter/hackathon/templates/hackathon/dropboxSearchFile.html @@ -0,0 +1,45 @@ + + + + {% include 'hackathon/base.html' %} + + +
+

Back to Search

+

Search Results:

+
+ + {% if data %} + + + + + + + + + + + {% for element in data %} + + + + + + + {% endfor %} + +
Type Path Size Modified
+ {% if element.is_dir %} + Folder + {% else %} + File + {% endif %} + {{ element.path }} {{ element.size }} {{ element.modified }}
+ + {% else %} +

No files were found

+ {% endif %} +
+ + diff --git a/hackathon_starter/hackathon/templates/hackathon/facebook.html b/hackathon_starter/hackathon/templates/hackathon/facebook.html deleted file mode 100644 index affd533..0000000 --- a/hackathon_starter/hackathon/templates/hackathon/facebook.html +++ /dev/null @@ -1,109 +0,0 @@ - - - -Facebook Login JavaScript Example - - - -{% include 'hackathon/base.html' %} - - - - - - - - - -
-
- - - \ No newline at end of file diff --git a/hackathon_starter/hackathon/templates/hackathon/facebookAPIExample.html b/hackathon_starter/hackathon/templates/hackathon/facebookAPIExample.html new file mode 100644 index 0000000..dc0e94b --- /dev/null +++ b/hackathon_starter/hackathon/templates/hackathon/facebookAPIExample.html @@ -0,0 +1,58 @@ + + + + {% include 'hackathon/base.html' %} + + +
+

Facebook API Usage Example

+
+

Basic User Info

+ + + + + + + + + + + + + + + + + + + + + + + + + +
User ID + {{userInfo.id}} +
First Name + {{userInfo.first_name}} +
Last Name + {{userInfo.last_name}} +
Gender + {{userInfo.gender}} +
Time Zone + GMT{{userInfo.timezone}} +
Profile + {{userInfo.link}} +
+
+ Every Facebook account basic information is available for all apps by default. In order to get more information about a user + (such as likes, photos, status updates, etc.) you must submit a request to facebook which you will find in the Facebook app page. + After gaining the desired permissions, you can call check_permissions(self, perm) to check if you gained permission from the user and request_permissions to request the permission from the user. +
+ + + \ No newline at end of file diff --git a/hackathon_starter/hackathon/templates/hackathon/foursquare.html b/hackathon_starter/hackathon/templates/hackathon/foursquare.html new file mode 100644 index 0000000..aa9ed5f --- /dev/null +++ b/hackathon_starter/hackathon/templates/hackathon/foursquare.html @@ -0,0 +1,71 @@ + + + + {% include 'hackathon/base.html' %} + + +
+

Foursqure API Example

+

Get Basic User Info

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
User ID + {{data.id}} +
First Name + {{data.firstName}} +
Last Name ID + {{data.lastName}} +
Gender + {% if data.gender == 'none' %} + Not Specified + {% else %} + {{data.gender}} + {% endif %} +
Email + {{data.contact.email}} +
Num. of Friends + {{data.friends.count}} +
Num. of Check Ins + {{data.checkins.count}} +
+ + + +
+ + diff --git a/hackathon_starter/hackathon/templates/hackathon/googlePlus.html b/hackathon_starter/hackathon/templates/hackathon/googlePlus.html new file mode 100644 index 0000000..5765dad --- /dev/null +++ b/hackathon_starter/hackathon/templates/hackathon/googlePlus.html @@ -0,0 +1,52 @@ + + + + {% include 'hackathon/base.html' %} + +
+

Google Plus API Example

+

Basic User Info

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
User ID + {{userInfo.id}} +
First Name + {{userInfo.given_name}} +
Last Name + {{userInfo.family_name}} +
Gender + {{userInfo.gender}} +
Profile + {{userInfo.link}} +
+ +
+ + \ No newline at end of file diff --git a/hackathon_starter/hackathon/templates/hackathon/login.html b/hackathon_starter/hackathon/templates/hackathon/login.html index 93a374e..12d63e9 100644 --- a/hackathon_starter/hackathon/templates/hackathon/login.html +++ b/hackathon_starter/hackathon/templates/hackathon/login.html @@ -6,7 +6,7 @@ max-width: 550px; padding: 15px; margin: 0 auto; - } + } @@ -25,7 +25,7 @@

Login

-
+
Sign in with Twitter @@ -45,7 +45,23 @@ Sign in with LinkedIn - + + + + Sign in with Facebook + + + + Sign in with Google+ + + + + Sign in with Dropbox + + + + Sign in with Foursquare +
- \ No newline at end of file + diff --git a/hackathon_starter/hackathon/templates/hackathon/register.html b/hackathon_starter/hackathon/templates/hackathon/register.html index 7e7367e..0745426 100644 --- a/hackathon_starter/hackathon/templates/hackathon/register.html +++ b/hackathon_starter/hackathon/templates/hackathon/register.html @@ -5,7 +5,7 @@ {% if registered %} Thank you for registering! - Return to the homepage.
+ Return to the homepage.
{% else %}
diff --git a/hackathon_starter/hackathon/unittests/testsnippets.py b/hackathon_starter/hackathon/unittests/testsnippets.py new file mode 100644 index 0000000..b6a8f48 --- /dev/null +++ b/hackathon_starter/hackathon/unittests/testsnippets.py @@ -0,0 +1,45 @@ +from hackathon.models import Snippet +from rest_framework import status +from rest_framework.test import APITestCase + + +class SnippetViewTestCase(APITestCase): + def setUp(self): + self.s1 = Snippet.objects.create(title='t1', code="""print("Hello, World.")""") + self.s2 = Snippet.objects.create(title='t2', code="""print("Goodbye, World.")""") + super(SnippetViewTestCase, self).setUp() + + def test_list(self): + response = self.client.get('/hackathon/snippets/') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(len(response.data), 2) + + def test_detail(self): + response = self.client.get('/hackathon/snippets/{}/'.format(self.s1.id)) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.data['id'], self.s1.id) + + def test_create(self): + payload = {'title': 't3', 'code': """print("Create, World.")"""} + response = self.client.post('/hackathon/snippets/', payload) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + self.assertEqual(response.data['title'], 't3') + self.assertEqual(response.data['code'], """print("Create, World.")""") + + def test_update(self): + payload = {'title': 't666', 'code': '2 + 2'} + response = self.client.put('/hackathon/snippets/{}/'.format(self.s1.id), payload) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.data['title'], 't666') + self.assertEqual(response.data['code'], '2 + 2') + + def test_partial_update(self): + payload = {'title': 't666'} + response = self.client.patch('/hackathon/snippets/{}/'.format(self.s1.id), payload) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.data['title'], 't666') + + def test_delete(self): + response = self.client.delete('/hackathon/snippets/{}/'.format(self.s1.id)) + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + self.assertEqual(Snippet.objects.count(), 1) diff --git a/hackathon_starter/hackathon/urls.py b/hackathon_starter/hackathon/urls.py index 516ce8d..f6d6745 100644 --- a/hackathon_starter/hackathon/urls.py +++ b/hackathon_starter/hackathon/urls.py @@ -1,9 +1,13 @@ -from django.conf.urls import patterns, url +from django.conf.urls import patterns, url, include +from rest_framework.routers import DefaultRouter from hackathon import views +router = DefaultRouter() +router.register(r'snippets', views.SnippetView) + urlpatterns = patterns('', - url(r'^$', views.index, name='index'), + url(r'^', include(router.urls)), url(r'^register/$', views.register, name='register'), url(r'^login/$', views.user_login, name='login'), url(r'^logout/$', views.user_logout, name='logout'), @@ -15,7 +19,6 @@ url(r'^githubTopRepositories/$', views.githubTopRepositories, name='githubTopRepositories'), url(r'^tumblr/$', views.tumblr, name='tumblr'), url(r'^linkedin/$', views.linkedin, name='linkedin'), - url(r'^snippets/$', views.snippet_list, name='snippets'), url(r'^twilio/$', views.twilio, name='twilio'), url(r'^instagram/$', views.instagram, name='instagram'), url(r'^instagram_login/$', views.instagram_login, name='instagram_login'), @@ -28,7 +31,15 @@ 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_login/$', views.facebook_login, name='facebook_login'), 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'^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'), @@ -45,4 +56,4 @@ url(r'^meetupToken/$', views.meetupToken, name='meetupToken'), url(r'^meetupUser/$', views.meetupUser, name='meetupUser'), url(r'^yelp/$', views.yelp, name='yelp'), -) \ No newline at end of file +) diff --git a/hackathon_starter/hackathon/views.py b/hackathon_starter/hackathon/views.py index 8d03a99..2370b2a 100644 --- a/hackathon_starter/hackathon/views.py +++ b/hackathon_starter/hackathon/views.py @@ -11,8 +11,11 @@ from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse +# Django REST Framework +from rest_framework import viewsets, mixins + # 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 * @@ -24,15 +27,18 @@ from scripts.meetup import * from scripts.linkedin import LinkedinOauthClient 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 import simplejson as json -from rest_framework.renderers import JSONRenderer -from rest_framework.parsers import JSONParser +import requests # Models -from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile +from hackathon.models import * from hackathon.serializers import SnippetSerializer from hackathon.forms import UserForm @@ -43,6 +49,10 @@ 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) +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) @@ -66,13 +76,11 @@ def index(request): except GithubProfile.DoesNotExist: profile = GithubProfile(user=new_user, access_token=getGithub.access_token, scopes=getGithub.scopes ,github_user=getGithub.username) profile.save() - #profile = GithubProfile(user=new_user, access_token=getGithub.access_token, scopes=getGithub.scopes ,github_user=getGithub.username) - #profile.save() user = authenticate(username=getGithub.username+'_github', password='password') 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) @@ -88,7 +96,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' @@ -117,6 +125,134 @@ 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) + 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'] + state = request.GET['state'] + getGoogle.get_access_token(code, state) + userInfo = getGoogle.get_user_info() + username = userInfo['given_name'] + userInfo['family_name'] + + try: + user = User.objects.get(username=username+'_google') + except User.DoesNotExist: + new_user = User.objects.create_user(username+'_google', username+'@madewithgoogleplus', 'password') + new_user.save() + + try: + profle = GoogleProfile.objects.get(user = new_user.id) + profile.access_token = getGoogle.access_token + except: + profile = GoogleProfile() + profile.user = new_user + profile.google_user_id = userInfo['id'] + profile.access_token = getGoogle.access_token + profile.profile_url = userInfo['link'] + profile.save() + 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) + + 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: if request.GET.items(): user = User.objects.get(username = request.user.username) @@ -143,7 +279,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']) @@ -158,6 +294,18 @@ 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'} return render(request, 'hackathon/index.html', context) @@ -176,7 +324,6 @@ def api_examples(request): ################# def steam(request): - #Should link to test of Steam API example. key = '231E98D442E52B87110816C3D5114A1D' SteamUN = "Marorin" steamID = steamidpulling(SteamUN, key) @@ -192,9 +339,48 @@ def steamDiscountedGames(request): ################# def facebook(request): - '''A sample application that will publish a status update after going into the login process using the Javascript SDK ''' - yourappid = '364831617044713' - return render(request, 'hackathon/facebook.html', { 'yourappid' : yourappid }) + ''' + This is an example of getting basic user info and display it + ''' + userInfo = getFacebook.get_user_info() + return render(request, 'hackathon/facebookAPIExample.html', { 'userInfo' : userInfo}) + +################# +# 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()}) + +####################### +# FOURSQUARE API # +####################### + +def foursquare(request): + userInfo = getFoursquare.get_user_info() + return render(request, 'hackathon/foursquare.html', {'data' : userInfo}) ################# @@ -218,15 +404,13 @@ def meetup(request): return HttpResponseRedirect(AUTHORIZE_URL) def meetupToken(request): - # print request.GET.get('code') access_token_url = 'https://secure.meetup.com/oauth2/access?' REDIRECT_URI = 'http://127.0.0.1:8000/hackathon/meetupToken' url = access_token_url + 'client_id=' + settings.MEETUP_CONSUMER_KEY + '&client_secret=' + settings.MEETUP_CONSUMER_SECRET + '&grant_type=authorization_code' + '&redirect_uri=' + REDIRECT_URI + '&code=' + request.GET.get('code') response = requests.post(url) access_token = json.loads(response.content)['access_token'] - # print access_token - #if not MeetupToken.objects.all()[0]: + if not MeetupToken.objects.all().exists(): meetupToken = MeetupToken(access_token = access_token) meetupToken.save() @@ -235,7 +419,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] @@ -337,7 +521,6 @@ def githubUser(request): user = request.POST.get('user') parsedData['userData'] = getUserData(user, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET) return render(request, 'hackathon/github.html', {'data': parsedData}) - # return JsonResponse({ 'data': parsedData }) def githubTopRepositories(request): '''Returns Top Commited Repositories for a specific Github User''' @@ -351,11 +534,10 @@ def githubTopRepositories(request): parsedData['committed'] = filtered print parsedData return render(request, 'hackathon/githubTopRepositories.html', {'data': parsedData}) - # return JsonResponse({ 'data': parsedData }) 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) @@ -377,34 +559,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) @@ -430,7 +597,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) @@ -495,7 +662,6 @@ def twitter(request): def twitterTweets(request): print getTwitter.is_authorized if getTwitter.is_authorized: - #content = getTwitter.get_tweets() if request.method == 'GET': if request.GET.items(): tweets = request.GET.get('tweets') @@ -520,7 +686,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) @@ -533,24 +699,17 @@ def linkedin(request): # Snippet RESTful Model # ######################### -class JSONResponse(HttpResponse): - """ - An HttpResponse that renders its content into JSON. - """ - def __init__(self, data, **kwargs): - content = JSONRenderer().render(data) - kwargs['content_type'] = 'application/json' - super(JSONResponse, self).__init__(content, **kwargs) - -@csrf_exempt -def snippet_list(request): - """ - List all code snippets, or create a new snippet. - """ - if request.method == 'GET': - snippets = Snippet.objects.all() - serializer = SnippetSerializer(snippets, many=True) - return JSONResponse(serializer.data) +class CRUDBaseView(mixins.ListModelMixin, + mixins.CreateModelMixin, + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + viewsets.GenericViewSet): + pass + +class SnippetView(CRUDBaseView): + serializer_class = SnippetSerializer + queryset = Snippet.objects.all() ################## @@ -580,12 +739,13 @@ def register(request): user.set_password(user.password) user.save() registered = True + return HttpResponseRedirect('/hackathon/login/') else: print user_form.errors else: user_form = UserForm() - + return render(request, 'hackathon/register.html', {'user_form': user_form, 'registered': registered} ) @@ -600,7 +760,7 @@ def user_login(request): if user: if user.is_active: login(request, user) - return HttpResponseRedirect('/hackathon/') + return HttpResponseRedirect('/hackathon/api/') else: return HttpResponse("Your Django Hackathon account is disabled.") else: @@ -612,7 +772,7 @@ def user_login(request): def user_logout(request): logout(request) - return HttpResponseRedirect('/hackathon/') + return HttpResponseRedirect('/hackathon/login/') def instagram_login(request): @@ -630,7 +790,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): @@ -644,3 +804,28 @@ 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) + + +def google_login(request): + global profile_track + 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) + +def foursquare_login(request): + global profile_track + profile_track = 'foursquare' + forsquare_url = getFoursquare.get_authorize_url() + return HttpResponseRedirect(forsquare_url) diff --git a/hackathon_starter/hackathon_starter/settings.py b/hackathon_starter/hackathon_starter/settings.py index 81a1770..7c081b5 100644 --- a/hackathon_starter/hackathon_starter/settings.py +++ b/hackathon_starter/hackathon_starter/settings.py @@ -107,40 +107,52 @@ # KEYS # ############ -GITHUB_CLIENT_ID = 'client_id=2404a1e21aebd902f6db' -GITHUB_CLIENT_SECRET = 'client_secret=3da44769d4b7c9465fa4c812669148a163607c23' +GITHUB_CLIENT_ID = 'client_id=' +GITHUB_CLIENT_SECRET = 'client_secret=' -TUMBLR_CONSUMER_KEY = 'KrSbAc9cYLmIgVAn1D21FjRR97QWsutNMxkPDFBxo8CMWtMk4M' -TUMBLR_CONSUMER_SECRET ='lKWMtL2Lj8zr5pY51PVqT8ugeoG0DjrdgoFewM0QTSyJ12jP8d' +TUMBLR_CONSUMER_KEY = '' +TUMBLR_CONSUMER_SECRET ='' -INSTAGRAM_CLIENT_ID = '77dc10b9e3624e908ce437c0a82da92e' -INSTAGRAM_CLIENT_SECRET = '8bcf3139857149aaba7acaa61288427f' +INSTAGRAM_CLIENT_ID = '' +INSTAGRAM_CLIENT_SECRET = '' -GOOGLEMAP_API_KEY = 'AIzaSyA7tttML91EGZ32S_FOOoxu-mbxN9Ojds8' -YAHOO_CONSUMER_KEY = 'dj0yJmk9bUtPVmVpZEczZWp5JmQ9WVdrOWQxbDJkMjFhTmpRbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1iOQ--' -YAHOO_CONSUMER_SECRET = '630e59649caf71255679853ca3f6b0580c571e98' -YAHOO_APP_ID = 'wYvwmZ64' +GOOGLEMAP_API_KEY = '' +YAHOO_CONSUMER_KEY = '' +YAHOO_CONSUMER_SECRET = '' +YAHOO_APP_ID = '' -TWITTER_CONSUMER_KEY = 'MS8DNyi5HX9HhJgigL24VEkqA' -TWITTER_CONSUMER_SECRET = '1QdaLTNyrGIoZUniToou5bqax8mo7yuzIm7o4XjxzMhBE4UPY1' -TWITTER_ACCESS_TOKEN = '43035062-zulNy9FQtEb2i9DeRGQen62HEDf21hpwWcRVAEOOy' -TWITTER_ACCESS_TOKEN_SECRET = 'EEssSDgD4JbXzksmWHW1stBVxNtwfj1nq5Pd2Plkm17wj' +TWITTER_CONSUMER_KEY = '' +TWITTER_CONSUMER_SECRET = '' +TWITTER_ACCESS_TOKEN = '' +TWITTER_ACCESS_TOKEN_SECRET = '' -MEETUP_CONSUMER_KEY = 'p50vftdqq72tgotpaeqk5660un' -MEETUP_CONSUMER_SECRET = 'i5l00ln2r4mcf161n6451hjoj8' +MEETUP_CONSUMER_KEY = '' +MEETUP_CONSUMER_SECRET = '' -BITBUCKET_CONSUMER_KEY = 'nQcSHrjPzaXRq7HjtJ' -BITBUCKET_CONSUMER_SECRET = 'd8XzR8EzgADW9GnyQGb3pZE7rWBtc2RA' +BITBUCKET_CONSUMER_KEY = '' +BITBUCKET_CONSUMER_SECRET = '' -LINKEDIN_CLIENT_ID = '77p43ettu67h56' -LINKEDIN_CLIENT_SECRET = '0NG9XjmS2IWL5pMl' +LINKEDIN_CLIENT_ID = '' +LINKEDIN_CLIENT_SECRET = '' -YELP_CONSUMER_KEY = 'EXMisJNWez_PuR5pr06hyQ' -YELP_CONSUMER_SECRET = 'VCK-4cDjtQ9Ra4HC5ltClNiJFXs' -YELP_TOKEN = 'AWYVs7Vim7mwYyT1BLJA2xhNTs_vXLYS' -YELP_TOKEN_SECRET = 'Rv4GrlYxYGhxUs14s0VBfk7JLJY' +YELP_CONSUMER_KEY = '' +YELP_CONSUMER_SECRET = '' +YELP_TOKEN = '' +YELP_TOKEN_SECRET = '' -POPAPIKEY = 'be4cd251d8a4f1a3362689088bdb0255:0:71947444' -TOPAPIKEY = 'c9655598e1fd4ff591f6d46f2321260e:17:71947444' +POPAPIKEY = '' +TOPAPIKEY = '' -QUANDLAPIKEY = 'fANs6ykrCdAxas7zpMz7' +QUANDLAPIKEY = '' + +FACEBOOK_APP_ID = '' +FACEBOOK_APP_SECRET = '' + +GOOGLE_PLUS_APP_ID = '' +GOOGLE_PLUS_APP_SECRET = '' + +DROPBOX_APP_ID = '' +DROPBOX_APP_SECRET = '' + +FOURSQUARE_APP_ID = '' +FOURSQUARE_APP_SECRET = '' diff --git a/hackathon_starter/hackathon_starter/urls.py b/hackathon_starter/hackathon_starter/urls.py index 6152b0e..5a1257a 100644 --- a/hackathon_starter/hackathon_starter/urls.py +++ b/hackathon_starter/hackathon_starter/urls.py @@ -1,7 +1,9 @@ from django.conf.urls import patterns, include, url from django.contrib import admin +from hackathon import views urlpatterns = patterns('', + url(r'^$', views.index, name='index'), url(r'^hackathon/', include('hackathon.urls')), url(r'^admin/', include(admin.site.urls)), # url(r'^openid/(.*)', SessionConsumer()),