Skip to content

Instantly share code, notes, and snippets.

@chriskief
Created October 24, 2013 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriskief/7131141 to your computer and use it in GitHub Desktop.
Save chriskief/7131141 to your computer and use it in GitHub Desktop.
import urllib2
import urlparse
import time
import json
import re
import oauth2 as oauth
from django.conf import settings
def get_user_data(request):
data = {}
# if we don't have a token yet, get one now
if 'yahoo_access_token' not in request.session:
# set the api URL
url = 'https://api.login.yahoo.com/oauth/v2/get_token'
# required params for yahoo
params = {
'oauth_timestamp': str(int(time.time())),
'oauth_nonce': unicode(csrf(request)['csrf_token']),
'oauth_version': '1.0',
'xoauth_lang_pref': 'en-us',
'oauth_verifier': request.GET['oauth_verifier']
}
# create the consumer and token
consumer = oauth.Consumer(key=settings.YAHOO_CONSUMER_KEY, secret=settings.YAHOO_CONSUMER_SECRET)
token = oauth.Token(key=request.session['yahoo_oauth_token'], secret=request.session['yahoo_oauth_token_secret'])
# create the request
req = oauth.Request(method='GET', url=url, parameters=params)
# sign the request
signature_method = oauth.SignatureMethod_PLAINTEXT()
req.sign_request(signature_method, consumer, token)
# get the request token from yahoo
response = urllib2.urlopen(req.to_url()).read()
# parse the response
params = urlparse.parse_qs(response)
# store the returned values
request.session['yahoo_guid'] = params['xoauth_yahoo_guid'][0]
request.session['yahoo_access_token'] = params['oauth_token'][0]
request.session['yahoo_access_token_secret'] = params['oauth_token_secret'][0]
# set the url using the user id
url = 'http://social.yahooapis.com/v1/user/%s/profile?format=json' % request.session['yahoo_guid']
consumer = oauth.Consumer(key=settings.YAHOO_CONSUMER_KEY, secret=settings.YAHOO_CONSUMER_SECRET)
token = oauth.Token(key=request.session['yahoo_access_token'], secret=request.session['yahoo_access_token_secret'])
# get the user's data from yahoo
client = oauth.Client(consumer, token)
response, content = client.request(url)
# grab the profile from the response
user = json.loads(content)['profile']
# split the name
full_name = user['nickname'].split(' ', 1)
# get the user's info
data['user_id'] = user['guid']
data['username'] = re.sub('[^0-9a-zA-Z]+', '', user['nickname']).lower()
data['email'] = user['emails'][0]['handle'] if 'handle' in user['emails'][0] else ''
data['full_name'] = user['nickname']
data['first_name'] = full_name[0] if len(full_name) > 0 else ''
data['last_name'] = full_name[1] if len(full_name) >= 2 else ''
data['timezone'] = user['timeZone']
data['picture'] = user['image']['imageUrl']
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment