from urlparse import parse_qs

import requests
from requests_oauthlib import OAuth1 as OAuth

client_key = 'dpf43f3p2l4k3l03'
client_secret = 'kd94hf93k423kf44'

request_token_url = 'http://localhost:5000/oauth/initiate'
authorization_url = 'http://localhost:5000/oauth/authorize'
access_token_url = 'http://localhost:5000/oauth/token'

callback_uri = 'http://localhost:5001/oauth/callback'

email = 'user@test.com'
password = 'password'

def initiate(client_key, client_secret, callback_uri):
  oauth = OAuth(client_key, client_secret, callback_uri=callback_uri)
  r = requests.post(request_token_url, auth=oauth)
  credentials = parse_qs(r.content)
  temporary_key = credentials.get('oauth_token')[0]
  temporary_secret = credentials.get('oauth_token_secret')[0]

  return temporary_key, temporary_secret

def authorize(temporary_key, temporary_secret):
  oauth = OAuth(client_key, client_secret, temporary_key, temporary_secret)
  data = {
    'oauth_token': temporary_key,
    'email': email,
    'password': password
  }
  r = requests.post(authorization_url, data=data, auth=oauth)
  verifier = parse_qs(r.content).get('oauth_verifier')[0]

  return verifier

def callback(client_key, client_secret, temporary_key, temporary_secret, verifier):
  oauth = OAuth(client_key, client_secret, temporary_key, temporary_secret, verifier=verifier)
  r = requests.post(access_token_url, auth=oauth)
  credentials = parse_qs(r.content)
  access_key = credentials.get('oauth_token')[0]
  access_secret = credentials.get('oauth_token_secret')[0]

  return access_key, access_secret

if __name__ == '__main__':
  temporary_key, temporary_secret = initiate(client_key, client_secret, callback_uri)
  verifier = authorize(temporary_key, temporary_secret)
  access_key, access_secret = callback(client_key, client_secret, temporary_key, temporary_secret, verifier)
  print access_key, access_secret

