Skip to content

Instantly share code, notes, and snippets.



Created Oct 24, 2013
What would you like to do?
import urllib2
import json
import re
from django.conf import settings
from django.core.urlresolvers import reverse
def get_user_data(request):
data = {}
# if we don't have a token yet, get one now
if 'google_access_token' not in request.session:
# URL to where we will redirect to
redirect_url = settings.SITE_URL + reverse('register_google')
# set the token URL
token_url = ''
# set the post params
params = {
'code': request.GET['code'],
'client_id': settings.GOOGLE_OAUTH2_CLIENT_ID,
'client_secret': settings.GOOGLE_OAUTH2_CLIENT_SECRET,
'redirect_uri': redirect_url,
'grant_type': 'authorization_code'
# grab the token from google
response = urllib2.urlopen(token_url, urllib.urlencode(params)).read()
# parse the response
tokens = json.loads(response)
# save the token
request.session['google_access_token'] = tokens['access_token']
request.session['google_access_token_expires'] = token['expires_in']
# set the api URL using the token we just fetched
api_url = '' \
+ 'access_token=' + request.session['google_access_token']
# get the user's data from google
response = urllib2.urlopen(api_url).read()
user = json.loads(response)
# get the user's info
data['user_id'] = user['id']
data['username'] = re.sub('[^0-9a-zA-Z]+', '', user['email'].split('@')[0]).lower()
data['email'] = user['email']
data['full_name'] = user['name']
data['first_name'] = user['given_name']
data['last_name'] = user['family_name']
data['timezone'] = user['timezone'] if 'timezone' in user else None
data['picture'] = user['picture'] if 'picture' in user else \
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment