Commit a304de7e authored by Josh Roesslein's avatar Josh Roesslein
Browse files

Implemented new pluggable auth system into binder. Implemented basic auth...

Implemented new pluggable auth system into binder. Implemented basic auth handler. Started work on oauth handler.
parent 6f65be77
...@@ -11,6 +11,7 @@ from models import * ...@@ -11,6 +11,7 @@ from models import *
from error import TweepError from error import TweepError
from api import API from api import API
from cache import * from cache import *
from auth import BasicAuthHandler, OAuthHandler
# Global, unauthenticated instance of API # Global, unauthenticated instance of API
api = API() api = API()
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
# Copyright 2009 Joshua Roesslein # Copyright 2009 Joshua Roesslein
# See LICENSE # See LICENSE
import base64
from binder import bind_api from binder import bind_api
from parsers import * from parsers import *
from models import User, Status, DirectMessage, Friendship, SavedSearch, SearchResult from models import User, Status, DirectMessage, Friendship, SavedSearch, SearchResult
...@@ -12,24 +10,15 @@ from error import TweepError ...@@ -12,24 +10,15 @@ from error import TweepError
"""Twitter API""" """Twitter API"""
class API(object): class API(object):
def __init__(self, username=None, password=None, host='twitter.com', def __init__(self, auth_handler=None, host='twitter.com', cache=None,
cache=None, secure=False, secure=False, classes={'user': User, 'status': Status,
classes={'user': User, 'status': Status,
'direct_message': DirectMessage, 'friendship': Friendship, 'direct_message': DirectMessage, 'friendship': Friendship,
'saved_search': SavedSearch, 'search_result': SearchResult}): 'saved_search': SavedSearch, 'search_result': SearchResult}):
if username and password: self.auth_handler = auth_handler
self.set_credentials(username, password)
else:
self._b64up = None
self.host = host self.host = host
self.cache = cache self.cache = cache
self.secure = secure self.secure = secure
self.classes = classes self.classes = classes
self.username = username
def set_credentials(self, username, password):
self._b64up = base64.b64encode('%s:%s' % (username, password))
self.username = username
"""Get public timeline""" """Get public timeline"""
public_timeline = bind_api( public_timeline = bind_api(
......
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
from urllib2 import Request, urlopen
import base64
import oauth
from error import TweepError
class AuthHandler(object):
def apply_auth(self, headers):
"""Apply authentication headers to request"""
raise NotImplemented
class BasicAuthHandler(AuthHandler):
def __init__(self, username, password):
self._b64up = base64.b64encode('%s:%s' % (username, password))
def apply_auth(self, headers):
headers['Authorization'] = 'Basic %s' % self._b64up
"""OAuth authentication handler"""
class OAuthHandler(AuthHandler):
REQUEST_TOKEN_URL = 'http://twitter.com/oauth/request_token'
AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
ACCESS_TOKEN_URL = 'http://twitter.com/oauth/access_token'
def __init__(self, consumer_key, consumer_secrete):
self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secrete)
self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.request_token = None
self.access_token = None
def _get_request_token(self):
try:
request = oauth.OAuthRequest.from_consumer_and_token(self._consumer, http_url = self.REQUEST_TOKEN_URL)
request.sign_request(self._sigmethod, self._consumer, None)
resp = urlopen(Request(self.REQUEST_TOKEN_URL, headers=request.to_header()))
return oauth.OAuthToken.from_string(resp.read())
except Exception, e:
raise TweepError(e)
def get_authorization_url(self, callback=None):
try:
# get the request token
self.request_token = self._get_request_token()
# build auth request and return as url
request = oauth.OAuthRequest.from_token_and_callback(
token=token, callback=callback, http_url=self.AUTHORIZATION_URL)
return request.to_url()
except Exception, e:
raise TweepError(e)
def get_access_token(self):
try:
# build request
request = oauth.OAuthRequest.from_consumer_and_token(self._consumer,
token=self.request_token, http_url=self.ACCESS_TOKEN_URL)
request.sign_request(self._sigmethod, self._consumer, self.request_token)
# send request
resp = urlopen(Request(self.ACCESS_TOKEN_URL, headers=request.to_header()))
self.access_token = oauth.OAuthToken.from_string(resp.read())
except Exception, e:
raise TweepError(e)
...@@ -13,7 +13,7 @@ def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False, ...@@ -13,7 +13,7 @@ def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False,
def _call(api, *args, **kargs): def _call(api, *args, **kargs):
# If require auth, throw exception if credentials not provided # If require auth, throw exception if credentials not provided
if require_auth and not api._b64up: if not api.auth_handler:
raise TweepError('Authentication required!') raise TweepError('Authentication required!')
# Filter out unallowed parameters # Filter out unallowed parameters
...@@ -50,8 +50,10 @@ def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False, ...@@ -50,8 +50,10 @@ def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False,
headers = { headers = {
'User-Agent': 'tweepy' 'User-Agent': 'tweepy'
} }
if api._b64up:
headers['Authorization'] = 'Basic %s' % api._b64up # Apply authentication
if api.auth_handler:
api.auth_handler.apply_auth(headers)
# Build request # Build request
conn.request(method, url, headers=headers) conn.request(method, url, headers=headers)
......
...@@ -8,7 +8,7 @@ Tweepy exception ...@@ -8,7 +8,7 @@ Tweepy exception
class TweepError(Exception): class TweepError(Exception):
def __init__(self, reason): def __init__(self, reason):
self.reason = reason self.reason = str(reason)
def __str__(self): def __str__(self):
return self.reason return self.reason
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment