Created
May 12, 2011 01:39
-
-
Save pmdarrow/967773 to your computer and use it in GitHub Desktop.
GData OAuth in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.shortcuts import render_to_response | |
from django.core.urlresolvers import reverse | |
from django.http import HttpResponseRedirect | |
import gdata.gauth | |
import gdata.contacts.client | |
CONSUMER_KEY = 'nothx' | |
CONSUMER_SECRET = 'nothx' | |
SCOPE = ['https://www.google.com/m8/feeds/'] | |
DOMAIN = 'nothx' | |
def index(request): | |
client = gdata.contacts.client.ContactsClient(source='sandbox') | |
if 'access_token' in request.session: | |
# User is fully authenticated, use stored token and token secret | |
access = request.session['access_token'] | |
client.auth_token = gdata.gauth.OAuthHmacToken(CONSUMER_KEY, CONSUMER_SECRET, | |
access.token, access.token_secret, gdata.gauth.ACCESS_TOKEN) | |
# Get some contacts and render them | |
contacts = client.GetContacts().entry | |
return render_to_response('index.html', {'contacts': contacts}) | |
else: | |
# User hasn't been authenticated yet, get a request token | |
oauth_callback_url = request.build_absolute_uri(reverse('oauth_callback')) | |
request_token = client.GetOAuthToken(SCOPE, oauth_callback_url, | |
CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) | |
request.session['request_token'] = request_token | |
# Redirect to Google authorization URL | |
return HttpResponseRedirect( | |
request_token.generate_authorization_url(google_apps_domain=DOMAIN)) | |
def oauth_callback(request): | |
# Authorize and upgrade the request token to an access token | |
client = gdata.contacts.client.ContactsClient(source='sandbox') | |
request_token = gdata.gauth.AuthorizeRequestToken( | |
request.session['request_token'], request.build_absolute_uri()) | |
access_token = client.GetAccessToken(request_token) | |
request.session['access_token'] = access_token | |
return HttpResponseRedirect(reverse('index')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment